"""Build MCP tool lists for an OpenAPI spec in three shapes and write them as JSON for token counting.

usage: python -I build_tool_lists.py <spec.json> <outdir> <path-to-mcp-example>
"""
import asyncio
import copy
import json
import sys

spec_path, outdir, example_dir = sys.argv[1], sys.argv[2], sys.argv[3]
spec = json.load(open(spec_path, encoding="utf-8"))


def resolve(node, seen=()):
    """Inline local $refs, stopping at cycles."""
    if isinstance(node, dict):
        if "$ref" in node and isinstance(node["$ref"], str) and node["$ref"].startswith("#/"):
            ref = node["$ref"]
            if ref in seen:
                return {"type": "object"}
            target = spec
            for part in ref[2:].split("/"):
                target = target[part.replace("~1", "/").replace("~0", "~")]
            return resolve(copy.deepcopy(target), seen + (ref,))
        return {k: resolve(v, seen) for k, v in node.items()}
    if isinstance(node, list):
        return [resolve(v, seen) for v in node]
    return node


full_tools, required_tools, ops_count = [], [], 0
for path, item in spec["paths"].items():
    shared = item.get("parameters", [])
    for method, op in item.items():
        if method not in {"get", "post", "put", "patch", "delete", "head"}:
            continue
        ops_count += 1
        params = [resolve(p) for p in shared + op.get("parameters", [])]
        body = resolve(op.get("requestBody", {})).get("content", {}).get("application/json", {}).get("schema")
        props, req = {}, []
        for p in params:
            if p.get("in") in ("path", "query"):
                props[p["name"]] = {**p.get("schema", {}), "description": p.get("description", "")}
                if p.get("required"):
                    req.append(p["name"])
        if body:
            props["body"] = body
            if op.get("requestBody", {}).get("required"):
                req.append("body")
        name = op.get("operationId", f"{method}_{path}").replace("/", "_")[:64]
        desc = (op.get("summary", "") + ". " + op.get("description", "")).strip()
        full_tools.append({"name": name, "description": desc,
                           "inputSchema": {"type": "object", "properties": props, "required": req}})
        required_tools.append({"name": name, "description": op.get("summary", ""),
                               "inputSchema": {"type": "object",
                                               "properties": {k: {"type": props[k].get("type", "object")} for k in req},
                                               "required": req}})

json.dump(full_tools, open(f"{outdir}/full.json", "w"))
json.dump(required_tools, open(f"{outdir}/required.json", "w"))

# The two-tool server's real tools/list output, plus sample search results
sys.path.insert(0, example_dir)
import httpx  # noqa: E402
from mcp import Client  # noqa: E402
import server  # noqa: E402

resolved_spec = {"paths": resolve(spec["paths"])}


async def two_tool():
    mcp = server.create_server(spec, httpx.Client(base_url="https://api.github.com"))
    async with Client(mcp) as c:
        tools = await c.list_tools()
        json.dump([t.model_dump(mode="json", by_alias=True, exclude_none=True) for t in tools.tools],
                  open(f"{outdir}/two_tool.json", "w"))
        samples = {}
        for q in ["list pull requests for a repository", "create an issue comment",
                  "get the latest release", "list workflow runs for a repository"]:
            r = await c.call_tool("search_operations", {"query": q, "limit": 3})
            samples[q] = [json.loads(x.text) for x in r.content]
        json.dump(samples, open(f"{outdir}/search_samples.json", "w"))

asyncio.run(two_tool())
print(json.dumps({"operations": ops_count}))
