#!/usr/bin/env python3
"""
Test just the tools/list request to isolate the hanging issue.
"""

import json
import select
import subprocess
import sys
import time


def test_tools_list():
    """Test tools/list request specifically."""
    print("Testing tools/list request...", file=sys.stderr)

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

    time.sleep(3)  # Give more time for tool loading

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

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

        # Read init response
        readable, _, _ = select.select([proc.stdout], [], [], 5.0)
        if not readable:
            print("❌ No response to init", file=sys.stderr)
            return False

        init_response = proc.stdout.readline()
        print(f"Init response: {init_response.strip()}", file=sys.stderr)

        # 2. Now try tools/list
        print("Sending tools/list...", file=sys.stderr)
        list_request = {
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list",
            "params": {}
        }

        proc.stdin.write(json.dumps(list_request) + "\n")
        proc.stdin.flush()

        # Wait for tools/list response
        readable, _, _ = select.select([proc.stdout], [], [], 10.0)
        if readable:
            list_response = proc.stdout.readline()
            if list_response:
                response = json.loads(list_response)
                tools = response.get("result", {}).get("tools", [])
                print(f"✅ Got {len(tools)} tools", file=sys.stderr)
                for tool in tools:
                    print(f"  - {tool.get('name', 'unnamed')}", file=sys.stderr)
                return True
            else:
                print("❌ Empty response to tools/list", file=sys.stderr)
                return False
        else:
            print("❌ Timeout on tools/list", file=sys.stderr)
            return False

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


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