#!/usr/bin/env python3
"""
快速测试脚本 - 测试调试服务的各个端点
"""

import requests
import json
import time

def test_endpoint(url, name):
    """测试单个端点"""
    print(f"\n🔍 测试 {name}: {url}")
    try:
        response = requests.get(url, timeout=5)
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            try:
                json_data = response.json()
                print(f"   响应JSON: {json.dumps(json_data, indent=2, ensure_ascii=False)}")
            except:
                print(f"   响应文本: {response.text}")
            print(f"   ✅ {name} 测试成功")
            return True
        else:
            print(f"   ❌ {name} 测试失败: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ {name} 测试异常: {e}")
        return False

def test_mcp_endpoint(base_url):
    """测试 MCP 端点"""
    print(f"\n🔌 测试 MCP 端点: {base_url}/mcp")
    try:
        # MCP 初始化请求
        init_request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {}},
                "clientInfo": {"name": "test-client", "version": "1.0.0"}
            }
        }
        
        headers = {"Content-Type": "application/json"}
        response = requests.post(f"{base_url}/mcp", 
                               json=init_request, 
                               headers=headers,
                               timeout=5)
        
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        print(f"   响应内容: {response.text}")
        
        if response.status_code == 200:
            print("   ✅ MCP 端点测试成功")
            return True
        else:
            print("   ❌ MCP 端点测试失败")
            return False
    except Exception as e:
        print(f"   ❌ MCP 端点测试异常: {e}")
        return False

def main():
    """主测试函数"""
    print("🧪 快速调试服务测试")
    print("=" * 50)
    
    base_url = "http://localhost:21923"
    
    # 等待服务启动
    print("⏳ 等待服务启动...")
    time.sleep(2)
    
    # 测试各个端点
    endpoints = [
        (f"{base_url}/", "根路径"),
        (f"{base_url}/health", "健康检查"),
        (f"{base_url}/debug", "调试信息"),
    ]
    
    results = []
    for url, name in endpoints:
        result = test_endpoint(url, name)
        results.append((name, result))
    
    # 测试 MCP 端点
    mcp_result = test_mcp_endpoint(base_url)
    results.append(("MCP端点", mcp_result))
    
    # 总结结果
    print("\n" + "=" * 50)
    print("📊 测试结果总结:")
    for name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"   {name}: {status}")
    
    all_passed = all(result for _, result in results)
    if all_passed:
        print("\n🎉 所有测试通过！服务运行正常")
    else:
        print("\n⚠️ 部分测试失败，请检查服务状态")
    
    print("\n💡 如果测试失败，请检查:")
    print("   1. 服务是否正在运行")
    print("   2. 端口 21923 是否被占用")
    print("   3. 查看服务日志 debug_service.log")

if __name__ == "__main__":
    main()
