"""Test: does the MCP server exit when stdin is closed?"""

import subprocess
import json
import time
import sys


def main():
    # Start the server using the entry point script
    env = {**__import__("os").environ, "KAGI_API_KEY": "dummy-key-for-testing"}
    proc = subprocess.Popen(
        [".venv/bin/python", "-c", "from kagimcp import main; main()"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd="/home/Rehan/Projects/mcp/kagi",
        env=env,
    )
    print(f"Server started, PID={proc.pid}")
    time.sleep(1)

    # Check it's still alive
    if proc.poll() is not None:
        print(f"Server exited early with code {proc.returncode}")
        print(f"stderr: {proc.stderr.read().decode()}")
        return

    # Send initialize request
    init_req = json.dumps({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {"name": "test-client", "version": "0.1.0"},
        },
    })
    proc.stdin.write((init_req + "\n").encode())
    proc.stdin.flush()
    print("Sent initialize request")

    # Read init response
    resp_line = proc.stdout.readline()
    print(f"Got init response: {resp_line.decode().strip()[:120]}...")

    # Send initialized notification
    initialized = json.dumps({
        "jsonrpc": "2.0",
        "method": "notifications/initialized",
    })
    proc.stdin.write((initialized + "\n").encode())
    proc.stdin.flush()
    print("Sent initialized notification")

    time.sleep(0.5)

    # Now close stdin (simulating client disconnect)
    print("\n--- Closing stdin (simulating client disconnect) ---")
    proc.stdin.close()

    # Wait and check if server exits
    for i in range(1, 11):
        ret = proc.poll()
        if ret is not None:
            stderr = proc.stderr.read().decode().strip()
            print(f"Server exited after {i}s with code {ret}")
            if stderr:
                print(f"stderr: {stderr[:500]}")
            return
        print(f"  ...still running after {i}s")
        time.sleep(1)

    print(f"\nServer still running after 10s! PID={proc.pid}")
    stderr = proc.stderr.read(4096).decode().strip() if proc.stderr else ""
    if stderr:
        print(f"stderr so far: {stderr[:500]}")
    proc.terminate()
    proc.wait(timeout=5)
    print("Had to terminate server manually.")


if __name__ == "__main__":
    main()
