#!/usr/bin/env python3
"""Echo MCP server — a minimal server for testing mcp-forge itself.

Exposes tools that echo input, for deterministic testing.
Communicates via STDIO with JSON-RPC 2.0.
"""

from __future__ import annotations

import json
import sys
from typing import Any


def handle_request(request: dict[str, Any]) -> dict[str, Any] | None:
    """Process a single JSON-RPC request and return a response."""
    method = request.get("method", "")
    req_id = request.get("id")
    params = request.get("params", {})

    # Notifications (no id) don't get responses
    if req_id is None:
        return None

    if method == "initialize":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "protocolVersion": "2025-06-18",
                "capabilities": {
                    "tools": {"listChanged": False},
                },
                "serverInfo": {
                    "name": "echo-server",
                    "version": "1.0.0",
                },
            },
        }

    elif method == "tools/list":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "tools": [
                    {
                        "name": "echo",
                        "description": "Echo the input message back.",
                        "inputSchema": {
                            "type": "object",
                            "required": ["message"],
                            "properties": {
                                "message": {
                                    "type": "string",
                                    "description": "The message to echo.",
                                },
                            },
                        },
                    },
                    {
                        "name": "add",
                        "description": "Add two numbers.",
                        "inputSchema": {
                            "type": "object",
                            "required": ["a", "b"],
                            "properties": {
                                "a": {"type": "number", "description": "First number."},
                                "b": {"type": "number", "description": "Second number."},
                            },
                        },
                    },
                    {
                        "name": "greet",
                        "description": "Generate a greeting.",
                        "inputSchema": {
                            "type": "object",
                            "required": ["name"],
                            "properties": {
                                "name": {
                                    "type": "string",
                                    "description": "Name to greet.",
                                },
                                "formal": {
                                    "type": "boolean",
                                    "description": "Use formal greeting.",
                                    "default": False,
                                },
                            },
                        },
                    },
                    {
                        "name": "fail",
                        "description": "Always returns an error (for testing error handling).",
                        "inputSchema": {
                            "type": "object",
                            "properties": {
                                "reason": {
                                    "type": "string",
                                    "description": "Error reason.",
                                    "default": "intentional failure",
                                },
                            },
                        },
                    },
                ]
            },
        }

    elif method == "tools/call":
        tool_name = params.get("name", "")
        args = params.get("arguments", {})

        if tool_name == "echo":
            message = args.get("message", "")
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {
                    "content": [{"type": "text", "text": message}],
                    "isError": False,
                },
            }

        elif tool_name == "add":
            a = args.get("a", 0)
            b = args.get("b", 0)
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {
                    "content": [{"type": "text", "text": str(a + b)}],
                    "isError": False,
                },
            }

        elif tool_name == "greet":
            name = args.get("name", "World")
            formal = args.get("formal", False)
            if formal:
                greeting = f"Good day, {name}. How do you do?"
            else:
                greeting = f"Hello, {name}!"
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {
                    "content": [{"type": "text", "text": greeting}],
                    "isError": False,
                },
            }

        elif tool_name == "fail":
            reason = args.get("reason", "intentional failure")
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {
                    "content": [{"type": "text", "text": f"Error: {reason}"}],
                    "isError": True,
                },
            }

        else:
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "error": {
                    "code": -32602,
                    "message": f"Unknown tool: {tool_name}",
                },
            }

    elif method == "resources/list":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {"resources": []},
        }

    elif method == "prompts/list":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {"prompts": []},
        }

    else:
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "error": {
                "code": -32601,
                "message": f"Method not found: {method}",
            },
        }


def main():
    """Run the echo server on STDIO."""
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue

        try:
            request = json.loads(line)
        except json.JSONDecodeError:
            continue

        response = handle_request(request)
        if response is not None:
            sys.stdout.write(json.dumps(response) + "\n")
            sys.stdout.flush()


if __name__ == "__main__":
    main()
