#!/usr/bin/env python3
"""
Manual JSON-RPC MCP server implementation to debug stdio issues.
"""

import json
import os
import sys

import requests


class ManualMCPServer:
    """Manual MCP server that handles JSON-RPC directly."""

    def __init__(self):
        self.tools = []
        self.load_tools()

    def load_tools(self):
        """Load tools from gateway."""
        try:
            gateway_url = os.getenv("GATEWAY_URL", "http://localhost:8000")
            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.append({
                            "name": tool["name"],
                            "description": tool.get("description", ""),
                            "inputSchema": tool.get("inputSchema", {})
                        })
        except Exception:
            pass  # Continue with empty tools

    def handle_initialize(self, request_id):
        """Handle initialize request."""
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "tools": {"listChanged": False}
                },
                "serverInfo": {
                    "name": "coherence-mcp-manual",
                    "version": "1.0.0"
                }
            }
        }

    def handle_tools_list(self, request_id):
        """Handle tools/list request."""
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "tools": self.tools
            }
        }

    def run(self):
        """Run the server."""
        while True:
            try:
                # Read request from stdin
                line = sys.stdin.readline()
                if not line:
                    break

                request = json.loads(line.strip())
                method = request.get("method")
                request_id = request.get("id")

                if method == "initialize":
                    response = self.handle_initialize(request_id)
                elif method == "tools/list":
                    response = self.handle_tools_list(request_id)
                else:
                    response = {
                        "jsonrpc": "2.0",
                        "id": request_id,
                        "error": {"code": -32601, "message": "Method not found"}
                    }

                # Send response to stdout
                sys.stdout.write(json.dumps(response) + "\n")
                sys.stdout.flush()

            except Exception as e:
                # Send error response
                error_response = {
                    "jsonrpc": "2.0",
                    "id": request.get("id") if 'request' in locals() else None,
                    "error": {"code": -32603, "message": str(e)}
                }
                sys.stdout.write(json.dumps(error_response) + "\n")
                sys.stdout.flush()


if __name__ == "__main__":
    server = ManualMCPServer()
    server.run()
