# -*- coding: utf-8 -*-
"""Minimal stdio JSON-RPC client for `figcraft-cli mcp`."""
import json
import subprocess
import sys
import threading

EXE = r"C:\Program Files\FigCraft\figcraft-cli.exe"


class Mcp:
    def __init__(self, roots=()):
        args = [EXE, "mcp"]
        for r in roots:
            args += ["--automation-write-root", r]
        self.p = subprocess.Popen(args, stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE, text=True,
                                  encoding="utf-8", bufsize=1)
        self._id = 0
        threading.Thread(target=self._drain, daemon=True).start()

    def _drain(self):
        for line in self.p.stderr:
            sys.stderr.write("[mcp] " + line)

    def call(self, method, params=None, timeout=180):
        self._id += 1
        msg = {"jsonrpc": "2.0", "id": self._id, "method": method}
        if params is not None:
            msg["params"] = params
        self.p.stdin.write(json.dumps(msg) + "\n")
        self.p.stdin.flush()
        while True:
            line = self.p.stdout.readline()
            if not line:
                raise RuntimeError("mcp server closed")
            line = line.strip()
            if not line:
                continue
            try:
                d = json.loads(line)
            except json.JSONDecodeError:
                continue
            if d.get("id") == self._id:
                return d

    def notify(self, method, params=None):
        msg = {"jsonrpc": "2.0", "method": method}
        if params is not None:
            msg["params"] = params
        self.p.stdin.write(json.dumps(msg) + "\n")
        self.p.stdin.flush()

    def tool(self, name, args):
        r = self.call("tools/call", {"name": name, "arguments": args})
        res = r.get("result", r)
        out = res.get("content", [{}])
        texts = [c.get("text", "") for c in out if c.get("type") == "text"]
        joined = "\n".join(texts)
        try:
            return json.loads(joined)
        except Exception:
            return joined

    def close(self):
        try:
            self.p.stdin.close()
        except Exception:
            pass
        self.p.terminate()


def connect(roots=()):
    m = Mcp(roots)
    m.call("initialize", {"protocolVersion": "2024-11-05",
                          "capabilities": {},
                          "clientInfo": {"name": "paygo", "version": "1"}})
    m.notify("notifications/initialized")
    return m


if __name__ == "__main__":
    m = connect()
    r = m.call("tools/list")
    for t in r.get("result", {}).get("tools", []):
        print(t["name"], "-", (t.get("description") or "")[:110])
    m.close()
