"""Exercise server.py end to end through a real MCP client, against a mocked upstream API."""

import asyncio
import json

import httpx
from mcp import Client

import server


def make_spec(extra_ops: int = 0) -> dict:
    paths = {
        "/invoices": {
            "get": {
                "operationId": "listInvoices", "summary": "List invoices", "tags": ["billing"],
                "parameters": [{"name": "status", "in": "query", "required": False,
                                "schema": {"type": "string", "enum": ["open", "paid"]}}],
            },
            "post": {
                "operationId": "createInvoice", "summary": "Create an invoice", "tags": ["billing"],
                "requestBody": {"content": {"application/json": {"schema": {
                    "type": "object", "required": ["customer_id", "amount"],
                    "properties": {"customer_id": {"type": "string"},
                                   "amount": {"type": "number", "minimum": 0}}}}}},
            },
        },
        "/invoices/{invoice_id}": {
            "get": {
                "operationId": "getInvoice", "summary": "Get one invoice by id", "tags": ["billing"],
                "parameters": [{"name": "invoice_id", "in": "path", "required": True,
                                "schema": {"type": "string"}}],
            }
        },
    }
    for i in range(extra_ops):  # simulate a large API surface
        paths[f"/resource{i}/{{id}}"] = {"get": {
            "operationId": f"getResource{i}", "summary": f"Get resource {i} by id",
            "tags": [f"product{i % 40}"],
            "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "string"}},
                           {"name": "expand", "in": "query", "schema": {"type": "string"}}]}}
    return {"openapi": "3.1.0", "paths": paths}


def upstream(request: httpx.Request) -> httpx.Response:
    assert request.headers["authorization"] == "Bearer test-token"
    if request.url.path == "/invoices":
        return httpx.Response(200, json=[{"id": "inv_1", "status": request.url.params.get("status")}])
    if request.url.path == "/invoices/inv%2F1" or request.url.path.startswith("/invoices/"):
        return httpx.Response(200, json={"id": request.url.raw_path.decode().rsplit("/", 1)[1]})
    return httpx.Response(404)


async def main() -> None:
    http = httpx.Client(base_url="https://api.test", transport=httpx.MockTransport(upstream),
                        headers={"Authorization": "Bearer test-token"})
    mcp = server.create_server(make_spec(), http)

    async with Client(mcp) as client:
        tools = await client.list_tools()
        names = sorted(t.name for t in tools.tools)
        assert names == ["call_operation", "search_operations"], names

        found = await client.call_tool("search_operations", {"query": "list open invoices"})
        top = json.loads(found.content[0].text)
        print("search top hit:", top["operationId"] if isinstance(top, dict) else top)

        ok = await client.call_tool("call_operation",
                                    {"operation_id": "listInvoices", "query": {"status": "open"}})
        print("list:", ok.content[0].text)

        enc = await client.call_tool("call_operation",
                                     {"operation_id": "getInvoice", "path_params": {"invoice_id": "inv/1"}})
        print("path encoding:", enc.content[0].text)

        bad = await client.call_tool("call_operation",
                                     {"operation_id": "listInvoices", "query": {"status": "void"}})
        print("bad enum -> isError:", bad.is_error, "|", bad.content[0].text)

        write = await client.call_tool("call_operation",
                                       {"operation_id": "createInvoice", "body": {"customer_id": "c1", "amount": 5}})
        print("write blocked -> isError:", write.is_error, "|", write.content[0].text[:90])

        missing = await client.call_tool("call_operation", {"operation_id": "getInvoice"})
        print("missing path param -> isError:", missing.is_error, "|", missing.content[0].text)


if __name__ == "__main__":
    asyncio.run(main())
