#!/usr/bin/env python3
"""
音频文件命名验证脚本
检查所有音频文件是否按照系统要求正确命名
"""

import os
from pathlib import Path

# 从音频系统定义中提取的必需文件名
REQUIRED_AUDIO_FILES = [
    "ambient_mystery.mp3",
    "electronic_tension.mp3", 
    "orchestral_revelation.mp3",
    "epic_finale.mp3",
    "ventilation_soft.mp3",
    "heart_monitor.mp3",
    "reactor_hum.mp3",
    "space_silence.mp3",
    "wind_gentle.mp3",
    "rain_light.mp3",
    "storm_cyber.mp3",
    "solar_storm.mp3",
    "button_click.mp3",
    "notification_beep.mp3",
    "error_alert.mp3",
    "discovery_chime.mp3",
    "time_distortion.mp3",
    "oxygen_leak_alert.mp3"
]

TARGET_DIR = Path("app/src/main/res/raw")

def check_audio_files():
    """检查音频文件命名"""
    print("🎵 音频文件命名验证")
    print("=" * 50)
    
    if not TARGET_DIR.exists():
        print(f"❌ 目录不存在: {TARGET_DIR}")
        return
    
    print(f"📂 检查目录: {TARGET_DIR}")
    print()
    
    # 获取目录中的所有音频文件
    existing_files = [f.name for f in TARGET_DIR.glob("*.mp3")]
    existing_files.extend([f.name for f in TARGET_DIR.glob("*.wav")])
    existing_files.extend([f.name for f in TARGET_DIR.glob("*.ogg")])
    
    print("📋 必需的音频文件检查:")
    print("-" * 30)
    
    missing_files = []
    present_files = []
    
    for required_file in REQUIRED_AUDIO_FILES:
        if required_file in existing_files:
            file_path = TARGET_DIR / required_file
            file_size = file_path.stat().st_size
            
            if file_size > 1000:  # 假设真实音频文件大于1KB
                print(f"✅ {required_file} (真实音频, {file_size:,} bytes)")
                present_files.append((required_file, "真实"))
            else:
                print(f"📄 {required_file} (占位符, {file_size} bytes)")
                present_files.append((required_file, "占位符"))
        else:
            print(f"❌ {required_file} (缺失)")
            missing_files.append(required_file)
    
    print()
    print("📊 统计结果:")
    print("-" * 30)
    print(f"✅ 存在文件: {len(present_files)}/{len(REQUIRED_AUDIO_FILES)}")
    print(f"❌ 缺失文件: {len(missing_files)}")
    
    # 分类统计
    real_audio = [f for f, t in present_files if t == "真实"]
    placeholder = [f for f, t in present_files if t == "占位符"]
    
    print(f"🎵 真实音频: {len(real_audio)} 个")
    print(f"📄 占位符: {len(placeholder)} 个")
    
    # 检查额外的文件
    extra_files = [f for f in existing_files if f not in REQUIRED_AUDIO_FILES and not f.startswith('readme')]
    if extra_files:
        print()
        print("⚠️ 额外的音频文件:")
        for extra_file in extra_files:
            print(f"   - {extra_file}")
        print("   (这些文件不会被音频系统使用)")
    
    # 检查命名规范
    print()
    print("📝 命名规范检查:")
    print("-" * 30)
    
    naming_issues = []
    for file in existing_files:
        # 检查是否包含大写字母
        if any(c.isupper() for c in file):
            naming_issues.append(f"{file} - 包含大写字母")
        
        # 检查是否包含空格
        if ' ' in file:
            naming_issues.append(f"{file} - 包含空格")
        
        # 检查是否包含特殊字符
        allowed_chars = set('abcdefghijklmnopqrstuvwxyz0123456789_.')
        if not set(file.lower()).issubset(allowed_chars):
            naming_issues.append(f"{file} - 包含特殊字符")
    
    if naming_issues:
        print("❌ 发现命名问题:")
        for issue in naming_issues:
            print(f"   - {issue}")
    else:
        print("✅ 所有文件命名符合Android资源规范")
    
    # 总结和建议
    print()
    print("💡 建议:")
    print("-" * 30)
    
    if missing_files:
        print("📥 缺失的文件需要下载:")
        for missing in missing_files:
            print(f"   - {missing}")
        print("   运行: python3 quick_audio_setup.py")
    
    if len(real_audio) < 5:
        print("🎵 建议下载更多真实音频文件以获得完整体验")
        print("   查看: AUDIO_DOWNLOAD_GUIDE.md")
    
    if len(present_files) == len(REQUIRED_AUDIO_FILES):
        print("🎉 所有音频文件已准备就绪!")
        print("✨ 可以编译并测试音频系统: ./gradlew assembleDebug")
    
    return len(missing_files) == 0 and len(naming_issues) == 0

def fix_naming_issues():
    """修复常见的命名问题"""
    print("\n🔧 修复命名问题...")
    
    # 检查常见的错误命名模式
    common_fixes = {
        "ambient_mystery.MP3": "ambient_mystery.mp3",
        "ambient_mystery.wav": "ambient_mystery.mp3",
        "Ambient_Mystery.mp3": "ambient_mystery.mp3",
        "ambient-mystery.mp3": "ambient_mystery.mp3",
        "ambient mystery.mp3": "ambient_mystery.mp3",
    }
    
    fixed_count = 0
    for old_name, new_name in common_fixes.items():
        old_path = TARGET_DIR / old_name
        new_path = TARGET_DIR / new_name
        
        if old_path.exists() and not new_path.exists():
            try:
                old_path.rename(new_path)
                print(f"✅ 重命名: {old_name} -> {new_name}")
                fixed_count += 1
            except Exception as e:
                print(f"❌ 重命名失败: {old_name} - {e}")
    
    if fixed_count > 0:
        print(f"🎉 修复了 {fixed_count} 个命名问题")
    else:
        print("ℹ️ 没有发现需要修复的命名问题")

if __name__ == "__main__":
    try:
        success = check_audio_files()
        
        if not success:
            print("\n❓ 是否尝试自动修复命名问题? (y/n)")
            # 在脚本环境中，我们直接尝试修复
            fix_naming_issues()
            print("\n🔄 重新检查...")
            check_audio_files()
            
    except Exception as e:
        print(f"💥 检查过程中出错: {e}")
