# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Tomasz Głuc
"""Smallest useful OmniDAW API client: no dependencies, just sockets and JSON."""
import json, os, socket, sys
from pathlib import Path

if sys.platform == "win32":
    config = Path(os.environ["APPDATA"]) / "omni"
elif sys.platform == "darwin":
    config = Path.home() / "Library" / "Application Support" / "omni"
else:
    config = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "omni"

endpoint = json.loads((config / "api" / "endpoint.json").read_text())
sock = socket.create_connection((endpoint["host"], endpoint["port"]))
stream = sock.makefile("rw", encoding="utf-8", newline="\n")
next_id = 0


def call(method, params=None):
    global next_id
    next_id += 1
    stream.write(json.dumps({"jsonrpc": "2.0", "id": next_id, "method": method, "params": params or {}}) + "\n")
    stream.flush()
    reply = json.loads(stream.readline())
    if "error" in reply:
        raise RuntimeError(f"{method}: {reply['error']['code']} {reply['error']['message']}")
    return reply["result"]


call("api.hello", {"token": endpoint["token"], "api_version": "0.21.0",
                   "client": {"name": "raw-example", "version": "1.0"}})
print(call("session.info"))
print([t["name"] for t in call("tracks.list")])
