"""Exercise real SDK discovery and calls with an entirely synthetic HTTP transport."""
import asyncio
from datetime import timedelta
import json

import httpx
from mcp.shared.memory import create_connected_server_and_client_session

from http_api_client import ArtifactClient, ID_PATTERN
from http_api_tool import make_server


async def main():
    requests = []

    def handler(request: httpx.Request) -> httpx.Response:
        requests.append(str(request.url))
        if request.url.path.endswith("KIT-43"):
            return httpx.Response(404, text="private upstream diagnostic")
        return httpx.Response(200, json={"item_id": "KIT-42", "title": "Demo kit", "status": "ready"})

    async with httpx.AsyncClient(transport=httpx.MockTransport(handler), trust_env=False) as http:
        server = make_server(ArtifactClient(http))
        async with create_connected_server_and_client_session(
            server, read_timeout_seconds=timedelta(seconds=5), raise_exceptions=True
        ) as session:
            tools = await session.list_tools()
            tool = next(tool for tool in tools.tools if tool.name == "get_artifact")
            assert tool.inputSchema["properties"]["item_id"]["pattern"] == ID_PATTERN
            assert "item_id" in tool.inputSchema["required"]
            assert tool.outputSchema is not None
            assert {"item_id", "title", "status"} <= set(tool.outputSchema["required"])
            success = await session.call_tool("get_artifact", {"item_id": "KIT-42"})
            assert not success.isError
            assert success.structuredContent == {"item_id": "KIT-42", "title": "Demo kit", "status": "ready"}
            missing = await session.call_tool("get_artifact", {"item_id": "KIT-43"})
            assert missing.isError
            assert "NOT_FOUND" in missing.content[0].text
            before = len(requests)
            invalid = await session.call_tool("get_artifact", {"item_id": "../secret"})
            assert invalid.isError and len(requests) == before
            print(json.dumps({"tool": tool.name, "success": success.structuredContent, "not_found_is_error": missing.isError, "invalid_input_http_requests": len(requests) - before}, ensure_ascii=False))
    assert http.is_closed
    print("PASS: real SDK list/call, mocked HTTP, client closed")


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