#!/usr/bin/env python3
"""
测试 MCPStoreWiki 服务的脚本
用于验证服务是否正常工作，特别是通过反向代理访问时
"""

import requests
import json
import time

def test_health_check(base_url):
    """测试健康检查端点"""
    print("🔍 测试健康检查端点...")
    try:
        response = requests.get(f"{base_url}/health", timeout=10)
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        if response.status_code == 200:
            print(f"   响应内容: {response.json()}")
            print("   ✅ 健康检查通过")
            return True
        else:
            print(f"   ❌ 健康检查失败: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ 健康检查异常: {e}")
        return False

def test_root_endpoint(base_url):
    """测试根端点"""
    print("\n🏠 测试根端点...")
    try:
        response = requests.get(base_url, timeout=10)
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        if response.status_code == 200:
            print(f"   响应内容: {response.json()}")
            print("   ✅ 根端点访问成功")
            return True
        else:
            print(f"   ❌ 根端点访问失败: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ 根端点访问异常: {e}")
        return False

def test_mcp_endpoint(base_url):
    """测试 MCP 端点"""
    print("\n🔌 测试 MCP 端点...")
    try:
        # 测试 MCP 初始化请求
        mcp_url = f"{base_url}/mcp"
        
        # 发送 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",
            "Accept": "application/json"
        }
        
        print(f"   发送初始化请求到: {mcp_url}")
        print(f"   请求头: {headers}")
        print(f"   请求体: {json.dumps(init_request, indent=2)}")
        
        response = requests.post(mcp_url, 
                               json=init_request, 
                               headers=headers,
                               timeout=10)
        
        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(f"   ❌ MCP 端点访问失败")
            return False
            
    except Exception as e:
        print(f"   ❌ MCP 端点访问异常: {e}")
        return False

def main():
    """主测试函数"""
    print("🧪 MCPStoreWiki 服务测试")
    print("=" * 60)
    
    # 测试不同的 URL
    test_urls = [
        "http://localhost:21923",  # 直接访问
        "http://127.0.0.1:21923",  # 本地访问
        # 如果您有域名，可以添加：
        # "https://your-domain.com",  # 通过 nginx 反向代理访问
    ]
    
    for base_url in test_urls:
        print(f"\n🎯 测试服务地址: {base_url}")
        print("-" * 40)
        
        # 测试健康检查
        health_ok = test_health_check(base_url)
        
        # 测试根端点
        root_ok = test_root_endpoint(base_url)
        
        # 测试 MCP 端点
        mcp_ok = test_mcp_endpoint(base_url)
        
        # 总结
        print(f"\n📊 {base_url} 测试结果:")
        print(f"   健康检查: {'✅' if health_ok else '❌'}")
        print(f"   根端点: {'✅' if root_ok else '❌'}")
        print(f"   MCP端点: {'✅' if mcp_ok else '❌'}")
        
        if health_ok and root_ok and mcp_ok:
            print(f"   🎉 {base_url} 全部测试通过！")
        else:
            print(f"   ⚠️ {base_url} 部分测试失败")
    
    print("\n" + "=" * 60)
    print("测试完成！")
    print("\n💡 如果通过反向代理访问失败，请检查：")
    print("1. nginx 配置是否正确")
    print("2. 防火墙是否开放端口")
    print("3. 服务是否正在运行")
    print("4. 查看服务日志文件 mcpstorewiki.log")

if __name__ == "__main__":
    main()
