#!/usr/bin/env python3
"""
Simplified stdio test that sends just an initialize request.
"""

import json
import select
import subprocess
import sys
import time


def test_stdio_init():
    """Test just the initialization over stdio."""
    print("Testing stdio initialization only...", file=sys.stderr)

    # Start server
    proc = subprocess.Popen(
        ["python", "server.py"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1
    )

    # Wait for startup
    time.sleep(2)

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

        request_str = json.dumps(init_request) + "\n"
        proc.stdin.write(request_str)
        proc.stdin.flush()

        # Wait for response with timeout
        readable, _, _ = select.select([proc.stdout], [], [], 5.0)

        if readable:
            response_line = proc.stdout.readline()
            if response_line:
                response = json.loads(response_line)
                print(f"✅ Initialization successful: {response.get('result', {}).get('serverInfo', {})}", file=sys.stderr)
                return True
            else:
                print("❌ Empty response", file=sys.stderr)
                return False
        else:
            print("❌ Timeout waiting for response", file=sys.stderr)
            return False

    except Exception as e:
        print(f"❌ Error: {e}", file=sys.stderr)

        # Check stderr
        stderr_output = proc.stderr.read()
        if stderr_output:
            print(f"Server stderr: {stderr_output}", file=sys.stderr)
        return False
    finally:
        proc.terminate()
        proc.wait()


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