#!/usr/bin/env python3
"""
Simplified MCP Server with synchronous tool loading to fix stdio hanging issue.
"""

import asyncio
import json
import logging
import os
import sys
from collections.abc import Sequence

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

try:
    from .gateway_client import GatewayClient
except ImportError:
    from gateway_client import GatewayClient

# Simple logging setup
logging.basicConfig(
    level=logging.ERROR,  # Only log errors to avoid stdio interference
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

# Configuration
GATEWAY_URL = os.getenv("GATEWAY_URL", "http://localhost:8000")
JWT_SECRET = os.getenv("JWT_SECRET", "55c121aa48dc1b79e3c04c805aabd2fe7646253ab6edd1c61894f8146ce1ed17")


class SimpleCoherenceMCPServer:
    """Simplified MCP Server implementation."""

    def __init__(self):
        self.gateway_client = GatewayClient(GATEWAY_URL, JWT_SECRET)
        self.tools = {}

    def load_tools_sync(self):
        """Load tools synchronously using requests."""
        try:
            import requests
            response = requests.get(
                f"{GATEWAY_URL}/mcp/tools/discovery",
                timeout=5.0
            )

            if response.status_code == 200:
                data = response.json()
                if data.get("tools"):
                    for tool in data["tools"]:
                        self.tools[tool["name"]] = {
                            "name": tool["name"],
                            "description": tool.get("description", ""),
                            "input_schema": tool.get("inputSchema", {})
                        }
                    return len(self.tools)
        except Exception:
            # Silently fail and continue with empty tools
            pass
        return 0


async def serve() -> None:
    """Run the simplified MCP server."""
    coherence = SimpleCoherenceMCPServer()
    server = Server("coherence-mcp")

    # Load tools synchronously before setting up handlers
    tool_count = coherence.load_tools_sync()

    @server.list_tools()
    async def list_tools() -> list[Tool]:
        """List all available tools."""
        mcp_tools = []
        for tool_name, tool_data in coherence.tools.items():
            mcp_tool = Tool(
                name=tool_name,
                description=tool_data.get("description", ""),
                inputSchema=tool_data.get("input_schema", {}),
            )
            mcp_tools.append(mcp_tool)
        return mcp_tools

    @server.call_tool()
    async def call_tool(
        name: str, arguments: dict
    ) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
        """Execute a tool via the gateway."""
        if name not in coherence.tools:
            return [TextContent(type="text", text=f"Unknown tool: {name}")]

        try:
            result = await coherence.gateway_client.execute_tool(name, arguments)

            if result.get("error"):
                response_text = f"Error: {result['error']}"
            else:
                # Extract data from response
                data = result
                if "output" in data:
                    data = data["output"]
                if isinstance(data, dict) and "data" in data:
                    data = data["data"]

                response_text = json.dumps(data, indent=2) if isinstance(data, (dict, list)) else str(data)

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

        except Exception as e:
            return [TextContent(type="text", text=f"Failed to execute tool {name}: {str(e)}")]

    # Create options and run
    options = server.create_initialization_options()
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, options)


def main():
    """Main entry point."""
    try:
        asyncio.run(serve())
    except KeyboardInterrupt:
        sys.exit(0)
    except Exception:
        sys.exit(1)


if __name__ == "__main__":
    main()
