"""
测试 MCP Server v1.0.9 STDIO 连接
"""
import subprocess
import json
import time

print("=" * 70)
print("测试 Questions MCP Server v1.0.9 STDIO 连接")
print("=" * 70)
print()

# 使用安装后的命令
python_exe = r"H:\project\questions_mcp_server\.venv\Scripts\python.exe"
cwd = r"H:\project\questions_mcp_server"

print(f"Python: {python_exe}")
print(f"工作目录: {cwd}")
print()

# 启动 MCP Server
print("启动 MCP Server...")
proc = subprocess.Popen(
    [python_exe, "-m", "src.main"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    cwd=cwd,
    text=True,
    encoding='utf-8',
    bufsize=0
)

print(f"进程 PID: {proc.pid}")
print("等待服务器启动...")
time.sleep(3)
print()

# 发送 initialize 请求
init_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {
            "name": "test-client",
            "version": "1.0.0"
        }
    }
}

print("发送 MCP initialize 请求...")
print()

try:
    request_str = json.dumps(init_request) + "\n"
    proc.stdin.write(request_str)
    proc.stdin.flush()
    
    print("等待响应（最多 10 秒）...")
    
    # 读取响应
    start_time = time.time()
    response_received = False
    
    while time.time() - start_time < 10:
        if proc.poll() is not None:
            print(f"[错误] 进程已退出，退出码: {proc.returncode}")
            break
            
        try:
            response_line = proc.stdout.readline()
            if response_line:
                print()
                print("✅ 收到响应:")
                print("-" * 70)
                print(response_line.strip())
                print("-" * 70)
                print()
                
                try:
                    response = json.loads(response_line)
                    print("✅ JSON 解析成功:")
                    print(json.dumps(response, indent=2, ensure_ascii=False))
                    print()
                    
                    if "result" in response:
                        server_info = response["result"].get("serverInfo", {})
                        print("✅ 服务器信息:")
                        print(f"  - 名称: {server_info.get('name')}")
                        print(f"  - 版本: {server_info.get('version')}")
                        print()
                        
                        if server_info.get('version') == '1.0.9':
                            print("✅✅✅ 版本验证成功！v1.0.9 正常工作")
                        else:
                            print(f"⚠️ 版本不匹配: 期望 1.0.9, 实际 {server_info.get('version')}")
                    
                    response_received = True
                    break
                    
                except json.JSONDecodeError as e:
                    print(f"❌ JSON 解析失败: {e}")
                    break
        except Exception as e:
            print(f"读取错误: {e}")
            break
    
    if not response_received:
        print()
        print("❌ 超时：10秒内未收到响应")
        print()
        print("检查 stderr 输出:")
        print("-" * 70)
        try:
            stderr_output = proc.stderr.read()
            if stderr_output:
                for line in stderr_output.split('\n')[:20]:
                    print(line)
        except:
            pass
        print("-" * 70)

except Exception as e:
    print(f"❌ 测试失败: {e}")
    import traceback
    traceback.print_exc()

finally:
    print()
    print("终止服务器...")
    proc.terminate()
    try:
        proc.wait(timeout=3)
    except subprocess.TimeoutExpired:
        proc.kill()
    
    print()
    print("=" * 70)
    print("测试完成")
    print("=" * 70)
