from __future__ import annotations

from typing import TYPE_CHECKING, Any

from fastapi import APIRouter, HTTPException

from niannian.mcp.client.config import list_enabled_servers, load_mcp_config
from niannian.mcp.client.pool import MCPClientPool

if TYPE_CHECKING:
    from niannian.client import NianNian


def create_mcp_router(nn: NianNian) -> APIRouter:
    router = APIRouter(prefix="/v1/mcp", tags=["mcp"])

    @router.get("/servers")
    def list_servers():
        cfg = load_mcp_config()
        enabled = list_enabled_servers(cfg)
        rows: list[dict[str, Any]] = []
        for name, spec in (cfg.get("servers") or {}).items():
            rows.append(
                {
                    "name": name,
                    "enabled": name in enabled,
                    "transport": spec.get("transport"),
                    "runtime": spec.get("runtime", "auto"),
                }
            )
        return {"servers": rows}

    @router.get("/servers/{name}/tools")
    def list_tools(name: str):
        pool = MCPClientPool()
        spec = pool.get_server_config(name)
        if spec is None:
            raise HTTPException(status_code=404, detail={"code": "server_not_found"})
        return {"name": name, "tools": pool.list_tools(name)}

    @router.post("/servers/{name}/probe")
    def probe_server(name: str):
        pool = MCPClientPool()
        spec = pool.get_server_config(name)
        if spec is None:
            raise HTTPException(status_code=404, detail={"code": "server_not_found"})
        ok = pool.lazy_connect(name)
        conn = pool._connections.get(name) or {}
        return {
            "name": name,
            "connected": ok,
            "status": conn.get("status", "unavailable"),
            "transport": spec.get("transport"),
        }

    return router
