"""Python 3.10+. pip install -r requirements.txt; set AMAZINGCAT_TOKEN."""
import asyncio
import json
import os
from datetime import timedelta

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client


async def main():
    # Keep the token on your server. Never embed it in a browser bundle.
    async with httpx.AsyncClient(
        headers={"Authorization": f"Bearer {os.environ['AMAZINGCAT_TOKEN']}"},
        timeout=httpx.Timeout(120.0, connect=15.0),
    ) as http:
        async with streamable_http_client(
            "https://mcp.amazingcat.net/mcp", http_client=http
        ) as (read, write, session_id):
            async with ClientSession(
                read, write, read_timeout_seconds=timedelta(seconds=120)
            ) as session:
                # initialize() also sends notifications/initialized.
                # The transport handles session/version headers and JSON/SSE.
                initialized = await session.initialize()
                tools = await session.list_tools()
                if not any(tool.name == "find_term" for tool in tools.tools):
                    raise RuntimeError("find_term is unavailable for this token")
                result = await session.call_tool(
                    "find_term", {"phrase": "банкротство", "court": "КС", "limit": 1, "detail": "compact"}
                )
                if result.isError:
                    raise RuntimeError("Tool returned an MCP error; inspect it privately")
                text = next((b.text for b in result.content if b.type == "text"), None)
                # HTTP 200 does not by itself prove success: plain text can be a quota error.
                if text is None:
                    raise RuntimeError("Tool returned no text content")
                try:
                    data = json.loads(text)
                except json.JSONDecodeError:
                    raise RuntimeError("Tool returned non-JSON text; check quota/errors") from None
                if not isinstance(data, dict) or data.get("error") or data.get("ошибка"):
                    raise RuntimeError("Tool returned an application error")
                # Print counters, avoiding personal names in the sample output.
                print(json.dumps({
                    "protocol_version": initialized.protocolVersion,
                    "session_present": bool(session_id()),
                    "tools_count": len(tools.tools),
                    "tool": "find_term", "is_error": bool(result.isError),
                    "найдено": data.get("найдено"),
                    "returned": len(data.get("results", [])),
                }, ensure_ascii=False))
        # terminate_on_close=True (the default) sends DELETE for the MCP session.


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