#!/usr/bin/env python3
"""
测试MCP配置注册UI功能
模拟Web界面的MCP服务注册流程
"""

import sys
import os
import json

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

def simulate_mcp_config_reading():
    """模拟MCP配置读取过程"""
    print("📄 模拟MCP配置读取过程...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        if not api_client.test_connection():
            print("    ❌ API服务器未连接")
            return None
        
        # 获取MCP配置
        response = api_client.show_mcpconfig()
        
        if not response or not response.get('success'):
            print("    ❌ 无法读取MCP配置文件")
            return None
        
        mcp_config = response.get('data', {})
        mcpServers = mcp_config.get('mcpServers', {})
        
        if not mcpServers:
            print("    ⚠️ MCP配置文件中未找到服务配置")
            return None
        
        print(f"    ✅ 找到 {len(mcpServers)} 个服务配置")
        
        # 解析服务配置
        services_to_register = []
        for server_name, server_config in mcpServers.items():
            if isinstance(server_config, dict):
                # 检查是否是简化格式（直接包含url字段）
                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']
                    
                    if 'timeout' in server_config:
                        service_config["timeout"] = server_config['timeout']
                    
                    if 'headers' in server_config:
                        service_config["headers"] = server_config['headers']
                    
                    if 'env' in server_config:
                        service_config["env"] = server_config['env']
                    
                    services_to_register.append(service_config)
        
        print(f"    📊 解析出 {len(services_to_register)} 个可注册的服务:")
        for service in services_to_register:
            print(f"      - {service['name']}: {service['url']}")
        
        return services_to_register
        
    except Exception as e:
        print(f"    ❌ MCP配置读取失败: {e}")
        return None

def simulate_service_selection(services_to_register):
    """模拟服务选择过程"""
    print("\n📋 模拟服务选择过程...")
    
    if not services_to_register:
        print("    ⚠️ 没有可选择的服务")
        return []
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        # 获取当前已注册的服务名称
        current_services_response = api_client.list_services()
        current_service_names = []
        if current_services_response and current_services_response.get('data'):
            current_service_names = [s.get('name') for s in current_services_response['data']]
        
        print(f"    📊 当前已注册服务: {len(current_service_names)} 个")
        for name in current_service_names:
            print(f"      - {name}")
        
        # 筛选出未注册的服务
        selected_services = []
        for service in services_to_register:
            service_name = service.get('name')
            if service_name not in current_service_names:
                selected_services.append(service)
                print(f"    ✅ 选择注册: {service_name}")
            else:
                print(f"    ⚠️ 已存在，跳过: {service_name}")
        
        print(f"    📋 最终选择 {len(selected_services)} 个服务进行注册")
        return selected_services
        
    except Exception as e:
        print(f"    ❌ 服务选择过程失败: {e}")
        return []

def simulate_service_registration(selected_services):
    """模拟服务注册过程"""
    print("\n🚀 模拟服务注册过程...")
    
    if not selected_services:
        print("    ⚠️ 没有选择的服务需要注册")
        return True
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        print(f"    📤 开始注册 {len(selected_services)} 个服务...")
        
        response = api_client.batch_add_services(selected_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', [])
            if results:
                print("    📊 详细注册结果:")
                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}")
            
            return True
        else:
            error_msg = response.get('message', '未知错误') if response else '请求失败'
            print(f"    ❌ 批量注册失败: {error_msg}")
            return False
        
    except Exception as e:
        print(f"    ❌ 服务注册过程失败: {e}")
        return False

def test_complete_mcp_registration_flow():
    """测试完整的MCP注册流程"""
    print("🔄 测试完整的MCP注册流程...")
    
    # 步骤1: 读取MCP配置
    services_to_register = simulate_mcp_config_reading()
    if not services_to_register:
        print("    ❌ MCP配置读取失败，流程终止")
        return False
    
    # 步骤2: 选择要注册的服务
    selected_services = simulate_service_selection(services_to_register)
    
    # 步骤3: 注册选中的服务
    registration_success = simulate_service_registration(selected_services)
    
    if registration_success:
        print("    ✅ 完整MCP注册流程测试成功")
        return True
    else:
        print("    ❌ 完整MCP注册流程测试失败")
        return False

def test_mcp_config_parsing_edge_cases():
    """测试MCP配置解析的边界情况"""
    print("\n🔍 测试MCP配置解析边界情况...")
    
    edge_cases = [
        {
            "name": "空配置",
            "config": {"mcpServers": {}}
        },
        {
            "name": "无URL的服务",
            "config": {
                "mcpServers": {
                    "invalid_service": {
                        "description": "没有URL的服务"
                    }
                }
            }
        },
        {
            "name": "混合有效无效服务",
            "config": {
                "mcpServers": {
                    "valid_service": {
                        "url": "http://valid.com/mcp",
                        "transport": "auto"
                    },
                    "invalid_service": {
                        "description": "无效服务"
                    },
                    "another_valid": {
                        "url": "https://another.com/mcp"
                    }
                }
            }
        }
    ]
    
    for case in edge_cases:
        print(f"  - 测试 {case['name']}...")
        
        config = case['config']
        mcpServers = config.get('mcpServers', {})
        
        services_found = []
        
        for server_name, server_config in mcpServers.items():
            if isinstance(server_config, dict) and 'url' in server_config:
                service_config = {
                    "name": server_name,
                    "url": server_config['url'],
                    "description": server_config.get('description', f"从MCP配置导入: {server_name}")
                }
                services_found.append(service_config)
        
        print(f"    ✅ 解析出 {len(services_found)} 个有效服务")
        for service in services_found:
            print(f"      - {service['name']}: {service['url']}")
    
    return True

def main():
    """主测试函数"""
    print("🧪 MCP配置注册UI功能测试")
    print("=" * 60)
    
    tests = [
        ("MCP配置解析边界情况", test_mcp_config_parsing_edge_cases),
        ("完整MCP注册流程", test_complete_mcp_registration_flow)
    ]
    
    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("-" * 40)
    
    print(f"\n📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有MCP配置注册UI功能测试通过！")
        print("✅ MCP配置文件读取和服务注册UI功能正常")
        print("\n💡 现在您可以在Web界面中:")
        print("   1. 点击 '添加服务' 标签页")
        print("   2. 选择 '📄 根据MCP配置文件注册'")
        print("   3. 点击 '📖 读取MCP配置' 按钮")
        print("   4. 选择要注册的服务")
        print("   5. 点击 '🚀 注册选中服务' 完成注册")
    else:
        print("⚠️ 部分MCP配置注册UI功能测试失败，请检查相关模块")
    
    return passed == total

if __name__ == "__main__":
    main()
