#!/usr/bin/env python3
"""
简化的视频拆分服务测试
"""

import os
import sys
import tempfile
import shutil
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def test_basic_functionality():
    """测试基本功能"""
    print("🎬 测试PySceneDetect视频拆分服务基本功能")
    print("=" * 60)
    
    # 查找测试视频
    assets_dir = project_root / "assets"
    video_files = list(assets_dir.rglob("*.mp4"))
    
    if not video_files:
        print("❌ 没有找到测试视频文件")
        return False
    
    test_video = str(video_files[0])
    print(f"📹 测试视频: {test_video}")
    print(f"   文件大小: {os.path.getsize(test_video) / (1024*1024):.1f} MB")
    
    try:
        # 检查PySceneDetect
        try:
            import scenedetect
            print(f"✅ PySceneDetect {scenedetect.__version__} 可用")
        except ImportError:
            print("❌ PySceneDetect不可用")
            return False
        
        from python_core.services.video_splitter import VideoSplitterService
        
        # 创建临时输出目录
        temp_dir = tempfile.mkdtemp(prefix="video_splitter_test_")
        print(f"📁 临时输出目录: {temp_dir}")
        
        # 创建服务
        splitter = VideoSplitterService(output_base_dir=temp_dir)
        print("✅ 视频拆分服务创建成功")
        
        # 测试场景检测
        print(f"\n🎯 测试场景检测...")
        scenes = splitter.detect_scenes(test_video, threshold=30.0)
        
        print(f"✅ 场景检测成功:")
        print(f"   检测到 {len(scenes)} 个场景")
        for scene in scenes[:3]:  # 只显示前3个
            print(f"   场景 {scene.scene_number}: {scene.start_time:.2f}s - {scene.end_time:.2f}s ({scene.duration:.2f}s)")
        if len(scenes) > 3:
            print(f"   ... 还有 {len(scenes) - 3} 个场景")
        
        # 测试视频分析
        print(f"\n🔍 测试视频分析...")
        analysis = splitter.analyze_video(test_video, threshold=30.0)
        
        if analysis["success"]:
            print(f"✅ 视频分析成功:")
            print(f"   总场景数: {analysis['total_scenes']}")
            print(f"   总时长: {analysis['total_duration']:.2f}秒")
            print(f"   平均场景时长: {analysis['average_scene_duration']:.2f}秒")
        else:
            print(f"❌ 视频分析失败: {analysis.get('error', 'Unknown error')}")
            return False
        
        print(f"\n✅ 基本功能测试通过！")
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        # 清理临时目录
        if 'temp_dir' in locals():
            print(f"\n🧹 清理临时目录: {temp_dir}")
            shutil.rmtree(temp_dir, ignore_errors=True)

def test_command_line():
    """测试命令行功能"""
    print("\n" + "=" * 60)
    print("🖥️ 测试命令行功能")
    print("=" * 60)
    
    # 查找测试视频
    assets_dir = project_root / "assets"
    video_files = list(assets_dir.rglob("*.mp4"))
    
    if not video_files:
        print("❌ 没有找到测试视频文件")
        return False
    
    test_video = str(video_files[0])
    print(f"📹 测试视频: {test_video}")
    
    try:
        import subprocess
        
        # 测试分析命令
        print(f"\n🔍 测试分析命令...")
        
        # 设置PYTHONPATH
        env = os.environ.copy()
        env['PYTHONPATH'] = str(project_root)
        
        cmd = [
            sys.executable, 
            str(project_root / "python_core" / "services" / "video_splitter.py"),
            "analyze",
            test_video,
            "--threshold", "30.0"
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60, env=env)
        
        if result.returncode == 0:
            print(f"✅ 分析命令执行成功")
            
            # 解析JSON输出
            import json
            try:
                analysis_data = json.loads(result.stdout)
                if analysis_data.get("success"):
                    print(f"   总场景数: {analysis_data.get('total_scenes', 0)}")
                    print(f"   总时长: {analysis_data.get('total_duration', 0):.2f}秒")
                else:
                    print(f"   分析失败: {analysis_data.get('error', 'Unknown error')}")
                    return False
            except json.JSONDecodeError:
                print(f"   输出: {result.stdout[:200]}...")
        else:
            print(f"❌ 分析命令执行失败")
            print(f"   错误: {result.stderr}")
            return False
        
        print(f"✅ 命令行功能测试通过！")
        return True
        
    except Exception as e:
        print(f"❌ 命令行测试失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 PySceneDetect视频拆分服务简化测试")
    
    try:
        # 测试基本功能
        success1 = test_basic_functionality()
        
        # 测试命令行功能
        success2 = test_command_line()
        
        print("\n" + "=" * 60)
        print("📊 测试总结")
        print("=" * 60)
        
        if success1 and success2:
            print("🎉 所有测试通过！")
            print("\n✅ 功能验证:")
            print("   1. PySceneDetect可用 - ✅")
            print("   2. 场景检测功能 - ✅")
            print("   3. 视频分析功能 - ✅")
            print("   4. 命令行接口 - ✅")
            
            print("\n🚀 使用方法:")
            print("   # 分析视频")
            print("   python python_core/services/video_splitter.py analyze video.mp4")
            print("   # 拆分视频")
            print("   python python_core/services/video_splitter.py split video.mp4")
            
            return 0
        else:
            print("⚠️ 部分测试失败")
            return 1
            
    except Exception as e:
        print(f"❌ 测试过程中出错: {e}")
        import traceback
        traceback.print_exc()
        return 1

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