#!/usr/bin/env python3
"""
功能测试脚本 - 验证各个模块是否正常工作
"""

import subprocess
import json
import sys
from pathlib import Path

def run_command(exe_path, module, action, params=None):
    """运行命令并返回结果"""
    cmd = [str(exe_path), '--module', module, '--action', action]
    
    if params:
        cmd.extend(['--params', json.dumps(params)])
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if result.returncode == 0:
            try:
                return True, json.loads(result.stdout)
            except json.JSONDecodeError:
                return True, {"raw_output": result.stdout}
        else:
            return False, {
                "error": result.stderr,
                "stdout": result.stdout,
                "returncode": result.returncode
            }
    except subprocess.TimeoutExpired:
        return False, {"error": "Command timed out"}
    except Exception as e:
        return False, {"error": str(e)}

def test_basic_functionality(exe_path):
    """测试基础功能"""
    print("🧪 Testing basic functionality...")
    
    tests = [
        # 基础测试
        ("test", "hello", None),
        ("test", "echo", {"message": "Hello World"}),
        
        # 版本测试
        ("test", "version", None),
    ]
    
    results = []
    for module, action, params in tests:
        print(f"  Testing {module}.{action}...")
        success, result = run_command(exe_path, module, action, params)
        results.append({
            "test": f"{module}.{action}",
            "success": success,
            "result": result
        })
        
        if success:
            print(f"    ✅ Success")
        else:
            print(f"    ❌ Failed: {result.get('error', 'Unknown error')}")
    
    return results

def test_service_modules(exe_path):
    """测试服务模块"""
    print("🔧 Testing service modules...")
    
    tests = [
        # 模板管理测试
        ("template_manager", "get_templates", None),
        
        # 项目管理测试
        ("project_manager", "get_projects", None),
        
        # 媒体管理测试
        ("media_manager", "get_media_list", None),
        
        # 音频管理测试
        ("audio_manager", "get_audio_list", None),
        
        # 模特管理测试
        ("model_manager", "get_models", None),
        
        # 资源分类测试
        ("resource_category_manager", "get_all_categories", None),
        
        # 文件管理测试
        ("file_manager", "list_files", {"path": "."}),
    ]
    
    results = []
    for module, action, params in tests:
        print(f"  Testing {module}.{action}...")
        success, result = run_command(exe_path, module, action, params)
        results.append({
            "test": f"{module}.{action}",
            "success": success,
            "result": result
        })
        
        if success:
            print(f"    ✅ Success")
        else:
            print(f"    ❌ Failed: {result.get('error', 'Unknown error')}")
    
    return results

def test_ai_modules(exe_path):
    """测试AI模块"""
    print("🤖 Testing AI modules...")
    
    tests = [
        # AI视频生成测试
        ("ai_video", "test_environment", None),
        ("video_generator", "get_status", None),
    ]
    
    results = []
    for module, action, params in tests:
        print(f"  Testing {module}.{action}...")
        success, result = run_command(exe_path, module, action, params)
        results.append({
            "test": f"{module}.{action}",
            "success": success,
            "result": result
        })
        
        if success:
            print(f"    ✅ Success")
        else:
            print(f"    ❌ Failed: {result.get('error', 'Unknown error')}")
    
    return results

def generate_report(all_results):
    """生成测试报告"""
    print("\n📊 Test Report")
    print("=" * 50)
    
    total_tests = 0
    passed_tests = 0
    
    for category, results in all_results.items():
        print(f"\n{category}:")
        for result in results:
            total_tests += 1
            if result['success']:
                passed_tests += 1
                status = "✅ PASS"
            else:
                status = "❌ FAIL"
            
            print(f"  {result['test']}: {status}")
            
            if not result['success']:
                error = result['result'].get('error', 'Unknown error')
                print(f"    Error: {error}")
    
    print(f"\nSummary: {passed_tests}/{total_tests} tests passed")
    
    if passed_tests == total_tests:
        print("🎉 All tests passed!")
        return True
    else:
        print(f"⚠️  {total_tests - passed_tests} tests failed")
        return False

def main():
    """主函数"""
    print("🚀 MixVideo V2 Python Core - Functionality Test")
    print("=" * 50)
    
    # 查找可执行文件
    exe_path = Path("dist/mixvideo-python-core.exe")
    if not exe_path.exists():
        print(f"❌ Executable not found: {exe_path}")
        print("Please build the executable first using:")
        print("  python -m PyInstaller build_enhanced.spec")
        return 1
    
    print(f"📁 Testing executable: {exe_path}")
    
    # 运行测试
    all_results = {}
    
    try:
        # 基础功能测试
        all_results["Basic Functionality"] = test_basic_functionality(exe_path)
        
        # 服务模块测试
        all_results["Service Modules"] = test_service_modules(exe_path)
        
        # AI模块测试
        all_results["AI Modules"] = test_ai_modules(exe_path)
        
        # 生成报告
        success = generate_report(all_results)
        
        # 保存详细结果
        report_file = Path("test_results.json")
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(all_results, f, indent=2, ensure_ascii=False)
        
        print(f"\n📄 Detailed results saved to: {report_file}")
        
        return 0 if success else 1
        
    except KeyboardInterrupt:
        print("\n⚠️ Testing interrupted by user")
        return 130
    except Exception as e:
        print(f"\n❌ Testing failed with error: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
