#!/usr/bin/env python3
"""
Simple test for MCP server - just checks if it starts and responds.
"""

import json
import subprocess
import sys
import time


def test_mcp_basic():
    """Basic test of MCP server startup and response."""
    print("Testing MCP server startup...\n")

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

    # Wait a bit for startup
    time.sleep(2)

    # Check if process is still running
    if proc.poll() is not None:
        stderr = proc.stderr.read()
        print(f"❌ Server crashed on startup:\n{stderr}")
        return False

    # Send a simple initialization request
    request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "0.1.0",
            "capabilities": {"tools": {}},
            "clientInfo": {"name": "test", "version": "1.0"}
        }
    }

    try:
        proc.stdin.write(json.dumps(request) + "\n")
        proc.stdin.flush()

        # Try to read response with timeout
        import select
        readable, _, _ = select.select([proc.stdout], [], [], 5.0)

        if readable:
            response_line = proc.stdout.readline()
            response = json.loads(response_line)
            print(f"✅ Server responded: {response.get('result', {}).get('serverInfo', {})}")
            return True
        else:
            print("❌ No response from server within 5 seconds")
            return False

    except Exception as e:
        print(f"❌ Error: {e}")
        return False
    finally:
        proc.terminate()
        proc.wait()


if __name__ == "__main__":
    # First check if the gateway is running
    import requests
    try:
        resp = requests.get("http://localhost:8000/health", timeout=2)
        print(f"Gateway health: {resp.status_code}\n")
    except:
        print("⚠️  Gateway not reachable at localhost:8000\n")

    success = test_mcp_basic()
    sys.exit(0 if success else 1)
