#!/usr/bin/env python3
"""
Test script for MCP server protocol communication.

This script tests the MCP server by sending JSON-RPC requests
through stdin/stdout, simulating how Claude Desktop would interact.
"""

import json
import os
import subprocess
import sys
import time
from typing import Any


def send_request(proc: subprocess.Popen, request: dict[str, Any]) -> dict[str, Any]:
    """Send a JSON-RPC request and get response."""
    # Send request
    request_str = json.dumps(request)
    print(f"→ Sending: {request_str}", file=sys.stderr)
    proc.stdin.write(request_str + "\n")
    proc.stdin.flush()

    # Read response
    response_line = proc.stdout.readline()
    if not response_line:
        raise Exception("No response received")

    response = json.loads(response_line)
    print(f"← Received: {json.dumps(response, indent=2)}", file=sys.stderr)
    return response


def test_mcp_server():
    """Test the MCP server with various requests."""
    print("=== Testing MCP Server ===", file=sys.stderr)

    # Start the MCP server
    print("\n1. Starting MCP server...", file=sys.stderr)
    proc = subprocess.Popen(
        ["python", "server.py"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        cwd=os.path.dirname(os.path.abspath(__file__))
    )

    # Give it time to start and load tools
    time.sleep(3)

    try:
        # Test 1: Initialize connection
        print("\n2. Testing initialization...", file=sys.stderr)
        init_request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "0.1.0",
                "capabilities": {
                    "tools": {}
                },
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                }
            }
        }
        init_response = send_request(proc, init_request)

        # Test 2: List tools
        print("\n3. Testing tools/list...", file=sys.stderr)
        list_request = {
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list",
            "params": {}
        }
        list_response = send_request(proc, list_request)

        # Test 3: Call a tool (if any available)
        if list_response.get("result", {}).get("tools"):
            tool_name = list_response["result"]["tools"][0]["name"]
            print(f"\n4. Testing tool call: {tool_name}...", file=sys.stderr)

            call_request = {
                "jsonrpc": "2.0",
                "id": 3,
                "method": "tools/call",
                "params": {
                    "name": tool_name,
                    "arguments": {}
                }
            }
            call_response = send_request(proc, call_request)
        else:
            print("\n4. No tools available to test", file=sys.stderr)

        print("\n✅ All tests completed!", file=sys.stderr)

    except Exception as e:
        print(f"\n❌ Test failed: {e}", file=sys.stderr)

        # Print stderr if available
        stderr_output = proc.stderr.read()
        if stderr_output:
            print(f"\nServer stderr:\n{stderr_output}", file=sys.stderr)

    finally:
        # Clean up
        proc.terminate()
        proc.wait()


if __name__ == "__main__":
    test_mcp_server()
