"""MCP Server that proxies tool calls to FlukeBase server.

This minimal MCP server fetches available tools from the FlukeBase API
and proxies all tool executions to the server side.
"""

import asyncio
import logging
from typing import Any, Sequence

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
    CallToolResult,
    TextContent,
    Tool,
)

from flukebase_connect.config import get_config
from flukebase_connect.flukebase.client import FlukeBaseClient

logger = logging.getLogger(__name__)


class FlukeBaseConnectServer:
    """MCP Server that proxies tools to FlukeBase platform."""

    def __init__(self):
        self.server = Server("flukebase-connect")
        self.config = get_config()
        self.client = FlukeBaseClient(self.config)
        self._tools_cache: list[dict] = []
        self._setup_handlers()

    def _setup_handlers(self):
        """Set up MCP protocol handlers."""

        @self.server.list_tools()
        async def list_tools() -> list[Tool]:
            """List available tools from server."""
            try:
                if not self._tools_cache:
                    self._tools_cache = await self.client.list_available_tools()

                return [
                    Tool(
                        name=tool["name"],
                        description=tool.get("description", ""),
                        inputSchema=tool.get("inputSchema", {"type": "object"}),
                    )
                    for tool in self._tools_cache
                ]
            except Exception as e:
                logger.error(f"Failed to list tools: {e}")
                return []

        @self.server.call_tool()
        async def call_tool(name: str, arguments: dict[str, Any]) -> Sequence[TextContent]:
            """Execute tool via server proxy."""
            try:
                result = await self.client.execute_tool(
                    tool_name=name,
                    arguments=arguments,
                    project_id=self.config.flukebase.current_project_id,
                )

                # Format result for MCP
                if isinstance(result, dict):
                    import json
                    content = json.dumps(result, indent=2, default=str)
                else:
                    content = str(result)

                return [TextContent(type="text", text=content)]

            except Exception as e:
                logger.error(f"Tool execution failed: {e}")
                return [TextContent(type="text", text=f"Error: {str(e)}")]

    async def run(self):
        """Run the MCP server."""
        async with stdio_server() as (read_stream, write_stream):
            await self.server.run(
                read_stream,
                write_stream,
                self.server.create_initialization_options(),
            )


def main():
    """Entry point for MCP server."""
    logging.basicConfig(level=logging.INFO)
    server = FlukeBaseConnectServer()
    asyncio.run(server.run())


if __name__ == "__main__":
    main()
