#!/usr/bin/env python3
"""
测试Web端功能是否正常使用
验证页面导入、API调用、组件渲染等
"""

import sys
import os
import importlib
import traceback

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

def test_imports():
    """测试所有模块导入"""
    print("📦 测试模块导入...")
    
    modules_to_test = [
        # 核心模块
        ('utils.api_client', 'API客户端'),
        ('utils.config_manager', '配置管理器'),
        ('utils.helpers', '辅助函数'),
        ('utils.tool_history', '工具历史'),
        
        # 页面模块
        ('pages.service_management', '服务管理页面'),
        ('pages.tool_management', '工具管理页面'),
        ('pages.agent_management', 'Agent管理页面'),
        ('pages.monitoring', '监控页面'),
        ('pages.configuration', '配置页面'),
        ('pages.api_showcase', 'API展示页面'),
        
        # 组件模块
        ('components.ui_components', 'UI组件'),
        ('components.service_components', '服务组件'),
    ]
    
    success_count = 0
    total_count = len(modules_to_test)
    
    for module_name, description in modules_to_test:
        try:
            module = importlib.import_module(module_name)
            print(f"    ✅ {description}: {module_name}")
            success_count += 1
        except Exception as e:
            print(f"    ❌ {description}: {module_name} - {e}")
    
    print(f"    📊 导入成功率: {success_count}/{total_count} ({success_count/total_count*100:.1f}%)")
    return success_count == total_count

def test_api_client_functionality():
    """测试API客户端功能"""
    print("\n🔌 测试API客户端功能...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        # 测试HTTP后端
        print("  - 测试HTTP后端...")
        http_client = MCPStoreAPI("http", "http://localhost:18611")
        
        # 测试连接
        if http_client.test_connection():
            print("    ✅ HTTP后端连接成功")
            
            # 测试基础API调用
            try:
                services = http_client.list_services()
                if services:
                    print(f"    ✅ 服务列表获取成功: {len(services.get('data', []))} 个服务")
                else:
                    print("    ⚠️ 服务列表为空")
                
                # 测试健康检查
                health = http_client.health()
                if health:
                    print("    ✅ 健康检查成功")
                else:
                    print("    ⚠️ 健康检查失败")
                
                # 测试统计信息
                stats = http_client.get_stats()
                if stats:
                    print("    ✅ 统计信息获取成功")
                else:
                    print("    ⚠️ 统计信息获取失败")
                
            except Exception as e:
                print(f"    ❌ API调用测试失败: {e}")
                return False
        else:
            print("    ❌ HTTP后端连接失败")
            return False
        
        # 测试Direct后端
        print("  - 测试Direct后端...")
        try:
            direct_client = MCPStoreAPI("direct")
            print("    ✅ Direct后端创建成功")
        except Exception as e:
            print(f"    ⚠️ Direct后端创建失败: {e}")
        
        return True
        
    except Exception as e:
        print(f"    ❌ API客户端测试失败: {e}")
        return False

def test_tool_history_functionality():
    """测试工具历史功能"""
    print("\n📝 测试工具历史功能...")
    
    try:
        from utils.tool_history import (
            get_history_manager, record_tool_usage, 
            get_tool_statistics, clear_tool_history
        )
        
        # 清空历史
        clear_tool_history()
        print("    ✅ 历史记录清空成功")
        
        # 添加测试记录
        test_records = [
            ("test_tool_1", {"param": "value1"}, {"result": "success"}, True, 1.0),
            ("test_tool_2", {"param": "value2"}, {"result": "success"}, True, 0.5),
            ("test_tool_1", {"param": "value3"}, {"error": "failed"}, False, 2.0),
        ]
        
        for tool_name, args, result, success, exec_time in test_records:
            record_tool_usage(tool_name, args, result, success, exec_time)
        
        print(f"    ✅ 添加 {len(test_records)} 条测试记录")
        
        # 测试统计
        stats = get_tool_statistics()
        expected_total = len(test_records)
        actual_total = stats['total_executions']
        
        if actual_total == expected_total:
            print(f"    ✅ 统计功能正常: {actual_total} 条记录")
            print(f"      - 成功率: {stats['success_rate']:.1f}%")
            print(f"      - 工具数量: {stats['unique_tools']}")
        else:
            print(f"    ❌ 统计功能异常: 期望 {expected_total}，实际 {actual_total}")
            return False
        
        return True
        
    except Exception as e:
        print(f"    ❌ 工具历史功能测试失败: {e}")
        traceback.print_exc()
        return False

def test_page_functions():
    """测试页面函数"""
    print("\n📄 测试页面函数...")
    
    pages_to_test = [
        ('pages.service_management', 'show'),
        ('pages.tool_management', 'show'),
        ('pages.agent_management', 'show'),
        ('pages.monitoring', 'show'),
        ('pages.configuration', 'show'),
        ('pages.api_showcase', 'show'),
    ]
    
    success_count = 0
    total_count = len(pages_to_test)
    
    for module_name, function_name in pages_to_test:
        try:
            module = importlib.import_module(module_name)
            if hasattr(module, function_name):
                print(f"    ✅ {module_name}.{function_name}() 存在")
                success_count += 1
            else:
                print(f"    ❌ {module_name}.{function_name}() 不存在")
        except Exception as e:
            print(f"    ❌ {module_name} 导入失败: {e}")
    
    print(f"    📊 页面函数完整性: {success_count}/{total_count} ({success_count/total_count*100:.1f}%)")
    return success_count == total_count

def test_component_functions():
    """测试组件函数"""
    print("\n🧩 测试组件函数...")
    
    try:
        from utils.helpers import (
            show_success_message, show_error_message, show_warning_message,
            validate_url, validate_service_name, format_json
        )
        print("    ✅ 辅助函数导入成功")
        
        # 测试格式化函数
        test_data = {"test": "data", "number": 123}
        formatted = format_json(test_data)
        if formatted and isinstance(formatted, str):
            print("    ✅ JSON格式化功能正常")
        else:
            print("    ❌ JSON格式化功能异常")
            return False
        
        # 测试验证函数
        if validate_url("http://example.com"):
            print("    ✅ URL验证功能正常")
        else:
            print("    ❌ URL验证功能异常")
            return False
        
        if validate_service_name("test_service"):
            print("    ✅ 服务名验证功能正常")
        else:
            print("    ❌ 服务名验证功能异常")
            return False
        
        return True
        
    except Exception as e:
        print(f"    ❌ 组件函数测试失败: {e}")
        return False

def test_file_structure():
    """测试文件结构"""
    print("\n📁 测试文件结构...")
    
    required_files = [
        'app.py',
        'utils/api_client.py',
        'utils/config_manager.py',
        'utils/helpers.py',
        'utils/tool_history.py',
        'pages/service_management.py',
        'pages/tool_management.py',
        'pages/agent_management.py',
        'pages/monitoring.py',
        'pages/configuration.py',
        'pages/api_showcase.py',
        'components/ui_components.py',
        'components/service_components.py',
    ]
    
    missing_files = []
    
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"    ✅ {file_path}")
        else:
            print(f"    ❌ {file_path} - 文件缺失")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"    ⚠️ 缺失 {len(missing_files)} 个文件")
        return False
    else:
        print("    ✅ 所有必需文件都存在")
        return True

def main():
    """主测试函数"""
    print("🧪 MCPStore Web端功能测试")
    print("=" * 50)
    
    tests = [
        ("文件结构", test_file_structure),
        ("模块导入", test_imports),
        ("API客户端功能", test_api_client_functionality),
        ("工具历史功能", test_tool_history_functionality),
        ("页面函数", test_page_functions),
        ("组件函数", test_component_functions),
    ]
    
    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("🎉 所有Web功能测试通过！")
        print("✅ MCPStore Web项目可以正常使用")
    else:
        print("⚠️ 部分Web功能测试失败，请检查相关模块")
    
    return passed == total

if __name__ == "__main__":
    main()
