#!/usr/bin/env python3
"""
测试MCP配置文件读取功能
验证从MCP配置文件注册服务的功能
"""

import sys
import os
import json

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def test_mcp_config_api():
    """测试MCP配置API"""
    print("📄 测试MCP配置API...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        if not api_client.test_connection():
            print("    ❌ API服务器未连接")
            return False
        
        # 测试获取MCP配置
        print("  - 测试获取MCP配置...")
        response = api_client.show_mcpconfig()
        
        if response and response.get('success'):
            print("    ✅ MCP配置获取成功")

            # 打印完整响应结构用于调试
            print(f"    🔍 响应结构: {response}")

            # API直接返回配置数据，不是包装在content字段中
            config_data = response.get('data', {})

            if config_data:
                print(f"    📄 配置数据: {config_data}")

                # 检查mcpServers字段
                if 'mcpServers' in config_data:
                    servers = config_data['mcpServers']
                    print(f"    📊 找到 {len(servers)} 个服务配置")

                    # 显示服务信息
                    for server_name, server_config in servers.items():
                        if isinstance(server_config, dict):
                            url = server_config.get('url', 'N/A')
                            transport = server_config.get('transport', 'auto')
                            print(f"      - {server_name}: {url} ({transport})")
                else:
                    print("    ⚠️ 配置中未找到mcpServers字段")
            else:
                print("    ⚠️ 配置数据为空")
        else:
            print("    ❌ MCP配置获取失败")
            return False
        
        return True
        
    except Exception as e:
        print(f"    ❌ MCP配置API测试失败: {e}")
        return False

def test_mcp_config_parsing():
    """测试MCP配置解析逻辑"""
    print("\n🔍 测试MCP配置解析逻辑...")
    
    # 模拟不同格式的MCP配置
    test_configs = [
        {
            "name": "简化格式配置",
            "config": {
                "mcpServers": {
                    "高德": {
                        "url": "https://mcp.amap.com/sse?key=test",
                        "transport": "sse"
                    },
                    "天气服务": {
                        "url": "http://127.0.0.1:8000/mcp",
                        "description": "本地天气服务"
                    }
                }
            }
        },
        {
            "name": "标准格式配置",
            "config": {
                "mcpServers": {
                    "test_service": {
                        "command": "python",
                        "args": ["server.py", "http://example.com/mcp"],
                        "env": {
                            "API_KEY": "test_key"
                        }
                    }
                }
            }
        },
        {
            "name": "混合格式配置",
            "config": {
                "mcpServers": {
                    "simple_service": {
                        "url": "http://simple.com/mcp",
                        "transport": "auto"
                    },
                    "complex_service": {
                        "command": "node",
                        "args": ["index.js", "http://complex.com/mcp"],
                        "env": {
                            "NODE_ENV": "production"
                        }
                    }
                }
            }
        }
    ]
    
    for test_case in test_configs:
        print(f"  - 测试 {test_case['name']}...")
        
        config = test_case['config']
        mcpServers = config.get('mcpServers', {})
        
        services_found = []
        
        for server_name, server_config in mcpServers.items():
            if isinstance(server_config, dict):
                # 检查是否是简化格式
                if 'url' in server_config:
                    service_config = {
                        "name": server_name,
                        "url": server_config['url'],
                        "description": server_config.get('description', f"从MCP配置导入: {server_name}")
                    }
                    
                    if 'transport' in server_config:
                        service_config["transport"] = server_config['transport']
                    
                    services_found.append(service_config)
                
                else:
                    # 标准格式
                    command = server_config.get('command')
                    args = server_config.get('args', [])
                    
                    url = None
                    if args:
                        for arg in args:
                            if isinstance(arg, str) and (arg.startswith('http') or '/mcp' in arg):
                                url = arg
                                break
                    
                    if url:
                        service_config = {
                            "name": server_name,
                            "url": url,
                            "description": f"从MCP配置导入: {command}"
                        }
                        
                        if 'env' in server_config:
                            service_config["env"] = server_config['env']
                        
                        services_found.append(service_config)
        
        print(f"    ✅ 解析出 {len(services_found)} 个服务:")
        for service in services_found:
            print(f"      - {service['name']}: {service['url']}")
    
    return True

def test_service_registration_simulation():
    """模拟服务注册测试"""
    print("\n🚀 模拟服务注册测试...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        if not api_client.test_connection():
            print("    ⚠️ API服务器未连接，跳过注册测试")
            return True
        
        # 模拟从MCP配置解析出的服务
        mock_services = [
            {
                "name": "mcp_test_service_1",
                "url": "http://example1.com/mcp",
                "description": "从MCP配置导入的测试服务1",
                "transport": "auto"
            },
            {
                "name": "mcp_test_service_2", 
                "url": "http://example2.com/mcp",
                "description": "从MCP配置导入的测试服务2",
                "transport": "sse"
            }
        ]
        
        print(f"  - 模拟注册 {len(mock_services)} 个服务...")
        
        response = api_client.batch_add_services(mock_services)
        
        if response and response.get('success'):
            summary = response.get('data', {}).get('summary', {})
            success_count = summary.get('success', 0)
            total_count = summary.get('total', 0)
            
            print(f"    ✅ 批量注册完成: {success_count}/{total_count} 个服务注册成功")
            
            # 显示详细结果
            results = response.get('data', {}).get('results', [])
            for result in results:
                service_name = result.get('name', 'Unknown')
                success = result.get('success', False)
                
                if success:
                    print(f"      ✅ {service_name}: 注册成功")
                else:
                    error = result.get('error', '未知错误')
                    print(f"      ❌ {service_name}: {error}")
        else:
            print("    ⚠️ 批量注册API调用失败")
        
        return True
        
    except Exception as e:
        print(f"    ❌ 服务注册模拟测试失败: {e}")
        return False

def main():
    """主测试函数"""
    print("🧪 MCP配置读取功能测试")
    print("=" * 50)
    
    tests = [
        ("MCP配置API", test_mcp_config_api),
        ("MCP配置解析逻辑", test_mcp_config_parsing),
        ("服务注册模拟", test_service_registration_simulation)
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n🔬 运行测试: {test_name}")
        try:
            if test_func():
                passed += 1
                print(f"✅ {test_name} - 通过")
            else:
                print(f"❌ {test_name} - 失败")
        except Exception as e:
            print(f"❌ {test_name} - 异常: {e}")
        
        print("-" * 30)
    
    print(f"\n📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有MCP配置读取功能测试通过！")
        print("✅ MCP配置文件读取和服务注册功能正常")
    else:
        print("⚠️ 部分MCP配置功能测试失败，请检查相关模块")
    
    return passed == total

if __name__ == "__main__":
    main()
