#!/usr/bin/env python3
"""UVM 快速测试脚本

这个脚本提供了一些常用的测试场景，方便快速验证功能。
"""

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


def run_command(cmd, description="", capture_output=False):
    """运行命令并处理结果"""
    print(f"\n🔍 {description}")
    print(f"执行: {' '.join(cmd)}")
    print("-" * 50)
    
    try:
        if capture_output:
            result = subprocess.run(cmd, check=True, capture_output=True, text=True)
            print(result.stdout)
            return result.stdout
        else:
            result = subprocess.run(cmd, check=True)
            print(f"✅ 成功: {description}")
            return True
    except subprocess.CalledProcessError as e:
        if capture_output:
            print(f"❌ 失败: {description}")
            print(f"错误输出: {e.stderr}")
        else:
            print(f"❌ 失败: {description} (退出码: {e.returncode})")
        return False
    except FileNotFoundError:
        print(f"❌ 命令未找到: {cmd[0]}")
        return False


def test_basic_commands():
    """测试基本命令"""
    print("\n🧪 测试基本命令...")
    
    success = True
    
    # 测试版本信息
    success &= run_command([sys.executable, "-m", "uvm", "--version"], "显示版本信息")
    
    # 测试列出镜像源
    success &= run_command([sys.executable, "-m", "uvm", "list"], "列出镜像源")
    
    # 测试显示当前镜像源
    success &= run_command([sys.executable, "-m", "uvm", "current"], "显示当前镜像源")
    
    return success


def test_mirror_operations():
    """测试镜像源操作"""
    print("\n🔄 测试镜像源操作...")
    
    success = True
    
    # 获取当前镜像源
    current_output = run_command(
        [sys.executable, "-m", "uvm", "current"], 
        "获取当前镜像源", 
        capture_output=True
    )
    
    if not current_output:
        return False
    
    # 测试切换到清华源
    success &= run_command([sys.executable, "-m", "uvm", "use", "tsinghua"], "切换到清华源")
    
    # 等待一下确保切换完成
    time.sleep(1)
    
    # 验证切换结果
    success &= run_command([sys.executable, "-m", "uvm", "current"], "验证切换结果")
    
    # 测试搜索功能
    success &= run_command([sys.executable, "-m", "uvm", "search", "tsinghua"], "搜索镜像源")
    
    return success


def test_speed_test():
    """测试速度测试功能"""
    print("\n⚡ 测试速度测试功能...")
    
    # 使用较短的超时时间进行快速测试
    success = run_command(
        [sys.executable, "-m", "uvm", "test", "--timeout", "2.0"], 
        "测试镜像源速度"
    )
    
    return success


def test_custom_mirror():
    """测试自定义镜像源功能"""
    print("\n🔧 测试自定义镜像源功能...")
    
    success = True
    
    # 添加测试镜像源
    test_mirror_name = "test-mirror"
    test_mirror_url = "https://pypi.tuna.tsinghua.edu.cn/simple"
    
    success &= run_command([
        sys.executable, "-m", "uvm", "add", 
        test_mirror_name, test_mirror_url,
        "--description", "测试镜像源",
        "--region", "CN"
    ], "添加测试镜像源")
    
    # 列出镜像源验证添加结果
    success &= run_command([sys.executable, "-m", "uvm", "list"], "验证添加结果")
    
    # 删除测试镜像源
    success &= run_command([
        sys.executable, "-m", "uvm", "remove", test_mirror_name
    ], "删除测试镜像源")
    
    return success


def test_error_handling():
    """测试错误处理"""
    print("\n⚠️  测试错误处理...")
    
    success = True
    
    # 测试不存在的镜像源
    success &= not run_command(
        [sys.executable, "-m", "uvm", "use", "nonexistent-mirror"], 
        "使用不存在的镜像源（应该失败）",
        capture_output=True
    )
    
    # 测试无效的URL
    success &= not run_command(
        [sys.executable, "-m", "uvm", "add", "invalid-mirror", "invalid-url"], 
        "添加无效URL（应该失败）",
        capture_output=True
    )
    
    return success


def run_unit_tests():
    """运行单元测试"""
    print("\n🧪 运行单元测试...")
    
    success = run_command([
        sys.executable, "-m", "pytest", 
        "tests/unit/", 
        "-v", 
        "--tb=short"
    ], "运行单元测试")
    
    return success


def run_integration_tests():
    """运行集成测试"""
    print("\n🔗 运行集成测试...")
    
    success = run_command([
        sys.executable, "-m", "pytest", 
        "tests/integration/", 
        "-v", 
        "--tb=short"
    ], "运行集成测试")
    
    return success


def main():
    """主函数"""
    print("🚀 UVM 快速测试脚本")
    print("=" * 50)
    
    # 检查是否在项目根目录
    if not Path("pyproject.toml").exists():
        print("❌ 错误: 请在项目根目录运行此脚本")
        return False
    
    # 检查依赖是否安装
    try:
        import uvm
    except ImportError:
        print("❌ 错误: UVM 未安装，请先运行 'python -m pip install -e .'")
        return False
    
    # 运行测试
    test_results = []
    
    test_results.append(("基本命令测试", test_basic_commands()))
    test_results.append(("镜像源操作测试", test_mirror_operations()))
    test_results.append(("速度测试功能", test_speed_test()))
    test_results.append(("自定义镜像源测试", test_custom_mirror()))
    test_results.append(("错误处理测试", test_error_handling()))
    test_results.append(("单元测试", run_unit_tests()))
    test_results.append(("集成测试", run_integration_tests()))
    
    # 显示测试结果
    print("\n" + "=" * 50)
    print("📊 测试结果汇总:")
    print("-" * 50)
    
    passed = 0
    total = len(test_results)
    
    for test_name, result in test_results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{test_name:<20} {status}")
        if result:
            passed += 1
    
    print("-" * 50)
    print(f"总计: {passed}/{total} 个测试通过")
    
    if passed == total:
        print("🎉 所有测试通过!")
        return True
    else:
        print("💥 部分测试失败!")
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)