#!/usr/bin/env python3
"""
调试素材加载问题的脚本
检查数据文件、加载过程和过滤逻辑
"""

import sys
import os
import json
from pathlib import Path

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

from python_core.services.media_manager import MediaManager
from python_core.config import settings

def check_data_files():
    """检查数据文件的存在和内容"""
    print("📁 检查数据文件...")
    
    cache_dir = settings.temp_dir / "cache"
    segments_file = cache_dir / "video_segments.json"
    original_videos_file = cache_dir / "original_videos.json"
    
    print(f"缓存目录: {cache_dir}")
    print(f"片段文件: {segments_file}")
    print(f"原始视频文件: {original_videos_file}")
    
    # 检查目录
    if cache_dir.exists():
        print(f"✅ 缓存目录存在")
        files = list(cache_dir.glob("*"))
        print(f"目录内容: {[f.name for f in files]}")
    else:
        print(f"❌ 缓存目录不存在")
        return False
    
    # 检查片段文件
    if segments_file.exists():
        try:
            with open(segments_file, 'r', encoding='utf-8') as f:
                segments_data = json.load(f)
            
            print(f"✅ 片段文件存在，包含 {len(segments_data)} 个片段")
            
            if segments_data:
                print("\n📋 片段数据示例:")
                for i, segment in enumerate(segments_data[:3]):
                    print(f"  {i+1}. {segment.get('filename', 'N/A')}")
                    print(f"     ID: {segment.get('id', 'N/A')}")
                    print(f"     标签: {segment.get('tags', [])}")
                    print(f"     激活状态: {segment.get('is_active', 'N/A')}")
                    print(f"     使用次数: {segment.get('use_count', 'N/A')}")
                    print()
            
            return True
            
        except Exception as e:
            print(f"❌ 读取片段文件失败: {e}")
            return False
    else:
        print(f"❌ 片段文件不存在")
        return False

def test_media_manager_loading():
    """测试MediaManager的加载过程"""
    print("\n🔧 测试MediaManager加载...")
    
    try:
        # 创建MediaManager实例
        media_manager = MediaManager()
        
        print(f"✅ MediaManager创建成功")
        print(f"加载的片段数量: {len(media_manager.video_segments)}")
        print(f"加载的原始视频数量: {len(media_manager.original_videos)}")
        
        # 检查内存中的数据
        if media_manager.video_segments:
            print("\n📊 内存中的片段数据:")
            for i, segment in enumerate(media_manager.video_segments[:3]):
                print(f"  {i+1}. {segment.filename}")
                print(f"     ID: {segment.id}")
                print(f"     标签: {segment.tags}")
                print(f"     激活状态: {segment.is_active}")
                print(f"     使用次数: {segment.use_count}")
                print()
        
        return media_manager
        
    except Exception as e:
        print(f"❌ MediaManager创建失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def test_get_all_segments(media_manager):
    """测试get_all_segments方法"""
    print("\n🔍 测试get_all_segments方法...")
    
    try:
        segments = media_manager.get_all_segments()
        print(f"✅ get_all_segments返回 {len(segments)} 个片段")
        
        if segments:
            print("\n📋 返回的片段数据:")
            for i, segment in enumerate(segments[:3]):
                print(f"  {i+1}. {segment.get('filename', 'N/A')}")
                print(f"     ID: {segment.get('id', 'N/A')}")
                print(f"     标签: {segment.get('tags', [])}")
                print(f"     激活状态: {segment.get('is_active', 'N/A')}")
                print()
        else:
            print("❌ 没有返回任何片段")
            
            # 分析原因
            print("\n🔍 分析原因:")
            total_segments = len(media_manager.video_segments)
            active_segments = [s for s in media_manager.video_segments if s.is_active]
            inactive_segments = [s for s in media_manager.video_segments if not s.is_active]
            
            print(f"总片段数: {total_segments}")
            print(f"激活的片段: {len(active_segments)}")
            print(f"未激活的片段: {len(inactive_segments)}")
            
            if inactive_segments:
                print("\n❌ 发现未激活的片段:")
                for i, segment in enumerate(inactive_segments[:3]):
                    print(f"  {i+1}. {segment.filename} (is_active: {segment.is_active})")
        
        return segments
        
    except Exception as e:
        print(f"❌ get_all_segments调用失败: {e}")
        import traceback
        traceback.print_exc()
        return []

def test_command_line_interface():
    """测试命令行接口"""
    print("\n🖥️ 测试命令行接口...")
    
    try:
        import subprocess
        import sys
        
        # 调用Python命令
        result = subprocess.run([
            sys.executable, '-m', 'python_core.services.media_manager', 'get_all_segments'
        ], capture_output=True, text=True, cwd=project_root)
        
        print(f"返回码: {result.returncode}")
        print(f"标准输出: {result.stdout}")
        print(f"标准错误: {result.stderr}")
        
        if result.returncode == 0 and result.stdout:
            try:
                response = json.loads(result.stdout)
                print(f"✅ 命令行接口返回: {response}")
                
                if response.get('status') and response.get('data'):
                    segments = response['data']
                    print(f"通过命令行获取到 {len(segments)} 个片段")
                else:
                    print(f"❌ 命令行返回状态: {response.get('status')}, 消息: {response.get('message')}")
                    
            except json.JSONDecodeError as e:
                print(f"❌ 解析JSON响应失败: {e}")
        else:
            print(f"❌ 命令行调用失败")
            
    except Exception as e:
        print(f"❌ 测试命令行接口失败: {e}")

def check_file_permissions():
    """检查文件权限"""
    print("\n🔐 检查文件权限...")
    
    cache_dir = settings.temp_dir / "cache"
    segments_file = cache_dir / "video_segments.json"
    
    if segments_file.exists():
        stat = segments_file.stat()
        print(f"文件权限: {oct(stat.st_mode)}")
        print(f"文件大小: {stat.st_size} 字节")
        print(f"可读: {os.access(segments_file, os.R_OK)}")
        print(f"可写: {os.access(segments_file, os.W_OK)}")
    else:
        print("文件不存在，无法检查权限")

def suggest_fixes():
    """建议修复方案"""
    print("\n🔧 修复建议:")
    print("1. 如果数据文件不存在:")
    print("   - 尝试导入一些测试视频")
    print("   - 检查导入过程是否有错误")
    
    print("\n2. 如果数据文件存在但为空:")
    print("   - 检查导入过程的保存逻辑")
    print("   - 查看Python日志文件")
    
    print("\n3. 如果片段存在但is_active为false:")
    print("   - 检查片段删除逻辑")
    print("   - 手动修改JSON文件中的is_active字段")
    
    print("\n4. 如果命令行接口失败:")
    print("   - 检查Python环境和依赖")
    print("   - 查看错误日志")
    
    print("\n5. 通用调试步骤:")
    print("   - 启用详细日志记录")
    print("   - 使用浏览器开发者工具查看网络请求")
    print("   - 检查Tauri后端日志")

def main():
    """主函数"""
    print("🔍 素材加载问题调试")
    print("=" * 50)
    
    # 1. 检查数据文件
    files_ok = check_data_files()
    
    if not files_ok:
        print("\n❌ 数据文件检查失败，无法继续")
        suggest_fixes()
        return
    
    # 2. 测试MediaManager加载
    media_manager = test_media_manager_loading()
    
    if not media_manager:
        print("\n❌ MediaManager加载失败，无法继续")
        suggest_fixes()
        return
    
    # 3. 测试get_all_segments方法
    segments = test_get_all_segments(media_manager)
    
    # 4. 测试命令行接口
    test_command_line_interface()
    
    # 5. 检查文件权限
    check_file_permissions()
    
    # 6. 提供修复建议
    suggest_fixes()
    
    print("\n✅ 调试完成！")

if __name__ == "__main__":
    main()
