"""KoanMCPServer — expose KOAN tools as an MCP server."""

from __future__ import annotations

from typing import TYPE_CHECKING

from mcp.server.fastmcp import FastMCP

if TYPE_CHECKING:
    from koan.tools.registry import ToolRegistry


class KoanMCPServer:
    """Wraps a KOAN ToolRegistry as an MCP server via FastMCP.

    Each registered KOAN tool becomes an MCP tool with the same name,
    description, and JSON schema.

    Usage::

        registry = ToolRegistry()
        registry.add(my_tool)

        server = KoanMCPServer("my-server", registry=registry)
        server.run()  # Starts stdio MCP server
    """

    def __init__(self, name: str, *, registry: ToolRegistry) -> None:
        self.name = name
        self.registry = registry
        self._mcp = FastMCP(name)
        self._register_tools()

    def _register_tools(self) -> None:
        """Register all KOAN tool functions directly with FastMCP.

        FastMCP introspects the function signature to build the parameter
        schema, so we pass the original decorated function directly.
        """
        for func in self.registry._tools.values():  # noqa: SLF001
            defn = func.__tool_definition__  # type: ignore[union-attr]
            self._mcp._tool_manager.add_tool(  # noqa: SLF001
                func,
                name=defn.name,
                description=defn.description,
            )

    @property
    def mcp(self) -> FastMCP:
        """Access the underlying FastMCP instance."""
        return self._mcp

    def run(self, transport: str = "stdio") -> None:
        """Run the MCP server."""
        self._mcp.run(transport=transport)  # type: ignore[arg-type]
