#!/usr/bin/env python3
"""
安装Python依赖的脚本
包括新添加的PySceneDetect库
"""

import subprocess
import sys
import os
from pathlib import Path

def install_requirements():
    """安装requirements.txt中的依赖"""
    print("🔧 安装Python依赖...")
    
    # 获取项目根目录
    project_root = Path(__file__).parent.parent
    requirements_file = project_root / "python_core" / "requirements.txt"
    
    if not requirements_file.exists():
        print(f"❌ requirements.txt 文件不存在: {requirements_file}")
        return False
    
    try:
        # 安装依赖
        print(f"📦 从 {requirements_file} 安装依赖...")
        subprocess.check_call([
            sys.executable, '-m', 'pip', 'install', '-r', str(requirements_file)
        ])
        
        print("✅ 依赖安装成功！")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False
    except Exception as e:
        print(f"❌ 安装过程中出现错误: {e}")
        return False

def verify_scenedetect():
    """验证PySceneDetect是否正确安装"""
    print("\n🧪 验证PySceneDetect安装...")
    
    try:
        # 尝试导入PySceneDetect
        import scenedetect
        from scenedetect import VideoManager, SceneManager
        from scenedetect.detectors import ContentDetector
        
        print(f"✅ PySceneDetect 导入成功")
        print(f"   版本: {scenedetect.__version__}")
        
        # 测试基本功能
        print("🔍 测试基本功能...")
        
        # 创建一个简单的测试
        video_manager = VideoManager([])
        scene_manager = SceneManager()
        scene_manager.add_detector(ContentDetector())
        
        print("✅ PySceneDetect 功能测试通过")
        return True
        
    except ImportError as e:
        print(f"❌ PySceneDetect 导入失败: {e}")
        return False
    except Exception as e:
        print(f"❌ PySceneDetect 功能测试失败: {e}")
        return False

def verify_other_dependencies():
    """验证其他关键依赖"""
    print("\n🔍 验证其他关键依赖...")
    
    dependencies = [
        ('opencv-python', 'cv2'),
        ('numpy', 'numpy'),
        ('moviepy', 'moviepy'),
        ('ffmpeg-python', 'ffmpeg'),
        ('loguru', 'loguru'),
        ('pydantic', 'pydantic')
    ]
    
    failed_deps = []
    
    for package_name, import_name in dependencies:
        try:
            __import__(import_name)
            print(f"✅ {package_name}")
        except ImportError:
            print(f"❌ {package_name}")
            failed_deps.append(package_name)
    
    if failed_deps:
        print(f"\n⚠️ 以下依赖导入失败: {', '.join(failed_deps)}")
        return False
    else:
        print("\n✅ 所有关键依赖验证通过")
        return True

def show_usage_info():
    """显示使用信息"""
    print("\n📖 PySceneDetect 使用信息:")
    print("1. PySceneDetect 已添加到 requirements.txt")
    print("2. 使用 scenedetect[opencv] 版本，包含OpenCV支持")
    print("3. 在 media_manager.py 中已集成PySceneDetect场景检测")
    print("4. 如果PySceneDetect不可用，会自动回退到OpenCV方法")
    
    print("\n🔧 手动安装命令:")
    print("pip install scenedetect[opencv]")
    
    print("\n📚 相关文档:")
    print("- PySceneDetect: https://pyscenedetect.readthedocs.io/")
    print("- 项目文档: docs/tauri-security-config-guide.md")

def main():
    """主函数"""
    print("🚀 Python依赖安装和验证")
    print("=" * 50)
    
    # 1. 安装依赖
    if not install_requirements():
        print("❌ 依赖安装失败，退出")
        return 1
    
    # 2. 验证PySceneDetect
    scenedetect_ok = verify_scenedetect()
    
    # 3. 验证其他依赖
    other_deps_ok = verify_other_dependencies()
    
    # 4. 显示使用信息
    show_usage_info()
    
    # 5. 总结
    print("\n" + "=" * 50)
    if scenedetect_ok and other_deps_ok:
        print("✅ 所有依赖安装和验证成功！")
        print("\n🎉 现在可以使用改进的场景检测功能了：")
        print("- 重新导入视频将使用PySceneDetect进行更准确的分镜")
        print("- 如果PySceneDetect不可用，系统会自动回退到OpenCV方法")
        return 0
    else:
        print("⚠️ 部分依赖存在问题，请检查上述错误信息")
        return 1

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