#!/usr/bin/env python3
"""
测试 nginx 反向代理的脚本
对比直接访问和通过域名访问的差异
"""

import requests
import json
import time

def test_mcp_endpoint(base_url, name):
    """测试 MCP 端点"""
    print(f"\n🔌 测试 {name}: {base_url}")
    print("-" * 60)
    
    # MCP 初始化请求
    init_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {"tools": {}},
            "clientInfo": {"name": "nginx-test-client", "version": "1.0.0"}
        }
    }
    
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "MCPStore-NginxTest/1.0",
        "X-Test-Source": name,
        "Accept": "application/json"
    }
    
    print(f"📤 发送请求:")
    print(f"   URL: {base_url}")
    print(f"   方法: POST")
    print(f"   请求头: {json.dumps(headers, indent=2)}")
    print(f"   请求体: {json.dumps(init_request, indent=2)}")
    
    try:
        start_time = time.time()
        response = requests.post(base_url, 
                               json=init_request, 
                               headers=headers,
                               timeout=10)
        end_time = time.time()
        
        print(f"\n📥 收到响应:")
        print(f"   状态码: {response.status_code}")
        print(f"   响应时间: {(end_time - start_time):.3f}秒")
        print(f"   响应头: {json.dumps(dict(response.headers), indent=2)}")
        
        if response.status_code == 200:
            try:
                result = response.json()
                print(f"   ✅ 成功 - 响应内容: {json.dumps(result, indent=2, ensure_ascii=False)}")
                return True
            except json.JSONDecodeError:
                print(f"   ⚠️ 响应不是有效JSON: {response.text}")
                return False
        else:
            print(f"   ❌ 失败 - 响应内容: {response.text}")
            return False
            
    except requests.exceptions.Timeout:
        print(f"   ❌ 请求超时")
        return False
    except requests.exceptions.ConnectionError as e:
        print(f"   ❌ 连接错误: {e}")
        return False
    except Exception as e:
        print(f"   ❌ 其他错误: {e}")
        return False

def test_get_request(url, name):
    """测试 GET 请求（用于对比）"""
    print(f"\n🌐 测试 GET 请求 {name}: {url}")
    
    try:
        response = requests.get(url, timeout=5)
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            print(f"   ✅ GET 请求成功")
            try:
                result = response.json()
                print(f"   响应: {json.dumps(result, indent=2, ensure_ascii=False)}")
            except:
                print(f"   响应文本: {response.text[:200]}...")
        else:
            print(f"   ❌ GET 请求失败: {response.text}")
            
    except Exception as e:
        print(f"   ❌ GET 请求异常: {e}")

def main():
    """主测试函数"""
    print("🧪 nginx 反向代理测试")
    print("=" * 80)
    
    # 测试配置
    test_configs = [
        {
            "name": "直接IP访问",
            "mcp_url": "http://59.110.160.18:21923/mcp",
            "base_url": "http://59.110.160.18:21923"
        },
        {
            "name": "域名访问",
            "mcp_url": "http://mcpstore.wiki/mcp",
            "base_url": "http://mcpstore.wiki"
        }
    ]
    
    results = []
    
    for config in test_configs:
        print(f"\n{'='*20} {config['name']} {'='*20}")
        
        # 测试 GET 请求到根路径（如果有健康检查）
        test_get_request(config['base_url'], config['name'])
        
        # 测试 MCP 端点
        success = test_mcp_endpoint(config['mcp_url'], config['name'])
        results.append((config['name'], success))
    
    # 总结结果
    print(f"\n{'='*80}")
    print("📊 测试结果总结:")
    for name, success in results:
        status = "✅ 成功" if success else "❌ 失败"
        print(f"   {name}: {status}")
    
    # 分析和建议
    direct_success = results[0][1] if len(results) > 0 else False
    proxy_success = results[1][1] if len(results) > 1 else False
    
    print(f"\n💡 分析和建议:")
    
    if direct_success and not proxy_success:
        print("   🔍 直接访问成功，代理访问失败 - nginx 配置问题")
        print("   📝 建议检查:")
        print("      1. nginx 路径映射是否正确")
        print("      2. proxy_pass 配置是否正确")
        print("      3. 请求头是否被正确转发")
        print("      4. 是否有防火墙或安全组限制")
        
        print(f"\n🔧 推荐的 nginx 配置:")
        print("   location /mcp {")
        print("       proxy_pass http://127.0.0.1:21923/mcp;")
        print("       proxy_set_header Host $host;")
        print("       proxy_set_header X-Real-IP $remote_addr;")
        print("       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;")
        print("       proxy_set_header X-Forwarded-Proto $scheme;")
        print("       proxy_http_version 1.1;")
        print("       proxy_buffering off;")
        print("   }")
        
    elif not direct_success and not proxy_success:
        print("   ❌ 直接访问和代理访问都失败 - 服务问题")
        print("   📝 建议检查:")
        print("      1. 服务是否正在运行")
        print("      2. 端口是否正确")
        print("      3. 防火墙设置")
        
    elif direct_success and proxy_success:
        print("   🎉 所有测试都成功！nginx 代理配置正确")
        
    else:
        print("   🤔 异常情况，需要进一步调查")

if __name__ == "__main__":
    main()
