#!/usr/bin/env python3
"""
Test MCP server tool listing and execution.
"""

import json
import select
import subprocess
import sys
import time


def send_and_receive(proc, request):
    """Send request and receive response with timeout."""
    proc.stdin.write(json.dumps(request) + "\n")
    proc.stdin.flush()

    # Wait for response with timeout
    readable, _, _ = select.select([proc.stdout], [], [], 5.0)
    if readable:
        response_line = proc.stdout.readline()
        return json.loads(response_line)
    else:
        raise TimeoutError("No response within 5 seconds")


def test_mcp_tools():
    """Test MCP tool listing and execution."""
    print("Starting MCP server test...\n")

    # Start the server
    proc = subprocess.Popen(
        ["poetry", "run", "python", "-m", "mcp_adapter.server"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )

    # Wait for startup
    time.sleep(3)

    try:
        # 1. Initialize
        print("1. Initializing connection...")
        init_request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "0.1.0",
                "capabilities": {"tools": {}},
                "clientInfo": {"name": "test", "version": "1.0"}
            }
        }
        init_resp = send_and_receive(proc, init_request)
        print(f"   Server: {init_resp['result']['serverInfo']}")

        # 2. List tools
        print("\n2. Listing available tools...")
        list_request = {
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list"
        }
        list_resp = send_and_receive(proc, list_request)

        tools = list_resp.get("result", {}).get("tools", [])
        print(f"   Found {len(tools)} tools:")
        for tool in tools:
            print(f"   - {tool['name']}: {tool.get('description', 'No description')}")

        # 3. Execute a tool (if available)
        if tools:
            tool_name = tools[0]["name"]
            print(f"\n3. Testing tool execution: {tool_name}")

            # Check what parameters the tool needs
            input_schema = tools[0].get("inputSchema", {})
            print(f"   Input schema: {json.dumps(input_schema, indent=2)}")

            # Try to call the tool with empty parameters
            call_request = {
                "jsonrpc": "2.0",
                "id": 3,
                "method": "tools/call",
                "params": {
                    "name": tool_name,
                    "arguments": {}
                }
            }

            try:
                call_resp = send_and_receive(proc, call_request)
                if "result" in call_resp:
                    content = call_resp["result"].get("content", [])
                    if content and len(content) > 0:
                        print(f"   Response: {content[0].get('text', 'No text')[:200]}...")
                elif "error" in call_resp:
                    print(f"   Error: {call_resp['error']}")
            except Exception as e:
                print(f"   Tool execution error: {e}")

        print("\n✅ Test completed successfully!")
        return True

    except Exception as e:
        print(f"\n❌ Test failed: {e}")
        # Print any stderr output
        try:
            stderr = proc.communicate(timeout=1)[1]
            if stderr:
                print(f"Server output:\n{stderr}")
        except:
            pass
        return False

    finally:
        proc.terminate()
        proc.wait()


if __name__ == "__main__":
    success = test_mcp_tools()
    sys.exit(0 if success else 1)
