"""
智能算法展示平台 - 测试运行脚本

此脚本用于运行各种类型的测试，包括单元测试、集成测试和端到端测试。
"""

import os
import sys
import subprocess
import argparse
import unittest
import time
from pathlib import Path


def run_unit_tests():
    """运行单元测试"""
    print("🚀 开始运行单元测试...")
    
    # 查找所有测试文件
    test_dir = Path(__file__).parent
    backend_dir = test_dir.parent / "backend"
    
    # 运行Python单元测试
    try:
        result = subprocess.run([
            sys.executable, "-m", "unittest", "discover", 
            str(backend_dir), "-p", "*_test.py", "-v"
        ], cwd=str(test_dir.parent), capture_output=True, text=True)
        
        print("单元测试输出:")
        print(result.stdout)
        if result.stderr:
            print("单元测试错误:")
            print(result.stderr)
            
        return result.returncode == 0
    except Exception as e:
        print(f"运行单元测试时出错: {e}")
        return False


def run_integration_tests():
    """运行集成测试"""
    print("⚙️ 开始运行集成测试...")
    
    test_file = Path(__file__).parent / "integration_tests.py"
    
    if not test_file.exists():
        print("⚠️ 集成测试文件不存在，跳过...")
        return True
    
    try:
        result = subprocess.run([
            sys.executable, str(test_file)
        ], cwd=str(test_file.parent), capture_output=True, text=True)
        
        print("集成测试输出:")
        print(result.stdout)
        if result.stderr:
            print("集成测试错误:")
            print(result.stderr)
            
        return result.returncode == 0
    except Exception as e:
        print(f"运行集成测试时出错: {e}")
        return False


def run_e2e_tests():
    """运行端到端测试"""
    print("🌐 开始运行端到端测试...")
    
    # 检查服务是否运行
    import requests
    from integration_test_config import get_test_config
    
    config = get_test_config()
    health_url = config.get_api_url("/monitoring/health")
    
    try:
        response = requests.get(health_url, headers=config.get_auth_headers(), timeout=10)
        if response.status_code == 200:
            print("✅ 服务正在运行，可以执行端到端测试")
            
            # 这里可以添加实际的端到端测试逻辑
            print("正在进行端到端测试...")
            
            # 示例：测试API的基本功能
            algorithms_url = config.get_api_url("/algorithms")
            response = requests.get(algorithms_url, headers=config.get_auth_headers())
            
            if response.status_code == 200:
                print("✅ 端到端测试 - 算法API访问正常")
                return True
            else:
                print(f"❌ 端到端测试失败 - 状态码: {response.status_code}")
                return False
        else:
            print("⚠️ 服务未运行，跳过端到端测试")
            return True  # 不将此视为失败，因为可能是预期的
    except requests.exceptions.ConnectionError:
        print("⚠️ 无法连接到服务，跳过端到端测试")
        return True  # 不将此视为失败
    except Exception as e:
        print(f"运行端到端测试时出错: {e}")
        return False


def run_load_tests():
    """运行负载测试"""
    print("📈 开始运行负载测试...")
    
    # 这里可以集成如locust等负载测试工具
    print("负载测试通常需要单独的工具，如Locust或JMeter")
    print("当前环境跳过负载测试...")
    return True


def generate_test_report(results):
    """生成测试报告"""
    print("\n" + "="*60)
    print("📊 测试报告")
    print("="*60)
    
    total_tests = len(results)
    passed_tests = sum(1 for result in results.values() if result)
    failed_tests = total_tests - passed_tests
    
    print(f"总测试类别: {total_tests}")
    print(f"通过: {passed_tests}")
    print(f"失败: {failed_tests}")
    
    for test_name, result in results.items():
        status = "✅ PASS" if result else "❌ FAIL"
        print(f"- {test_name}: {status}")
    
    print("="*60)
    
    if failed_tests == 0:
        print("🎉 所有测试都通过了！")
        return True
    else:
        print(f"⚠️ 有 {failed_tests} 个测试类别失败")
        return False


def main():
    parser = argparse.ArgumentParser(description='运行智能算法展示平台测试')
    parser.add_argument('--unit', action='store_true', help='运行单元测试')
    parser.add_argument('--integration', action='store_true', help='运行集成测试')
    parser.add_argument('--e2e', action='store_true', help='运行端到端测试')
    parser.add_argument('--load', action='store_true', help='运行负载测试')
    parser.add_argument('--all', action='store_true', help='运行所有测试')
    parser.add_argument('--verbose', '-v', action='store_true', help='详细输出')
    
    args = parser.parse_args()
    
    # 如果没有指定任何测试类型，则运行所有测试
    if not any([args.unit, args.integration, args.e2e, args.load, args.all]):
        args.all = True
    
    print("🧪 智能算法展示平台测试运行器")
    print("-" * 40)
    
    results = {}
    
    # 根据参数决定运行哪些测试
    test_functions = []
    
    if args.all or args.unit:
        test_functions.append(("单元测试", run_unit_tests))
    
    if args.all or args.integration:
        test_functions.append(("集成测试", run_integration_tests))
    
    if args.all or args.e2e:
        test_functions.append(("端到端测试", run_e2e_tests))
    
    if args.all or args.load:
        test_functions.append(("负载测试", run_load_tests))
    
    # 运行测试
    for test_name, test_func in test_functions:
        print(f"\n{'='*20} {test_name} {'='*20}")
        start_time = time.time()
        
        try:
            result = test_func()
            elapsed_time = time.time() - start_time
            
            results[test_name] = result
            status = "✅ 通过" if result else "❌ 失败"
            print(f"\n{test_name}结果: {status} (耗时: {elapsed_time:.2f}秒)")
            
        except KeyboardInterrupt:
            print("\n⚠️ 测试被用户中断")
            results[test_name] = False
            break
        except Exception as e:
            print(f"\n❌ {test_name}执行时发生错误: {e}")
            results[test_name] = False
    
    # 生成报告
    all_passed = generate_test_report(results)
    
    # 设置退出码
    sys.exit(0 if all_passed else 1)


if __name__ == "__main__":
    main()