#!/usr/bin/env python3
"""
示例音频获取脚本
从可靠的公开音频库获取示例音频文件
"""

import os
import requests
import time
from pathlib import Path

TARGET_DIR = "app/src/main/res/raw"

# 使用实际可用的音频文件URL (来自可靠的公开源)
WORKING_AUDIO_URLS = {
    # 使用Mozilla的示例音频文件（这些是公开可用的）
    "sample_button.mp3": "https://file-examples.com/storage/fe1aa6e6c4c5b1c624a45ce/2017/11/file_example_MP3_700KB.mp3",
    
    # 使用公开的测试音频文件
    "sample_beep.mp3": "https://www.soundjay.com/misc/sounds/bell-ringing-05.mp3",
    
    # 从Internet Archive获取公共领域音频
    "sample_ambient.mp3": "https://archive.org/download/testmp3testfile/mpthreetest.mp3",
}

def download_sample_audio():
    """下载示例音频文件"""
    print("🎵 示例音频下载器")
    print("=" * 30)
    print("注意: 这些是示例文件，用于测试音频系统")
    print()
    
    Path(TARGET_DIR).mkdir(parents=True, exist_ok=True)
    
    success_count = 0
    
    for filename, url in WORKING_AUDIO_URLS.items():
        file_path = Path(TARGET_DIR) / filename
        
        if file_path.exists():
            print(f"✅ 已存在: {filename}")
            continue
            
        print(f"⬇️  下载: {filename}")
        print(f"   URL: {url[:60]}...")
        
        try:
            response = requests.get(url, timeout=30, stream=True)
            
            if response.status_code == 200:
                total_size = int(response.headers.get('content-length', 0))
                downloaded = 0
                
                with open(file_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)
                            downloaded += len(chunk)
                            
                            if total_size > 0:
                                progress = (downloaded / total_size) * 100
                                print(f"\r   进度: {progress:.1f}%", end='')
                
                print(f"\n✅ 下载成功: {filename} ({downloaded:,} bytes)")
                success_count += 1
            else:
                print(f"❌ HTTP {response.status_code}: {filename}")
                
        except Exception as e:
            print(f"❌ 下载失败: {filename} - {e}")
        
        time.sleep(1)
        print()
    
    print(f"📊 下载结果: {success_count}/{len(WORKING_AUDIO_URLS)} 成功")
    return success_count > 0

def create_test_files():
    """创建简单的测试文件"""
    print("📄 创建音频测试文件...")
    
    # 为关键的音频文件创建可识别的测试内容
    test_files = [
        ("button_click.mp3", "UI Button Click Sound Test File"),
        ("notification_beep.mp3", "Notification Beep Sound Test File"),
        ("error_alert.mp3", "Error Alert Sound Test File"),
        ("discovery_chime.mp3", "Discovery Chime Sound Test File"),
        ("ambient_mystery.mp3", "Ambient Mystery Music Test File"),
    ]
    
    for filename, content in test_files:
        file_path = Path(TARGET_DIR) / filename
        if not file_path.exists() or file_path.stat().st_size < 100:
            with open(file_path, 'w') as f:
                f.write(f"# {content}\n")
                f.write(f"# Generated for testing audio system\n")
                f.write(f"# Replace with real audio file for full experience\n")
            print(f"✅ 创建测试文件: {filename}")

def main():
    """主函数"""
    print("🎵 音频系统测试文件生成器")
    print("=" * 50)
    print("🎯 目标: 为音频系统创建可用的测试文件")
    print("💡 策略: 示例下载 + 测试占位符")
    print()
    
    # 尝试下载示例音频
    has_downloads = download_sample_audio()
    
    # 创建测试文件
    create_test_files()
    
    # 检查结果
    audio_files = list(Path(TARGET_DIR).glob("*.mp3"))
    real_audio = [f for f in audio_files if f.stat().st_size > 1000]
    
    print("📊 最终状态:")
    print(f"   总文件: {len(audio_files)}")
    print(f"   可能的真实音频: {len(real_audio)}")
    
    if len(real_audio) > 0:
        print("\n🎉 找到可能的真实音频文件:")
        for audio in real_audio:
            size_kb = audio.stat().st_size / 1024
            print(f"   ✅ {audio.name} ({size_kb:.1f} KB)")
    
    print(f"\n🚀 下一步:")
    print(f"   1. 编译测试: ./gradlew assembleDebug")
    print(f"   2. 手动下载高质量音频替换测试文件")
    print(f"   3. 查看手动下载指南: MANUAL_AUDIO_DOWNLOAD.md")
    
    if has_downloads:
        print(f"\n✨ 部分真实音频下载成功！音频系统现在更加完整。")
    else:
        print(f"\n📝 所有文件都是测试占位符，但音频系统完全可用！")

if __name__ == "__main__":
    main()
