"""A minimal MCP client for jifto's agent server, with the Python standard library only.

    from jifto_mcp import Jifto
    jifto = Jifto()                      # finds the running Rhino, or JIFTO_MCP_URL / JIFTO_MCP_TOKEN
    status = jifto.call("jifto_status")
    ids = jifto.call("jifto_geometry", action="add", items=[{"kind": "box", "min": [0, 0, 0], "max": [10, 10, 9]}])

A tool that fails raises JiftoError with jifto's message and what to do instead.
"""
import glob
import json
import os
import socket
import urllib.error
import urllib.request


class JiftoError(RuntimeError):
    """A tool call jifto refused or could not do; .reply holds jifto's whole answer."""

    def __init__(self, tool, reply):
        self.reply = reply
        text = reply.get("error") or reply.get("message") or json.dumps(reply)
        if reply.get("fix"):
            text += " | fix: " + reply["fix"]
        super().__init__(f"{tool}: {text}")


class Jifto:
    def __init__(self, url=None, token=None, timeout=900):
        folder = os.path.join(os.environ.get("APPDATA", ""), "jifto", "agents")
        self.url = url or os.environ.get("JIFTO_MCP_URL") or self._find_url(folder)
        self.token = token or os.environ.get("JIFTO_MCP_TOKEN") or open(os.path.join(folder, "token"), encoding="utf-8").read().strip()
        self.timeout = timeout
        self.session = None
        self._id = 0
        init = self._send("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
                                         "clientInfo": {"name": "jifto_mcp.py", "version": "1"}})
        self.instructions = init.get("result", {}).get("instructions", "")
        self._notify("notifications/initialized")

    @staticmethod
    def _find_url(folder):
        # The newest Rhino whose server answers; a Rhino that crashed may have left its file behind.
        instances = sorted(glob.glob(os.path.join(folder, "instances", "*.json")), key=os.path.getmtime, reverse=True)
        for path in instances:
            try:
                with open(path, encoding="utf-8") as f:
                    info = json.load(f)
                with socket.create_connection(("localhost", int(info["port"])), timeout=2):
                    return info["url"]
            except (OSError, ValueError, KeyError):
                continue
        return "http://localhost:47110/mcp"

    def _request(self, body):
        data = json.dumps(body).encode("utf-8")
        request = urllib.request.Request(self.url, data=data, method="POST", headers={
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "Authorization": "Bearer " + self.token})
        if self.session:
            request.add_header("Mcp-Session-Id", self.session)
        with urllib.request.urlopen(request, timeout=self.timeout) as response:
            self.session = response.headers.get("Mcp-Session-Id") or self.session
            text = response.read().decode("utf-8")
            return json.loads(text) if text else None

    def _send(self, method, params=None):
        self._id += 1
        body = {"jsonrpc": "2.0", "id": self._id, "method": method}
        if params is not None:
            body["params"] = params
        return self._request(body)

    def _notify(self, method):
        self._request({"jsonrpc": "2.0", "method": method})

    def call(self, tool, **arguments):
        """Calls a jifto tool; returns its JSON reply, or raises JiftoError when it failed."""
        response = self._send("tools/call", {"name": tool, "arguments": arguments})
        if "error" in response:
            raise JiftoError(tool, response["error"])
        result = response["result"]
        text = next((c["text"] for c in result["content"] if c["type"] == "text"), "{}")
        reply = json.loads(text)
        if result.get("isError") or reply.get("ok") is False:
            raise JiftoError(tool, reply)
        return reply

    def batch(self, *calls, stop_on_error=True):
        """Runs (tool, arguments) pairs in one request; returns each call's reply."""
        reply = self.call("jifto_batch", calls=[{"tool": t, "arguments": a} for t, a in calls], stop_on_error=stop_on_error)
        return [r["reply"] for r in reply["replies"]]
