"""MCP Server - 将 Agent 能力暴露为 MCP 工具

基于 FastAPI 实现，支持 Streamable HTTP 传输。
"""

import logging
from typing import Any

logger = logging.getLogger(__name__)


class MCPServer:
    """MCP Server - 暴露 Agent 能力为 MCP 工具

    自动将 ToolRegistry 中注册的工具暴露为 MCP 工具端点。
    """

    def __init__(self, tool_registry: Any = None, host: str = "0.0.0.0", port: int = 8080):
        self._tool_registry = tool_registry
        self._host = host
        self._port = port
        self._app = None

    def _create_app(self):
        """创建 FastAPI 应用"""
        try:
            from fastapi import FastAPI
            from fastapi import Request
        except ImportError:
            raise ImportError("MCP Server requires fastapi: pip install fischer-agentkit[mcp]")

        app = FastAPI(title="Fischer AgentKit MCP Server")

        @app.get("/tools/list")
        async def list_tools():
            if self._tool_registry is None:
                return {"tools": []}
            tools = self._tool_registry.list_tools()
            return {
                "tools": [
                    {
                        "name": t.name,
                        "description": t.description,
                        "inputSchema": t.input_schema or {},
                    }
                    for t in tools
                ]
            }

        @app.post("/tools/call")
        async def call_tool(request: dict):
            tool_name = request.get("name")
            arguments = request.get("arguments", {})

            if not tool_name or self._tool_registry is None:
                return {"error": "Tool not specified or registry not configured"}

            try:
                tool = self._tool_registry.get(tool_name)
                result = await tool.safe_execute(**arguments)
                return {"content": [{"type": "text", "text": str(result)}]}
            except Exception as e:
                return {"isError": True, "content": [{"type": "text", "text": str(e)}]}

        @app.get("/health")
        async def health():
            return {"status": "ok"}

        @app.post("/")
        async def jsonrpc_endpoint(request: Request):
            """JSON-RPC 2.0 endpoint for MCP protocol compatibility.

            Handles requests from HTTPTransport which sends JSON-RPC format.
            """
            import json

            try:
                body = await request.json()
            except Exception:
                return {"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": None}

            method = body.get("method", "")
            params = body.get("params", {})
            req_id = body.get("id")

            if method == "initialize":
                result = {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {"tools": {}},
                    "serverInfo": {"name": "agentkit-mcp-server", "version": "2.0.0"},
                }
            elif method == "tools/list":
                if self._tool_registry is None:
                    result = {"tools": []}
                else:
                    tools = self._tool_registry.list_tools()
                    result = {
                        "tools": [
                            {
                                "name": t.name,
                                "description": t.description,
                                "inputSchema": t.input_schema or {},
                            }
                            for t in tools
                        ]
                    }
            elif method == "tools/call":
                tool_name = params.get("name", "")
                arguments = params.get("arguments", {})

                if not tool_name or self._tool_registry is None:
                    result = {"isError": True, "content": [{"type": "text", "text": "Tool not found"}]}
                else:
                    try:
                        tool = self._tool_registry.get(tool_name)
                        tool_result = await tool.safe_execute(**arguments)
                        result = {"content": [{"type": "text", "text": str(tool_result)}]}
                    except Exception as e:
                        result = {"isError": True, "content": [{"type": "text", "text": str(e)}]}
            else:
                return {
                    "jsonrpc": "2.0",
                    "error": {"code": -32601, "message": f"Method not found: {method}"},
                    "id": req_id,
                }

            response = {"jsonrpc": "2.0", "result": result, "id": req_id}
            return response

        return app

    async def start(self):
        """启动 MCP Server"""
        self._app = self._create_app()

        try:
            import uvicorn
            config = uvicorn.Config(self._app, host=self._host, port=self._port, log_level="info")
            server = uvicorn.Server(config)
            await server.serve()
        except ImportError:
            raise ImportError("MCP Server requires uvicorn: pip install uvicorn")

    def get_app(self):
        """获取 FastAPI 应用实例（用于测试或嵌入）"""
        if self._app is None:
            self._app = self._create_app()
        return self._app
