"""TypeSafe AI's tools as an MCP server over stdio: each call asks Ivy's decisions endpoint,
which answers with Jev on Ivy's TypeSafe AI account. Standard library only: the sandbox
installs nothing."""

import http.client
import json
import math
import os
import socket
import sys
import threading
import urllib.parse
from pathlib import Path

PROTOCOL_VERSION = "2025-06-18"
# The endpoint waits up to 55 s for Jev.
TIMEOUT_SECONDS = 70
HERE = Path(__file__).resolve().parent
# Agents read each tool's description from the app's manifest, not from this list.
TOOLS = [
    {
        "name": name,
        "inputSchema": json.loads((HERE / "tools" / f"{name}.json").read_text("utf-8")),
    }
    for name in ("decide", "choose", "score")
]

write_lock = threading.Lock()


class ToolError(Exception):
    pass


class UnixConnection(http.client.HTTPConnection):
    def __init__(self, address):
        super().__init__("ivy-api", timeout=TIMEOUT_SECONDS)
        self.address = address

    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.settimeout(self.timeout)
        self.sock.connect(self.address)


def connection():
    url = os.environ.get("IVY_API_URL", "")
    if url.startswith("@"):
        return UnixConnection("\0" + url[1:])
    if url.startswith("/"):
        return UnixConnection(url)
    parts = urllib.parse.urlsplit(url)
    if parts.scheme == "http" and parts.hostname:
        return http.client.HTTPConnection(parts.hostname, parts.port, timeout=TIMEOUT_SECONDS)
    raise ToolError("this app can't reach Ivy here (no IVY_API_URL)")


def decisions_path():
    ids = [
        urllib.parse.quote(os.environ.get(name, ""), safe="")
        for name in ("IVY_ORGANISATION_ID", "IVY_WORKSPACE_ID", "IVY_APP_ID", "IVY_INSTANCE_ID")
    ]
    return "/v1/organisations/{}/workspaces/{}/apps/{}/instances/{}/decisions".format(*ids)


def ask(state, question):
    body = json.dumps({"state": state, "questions": [{"id": "answer", **question}]}).encode()
    conn = connection()
    try:
        conn.request(
            "POST",
            decisions_path(),
            body=body,
            headers={"Content-Type": "application/json", "Content-Length": str(len(body))},
        )
        response = conn.getresponse()
        text = response.read().decode("utf-8", "replace")
    except (OSError, http.client.HTTPException) as error:
        raise ToolError(f"Ivy didn't answer: {error!r}") from None
    finally:
        conn.close()
    try:
        answer = json.loads(text)
    except ValueError:
        answer = {}
    if response.status != 200:
        error = answer.get("error", {}) if isinstance(answer, dict) else {}
        code = error.get("code", f"http_{response.status}")
        raise ToolError(f"{code}: {error.get('message', 'the decision failed')}")
    return answer["answers"][0], answer.get("model")


def decide(args):
    answer, model = ask(
        args["state"],
        {"kind": "boolean", "prompt": args["question"], "options": None, "scale": None},
    )
    return {
        "answer": answer["value"],
        "probability_yes": answer["probability"],
        "confidence": answer["confidence"],
        "model": model,
    }


def choose(args):
    answer, model = ask(
        args["state"],
        {"kind": "choice", "prompt": args["question"], "options": args["options"], "scale": None},
    )
    return {
        "choice": answer["value"],
        "probability": answer["probability"],
        "confidence": answer["confidence"],
        "probabilities": answer["probabilities"],
        "model": model,
    }


def score(args):
    scale = args["scale"]
    answer, model = ask(
        args["state"],
        {"kind": "score", "prompt": args["question"], "options": None, "scale": scale},
    )
    nearest = min(max(math.floor(answer["value"] + 0.5), 0), len(scale) - 1)
    return {
        "score": answer["value"],
        "level": scale[nearest],
        "confidence": answer["confidence"],
        "probabilities": answer["probabilities"],
        "model": model,
    }


HANDLERS = {"decide": decide, "choose": choose, "score": score}


def send(message):
    line = json.dumps(message, ensure_ascii=False) + "\n"
    with write_lock:
        sys.stdout.write(line)
        sys.stdout.flush()


def call_tool(request_id, params):
    handler = HANDLERS.get(params.get("name"))
    try:
        if handler is None:
            raise ToolError(f"no tool {params.get('name')!r}")
        result = handler(params.get("arguments") or {})
        content, is_error = json.dumps(result, ensure_ascii=False), False
    except ToolError as error:
        content, is_error = str(error), True
    except (KeyError, TypeError, ValueError) as error:
        content, is_error = f"unexpected input or answer: {error!r}", True
    send(
        {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {"content": [{"type": "text", "text": content}], "isError": is_error},
        }
    )


def handle(message):
    method, request_id = message.get("method"), message.get("id")
    if request_id is None:
        return
    if method == "tools/call":
        threading.Thread(
            target=call_tool, args=(request_id, message.get("params") or {}), daemon=True
        ).start()
        return
    if method == "initialize":
        result = {
            "protocolVersion": PROTOCOL_VERSION,
            "capabilities": {"tools": {}},
            "serverInfo": {"name": "typesafe", "version": "1.0.0"},
        }
    elif method == "tools/list":
        result = {"tools": TOOLS}
    elif method == "ping":
        result = {}
    else:
        send(
            {
                "jsonrpc": "2.0",
                "id": request_id,
                "error": {"code": -32601, "message": f"no method {method!r}"},
            }
        )
        return
    send({"jsonrpc": "2.0", "id": request_id, "result": result})


def main():
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            message = json.loads(line)
        except ValueError:
            continue
        if isinstance(message, dict):
            handle(message)


if __name__ == "__main__":
    main()
