"""Local, read-only MCP exercise. Requires Python 3.11+ and mcp==1.29.0."""

import asyncio
from pathlib import Path
import sys

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError

server = FastMCP("sre-demo")
RUNBOOK = "runbook://checkout/5xx"


@server.resource(RUNBOOK)
def checkout_runbook() -> str:
    """Read the synthetic checkout runbook."""
    return "Compare 5xx rates by deployment version and time window."


@server.prompt()
def incident_summary() -> str:
    """Build a reusable prompt without executing a tool."""
    return "List the observations, competing hypotheses, and next check."


@server.tool()
def get_error_rate(service: str) -> dict[str, str | int]:
    """Read count data from two adjacent 10-minute windows."""
    if service != "checkout":
        raise ToolError("This fixture only provides checkout data.")
    return {
        "service": service,
        "before_start_utc": "2026-11-21T15:50:00Z",
        "after_start_utc": "2026-11-21T16:00:00Z",
        "after_end_utc": "2026-11-21T16:10:00Z",
        "before_requests": 1000,
        "after_requests": 1000,
        "before_5xx": 2,
        "after_5xx": 49,
    }


async def verify() -> None:
    command = StdioServerParameters(
        command=sys.executable, args=[str(Path(__file__).resolve()), "--serve"]
    )
    async with stdio_client(command) as (incoming, outgoing):
        async with ClientSession(incoming, outgoing) as client:
            session = await client.initialize()
            tools = await client.list_tools()
            assert [tool.name for tool in tools.tools] == ["get_error_rate"]

            runbook = await client.read_resource(RUNBOOK)
            assert "deployment version" in runbook.contents[0].text
            prompt = await client.get_prompt("incident_summary")
            assert "hypotheses" in prompt.messages[0].content.text

            result = await client.call_tool("get_error_rate", {"service": "checkout"})
            assert not result.isError and result.structuredContent is not None
            counts = result.structuredContent
            before = 100 * counts["before_5xx"] / counts["before_requests"]
            after = 100 * counts["after_5xx"] / counts["after_requests"]
            assert (before, after) == (0.2, 4.9)

            denied = await client.call_tool("get_error_rate", {"service": "billing"})
            assert denied.isError
            print(f"MCP {session.protocolVersion}")
            print(f"checkout: {before:.1f}% -> {after:.1f}% (+{after-before:.1f} pp)")
            print("Catalog, resource, prompt, tool result and denied lookup: PASS")


if __name__ == "__main__":
    if sys.argv[1:] == ["--serve"]:
        server.run(transport="stdio")
    else:
        asyncio.run(verify())
