#!/usr/bin/env python3
"""
Rohkun MCP Server - JSON-RPC 2.0 over stdio

Thin wrapper around existing Rohkun CLI functionality.
No changes to existing code required.
"""
import sys
import json
from pathlib import Path
from typing import Dict, Any, Optional

from .tools import get_tools, handle_tool_call
from .resources import get_resources, handle_resource_read


class MCPServer:
    """MCP server implementing JSON-RPC 2.0 over stdio"""
    
    def __init__(self):
        self.protocol_version = "2024-11-05"
        self.server_info = {
            "name": "rohkun-mcp",
            "version": "0.1.0"
        }
    
    def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
        """Handle incoming JSON-RPC request"""
        method = request.get("method")
        params = request.get("params", {})
        request_id = request.get("id")
        
        try:
            if method == "initialize":
                return self.handle_initialize(params, request_id)
            elif method == "tools/list":
                return self.handle_tools_list(request_id)
            elif method == "tools/call":
                return self.handle_tool_call(params, request_id)
            elif method == "resources/list":
                return self.handle_resources_list(request_id)
            elif method == "resources/read":
                return self.handle_resource_read(params, request_id)
            else:
                return self.error_response(
                    request_id, -32601, f"Method not found: {method}"
                )
        except Exception as e:
            return self.error_response(request_id, -32603, str(e))
    
    def handle_initialize(self, params: Dict[str, Any], request_id: int) -> Dict[str, Any]:
        """Handle initialize request"""
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "protocolVersion": self.protocol_version,
                "capabilities": {
                    "tools": {},
                    "resources": {}
                },
                "serverInfo": self.server_info
            }
        }
    
    def handle_tools_list(self, request_id: int) -> Dict[str, Any]:
        """Handle tools/list request"""
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "tools": get_tools()
            }
        }
    
    def handle_tool_call(self, params: Dict[str, Any], request_id: int) -> Dict[str, Any]:
        """Handle tools/call request"""
        tool_name = params.get("name")
        tool_params = params.get("arguments", {})
        
        try:
            result = handle_tool_call(tool_name, tool_params)
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": result
            }
        except Exception as e:
            return self.error_response(request_id, -32603, f"Tool execution failed: {str(e)}")
    
    def handle_resources_list(self, request_id: int) -> Dict[str, Any]:
        """Handle resources/list request"""
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "resources": get_resources()
            }
        }
    
    def handle_resource_read(self, params: Dict[str, Any], request_id: int) -> Dict[str, Any]:
        """Handle resources/read request"""
        uri = params.get("uri")
        
        try:
            result = handle_resource_read(uri)
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": result
            }
        except Exception as e:
            return self.error_response(request_id, -32603, f"Resource read failed: {str(e)}")
    
    def error_response(self, request_id: Optional[int], code: int, message: str) -> Dict[str, Any]:
        """Create JSON-RPC error response"""
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "error": {
                "code": code,
                "message": message
            }
        }
    
    def run(self):
        """Main server loop - read from stdin, write to stdout"""
        for line in sys.stdin:
            line = line.strip()
            if not line:
                continue
            
            try:
                request = json.loads(line)
                response = self.handle_request(request)
                print(json.dumps(response), flush=True)
            except json.JSONDecodeError as e:
                error_response = self.error_response(None, -32700, f"Parse error: {str(e)}")
                print(json.dumps(error_response), flush=True)
            except Exception as e:
                error_response = self.error_response(None, -32603, f"Internal error: {str(e)}")
                print(json.dumps(error_response), flush=True)


def main():
    """Entry point for rohkun-mcp command"""
    server = MCPServer()
    server.run()


if __name__ == "__main__":
    main()
