"""
A "search and call" MCP server for a large REST API, without running model-written code.

The model sees two tools, whatever the size of the API:
  - search_operations: find operations in the OpenAPI spec and return only their schemas
  - call_operation:     call one operation by operationId, validated against the spec

Requires: Python 3.11+, mcp>=2.0, httpx, jsonschema
Run:      OPENAPI_SPEC=./openapi.json API_BASE_URL=https://api.example.com API_TOKEN=... \
          python server.py
"""

from __future__ import annotations

import json
import math
import os
import re
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import quote

import httpx
import jsonschema
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations

MAX_RESULT_CHARS = 8_000          # cap what goes back into the model's context
ALLOW_WRITES = os.getenv("ALLOW_WRITES", "false").lower() == "true"
READ_METHODS = {"get", "head"}


@dataclass
class Operation:
    operation_id: str
    method: str
    path: str
    summary: str
    tags: list[str]
    parameters: list[dict[str, Any]]
    body_schema: dict[str, Any] | None
    search_text: str = field(repr=False, default="")


def _tokens(text: str) -> set[str]:
    return set(re.findall(r"[a-z0-9]+", text.lower()))


def _validate(value: Any, schema: dict[str, Any], label: str) -> None:
    # Validation errors go back to the model as tool errors so it can correct itself.
    try:
        jsonschema.validate(value, schema)
    except jsonschema.ValidationError as exc:
        raise ToolError(f"Invalid {label}: {exc.message}") from None


def resolve_refs(node: Any, root: dict[str, Any], seen: tuple[str, ...] = ()) -> Any:
    """Inline local $refs so every schema the model sees is self-contained."""
    if isinstance(node, dict):
        ref = node.get("$ref")
        if isinstance(ref, str) and ref.startswith("#/"):
            if ref in seen:                      # recursive schema: stop expanding
                return {"type": "object"}
            target: Any = root
            for part in ref[2:].split("/"):
                target = target[part.replace("~1", "/").replace("~0", "~")]
            return resolve_refs(target, root, seen + (ref,))
        return {k: resolve_refs(v, root, seen) for k, v in node.items()}
    if isinstance(node, list):
        return [resolve_refs(v, root, seen) for v in node]
    return node


def load_operations(spec: dict[str, Any]) -> dict[str, Operation]:
    """Flatten an OpenAPI 3.x document into one record per operation."""
    spec = {"paths": resolve_refs(spec.get("paths", {}), spec)}
    ops: dict[str, Operation] = {}
    for path, item in spec.get("paths", {}).items():
        shared = item.get("parameters", [])
        for method, op in item.items():
            if method not in {"get", "post", "put", "patch", "delete", "head"}:
                continue
            body = (
                op.get("requestBody", {})
                .get("content", {})
                .get("application/json", {})
                .get("schema")
            )
            record = Operation(
                operation_id=op["operationId"],
                method=method,
                path=path,
                summary=op.get("summary", ""),
                tags=op.get("tags", []),
                parameters=shared + op.get("parameters", []),
                body_schema=body,
            )
            record.search_text = " ".join(
                [record.operation_id, path, record.summary, " ".join(record.tags),
                 op.get("description", "")]
            )
            ops[record.operation_id] = record
    return ops


def build_index(operations: dict[str, Operation]):
    """Weight rare words above common ones (IDF), and the summary and id above the
    long description, so "list pull requests" finds pulls/list, not every list call."""
    docs = {
        op_id: (_tokens(op.operation_id + " " + op.summary), _tokens(op.search_text))
        for op_id, op in operations.items()
    }
    df: dict[str, int] = {}
    for strong, weak in docs.values():
        for tok in strong | weak:
            df[tok] = df.get(tok, 0) + 1
    n = len(docs)
    idf = {tok: math.log(1 + n / count) for tok, count in df.items()}

    def score(op_id: str, query_tokens: set[str]) -> float:
        strong, weak = docs[op_id]
        return sum(idf.get(t, 0.0) * (2.0 if t in strong else 1.0 if t in weak else 0.0)
                   for t in query_tokens)

    return score


def create_server(spec: dict[str, Any], http: httpx.Client) -> MCPServer:
    operations = load_operations(spec)
    score_op = build_index(operations)
    mcp = MCPServer(
        name="api-search-call",
        instructions=(
            "Call search_operations first to find the operationId and its parameters, "
            "then call call_operation with exactly those parameters."
        ),
    )

    @mcp.tool(annotations=ToolAnnotations(read_only_hint=True))
    def search_operations(query: str, tag: str | None = None, limit: int = 5) -> list[dict]:
        """Search the API's operations by keywords (for example "list open invoices").
        Returns operationId, method, path, summary and the parameter schema of the
        best matches. Use the returned operationId with call_operation."""
        wanted = _tokens(query)
        scored = []
        for op in operations.values():
            if tag and tag not in op.tags:
                continue
            score = score_op(op.operation_id, wanted)
            if score > 0:
                scored.append((score, op))
        scored.sort(key=lambda pair: (-pair[0], pair[1].operation_id))
        return [
            {
                "operationId": op.operation_id,
                "method": op.method.upper(),
                "path": op.path,
                "summary": op.summary,
                "parameters": [
                    {"name": p["name"], "in": p["in"], "required": p.get("required", False),
                     "schema": p.get("schema", {})}
                    for p in op.parameters
                ],
                "body": op.body_schema,
                "readOnly": op.method in READ_METHODS,
            }
            for _, op in scored[: max(1, min(limit, 10))]
        ]

    @mcp.tool(annotations=ToolAnnotations(read_only_hint=False, destructive_hint=True))
    def call_operation(
        operation_id: str,
        path_params: dict[str, Any] | None = None,
        query: dict[str, Any] | None = None,
        body: dict[str, Any] | None = None,
    ) -> dict:
        """Call one API operation found with search_operations. Arguments are
        validated against the API spec before any request is sent."""
        op = operations.get(operation_id)
        if op is None:
            raise ToolError(f"Unknown operationId '{operation_id}'. Use search_operations.")
        if op.method not in READ_METHODS and not ALLOW_WRITES:
            raise ToolError(f"'{operation_id}' changes data and writes are disabled on this server.")

        path_params, query = path_params or {}, query or {}
        for p in op.parameters:
            source = path_params if p["in"] == "path" else query if p["in"] == "query" else None
            if source is None:
                continue
            if p.get("required") and p["name"] not in source:
                raise ToolError(f"Missing required {p['in']} parameter '{p['name']}'.")
            if p["name"] in source and "schema" in p:
                _validate(source[p["name"]], p["schema"], f"{p['in']} parameter '{p['name']}'")
        if op.body_schema is not None:
            _validate(body or {}, op.body_schema, "request body")

        url = op.path
        for name, value in path_params.items():
            url = url.replace("{" + name + "}", quote(str(value), safe=""))
        if "{" in url:
            raise ToolError(f"Unresolved path parameters in {url}.")

        response = http.request(op.method.upper(), url, params=query,
                                json=body if op.body_schema is not None else None)
        text = response.text
        truncated = len(text) > MAX_RESULT_CHARS
        try:
            payload: Any = json.loads(text) if not truncated else text[:MAX_RESULT_CHARS]
        except json.JSONDecodeError:
            payload = text[:MAX_RESULT_CHARS]
        return {"status": response.status_code, "truncated": truncated, "data": payload}

    return mcp


if __name__ == "__main__":
    with open(os.environ["OPENAPI_SPEC"], encoding="utf-8") as fh:
        spec = json.load(fh)
    client = httpx.Client(
        base_url=os.environ["API_BASE_URL"],
        headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"},  # never shown to the model
        timeout=15.0,
    )
    create_server(spec, client).run()  # stdio by default
