#!/opt/homebrew/bin/python3.11
"""
長影片（Charade 1963，114 分鐘）完整測試腳本
"""

import json
import subprocess
import time
from pathlib import Path
from datetime import datetime


def print_header(title):
    """打印標題"""
    print("\n" + "="*70)
    print(f" {title}")
    print("="*70)


def test_data_files():
    """測試數據文件"""
    print_header("1. 數據文件測試")
    
    files = {
        '音頻文件': '/tmp/charade_audio.wav',
        'ASRX 結果': '/tmp/asrx_charade_optimized.json',
        'Face 結果': '/tmp/face_long.json',
        '整合結果': '/tmp/charade_integrated.json'
    }
    
    all_ok = True
    for name, path in files.items():
        exists = Path(path).exists()
        size = Path(path).stat().st_size / 1024 / 1024 if exists else 0
        status = "✅" if exists else "❌"
        print(f"{status} {name}: {size:.1f} MB")
        all_ok = all_ok and exists
    
    return all_ok


def test_asrx_results():
    """測試 ASRX 結果"""
    print_header("2. ASRX 結果測試")
    
    with open('/tmp/asrx_charade_optimized.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    total_duration = data.get('total_duration', 0)
    n_speakers = data.get('n_speakers', 0)
    n_segments = data.get('n_speech_segments', 0)
    
    print(f"📊 影片時長：{total_duration/60:.1f} 分鐘 ({total_duration:.1f}秒)")
    print(f" 說話人數量：{n_speakers}")
    print(f"📊 語音片段：{n_segments}")
    
    # 說話人統計
    print(f"\n📢 說話人分佈:")
    speaker_stats = data.get('speaker_stats', {})
    for speaker, stats in sorted(speaker_stats.items(), key=lambda x: x[1]['duration'], reverse=True):
        duration = stats.get('duration', 0)
        count = stats.get('count', 0)
        pct = duration / total_duration * 100 if total_duration > 0 else 0
        print(f"   {speaker}: {count} 片段，{duration/60:.1f}分鐘 ({pct:.1f}%)")
    
    return n_speakers >= 2 and n_segments > 100


def test_face_results():
    """測試 Face 結果"""
    print_header("3. Face 結果測試")
    
    with open('/tmp/face_long.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    total_frames = data.get('frame_count', 0)
    detected_frames = data.get('frames', [])
    fps = data.get('fps', 0)
    
    print(f"📊 總數：{total_frames:,}")
    print(f"📊 檢測到人臉：{len(detected_frames):,}")
    print(f"📊 FPS: {fps:.2f}")
    print(f"📊 檢測率：{len(detected_frames)/total_frames*100:.2f}%")
    
    return len(detected_frames) > 0


def test_integration():
    """測試整合結果"""
    print_header("4. Face + ASRX 整合測試")
    
    with open('/tmp/charade_integrated.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    segments = data.get('integrated_segments', [])
    total = len(segments)
    with_face = sum(1 for seg in segments if seg.get('has_face', False))
    match_rate = with_face / total * 100 if total > 0 else 0
    
    print(f"📊 總片段：{total}")
    print(f"📊 有人臉：{with_face}")
    print(f"📊 匹配率：{match_rate:.2f}%")
    
    # 說話人匹配統計
    print(f"\n📢 說話人匹配詳情:")
    speaker_stats = data.get('speaker_stats', {})
    for speaker, stats in sorted(speaker_stats.items()):
        total_seg = stats.get('total_segments', 0)
        with_face_seg = stats.get('with_face', 0)
        rate = with_face_seg / total_seg * 100 if total_seg > 0 else 0
        status = "✅" if rate >= 99 else "⚠️" if rate >= 50 else "❌"
        print(f"   {status} {speaker}: {with_face_seg}/{total_seg} ({rate:.1f}%)")
    
    return match_rate >= 95


def test_gui_process():
    """測試 GUI 進程"""
    print_header("5. GUI 進程測試")
    
    result = subprocess.run(['pgrep', '-f', 'speaker_player_gui_face'], 
                          capture_output=True, text=True)
    running = result.returncode == 0
    
    if running:
        pid = result.stdout.strip()
        print(f"✅ GUI 進程運行中 (PID: {pid})")
        
        # 檢查進程資源使用
        ps_result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        for line in ps_result.stdout.split('\n'):
            if 'speaker_player_gui_face' in line and 'grep' not in line:
                parts = line.split()
                if len(parts) >= 8:
                    cpu = parts[2]
                    mem = parts[3]
                    print(f"   CPU: {cpu}%, 記憶體：{mem}%")
    else:
        print("❌ GUI 進程未運行")
    
    return running


def test_playback():
    """測試播放功能（模擬）"""
    print_header("6. 播放功能測試")
    
    # 測試 ffmpeg 是否可用
    result = subprocess.run(['which', 'ffmpeg'], capture_output=True, text=True)
    ffmpeg_ok = result.returncode == 0
    print(f"{'✅' if ffmpeg_ok else '❌'} ffmpeg: {'可用' if ffmpeg_ok else '不可用'}")
    
    # 測試 afplay 是否可用
    result = subprocess.run(['which', 'afplay'], capture_output=True, text=True)
    afplay_ok = result.returncode == 0
    print(f"{'✅' if afplay_ok else '❌'} afplay: {'可用' if afplay_ok else '不可用'}")
    
    # 測試音頻提取（第一個片段）
    with open('/tmp/asrx_charade_optimized.json', 'r', encoding='utf-8') as f:
        asrx_data = json.load(f)
    
    first_seg = asrx_data['segments'][0]
    start = first_seg['start']
    end = first_seg['end']
    duration = end - start
    
    print(f"\n🎵 測試提取第一個片段:")
    print(f"   時間：{start:.2f}s - {end:.2f}s ({duration:.2f}s)")
    
    # 實際提取測試
    temp_file = '/tmp/test_segment.wav'
    cmd = [
        'ffmpeg', '-y', '-loglevel', 'quiet',
        '-i', '/tmp/charade_audio.wav',
        '-ss', str(start),
        '-t', str(duration),
        temp_file
    ]
    
    result = subprocess.run(cmd, capture_output=True)
    extract_ok = result.returncode == 0 and Path(temp_file).exists()
    
    print(f"{'✅' if extract_ok else '❌'} 音頻提取: {'成功' if extract_ok else '失敗'}")
    
    if extract_ok:
        size = Path(temp_file).stat().st_size / 1024
        print(f"   文件大小：{size:.1f} KB")
        Path(temp_file).unlink()  # 清理
    
    return ffmpeg_ok and afplay_ok and extract_ok


def generate_report():
    """生成測試報告"""
    print_header("測試報告")
    
    tests = [
        ("數據文件", test_data_files()),
        ("ASRX 結果", test_asrx_results()),
        ("Face 結果", test_face_results()),
        ("整合結果", test_integration()),
        ("GUI 進程", test_gui_process()),
        ("播放功能", test_playback())
    ]
    
    passed = sum(1 for _, result in tests if result)
    total = len(tests)
    
    print("\n" + "="*70)
    print(f" 測試總結：{passed}/{total} 通過")
    print("="*70)
    
    for name, result in tests:
        status = "✅" if result else "❌"
        print(f"{status} {name}")
    
    if passed == total:
        print("\n🎉 所有測試通過！")
    else:
        print(f"\n⚠️ {total - passed} 個測試失敗")
    
    # 保存報告
    report_path = '/tmp/long_movie_test_report.md'
    with open(report_path, 'w', encoding='utf-8') as f:
        f.write(f"# 長影片測試報告\n\n")
        f.write(f"**測試時間**: {datetime.now().isoformat()}\n")
        f.write(f"**測試影片**: Charade 1963 (114.7 分鐘)\n\n")
        f.write(f"## 結果\n\n")
        f.write(f"**通過**: {passed}/{total}\n\n")
        for name, result in tests:
            status = "✅" if result else "❌"
            f.write(f"- {status} {name}\n")
    
    print(f"\n📄 報告已保存：{report_path}")
    
    return passed == total


if __name__ == "__main__":
    success = generate_report()
    exit(0 if success else 1)
