#!/opt/homebrew/bin/python3.11
"""
GUI Face Player 自動化測試腳本
測試所有功能並生成測試報告
"""

import json
import subprocess
import time
import os
from pathlib import Path


def check_file_exists(path, description):
    """檢查文件是否存在"""
    exists = Path(path).exists()
    status = "✅" if exists else "❌"
    size = Path(path).stat().st_size / 1024 / 1024 if exists else 0
    print(f"{status} {description}: {path} ({size:.1f} MB)")
    return exists


def check_process_running(pattern):
    """檢查進程是否運行"""
    result = subprocess.run(['pgrep', '-f', pattern], capture_output=True, text=True)
    running = result.returncode == 0
    status = "✅" if running else "❌"
    print(f"{status} 進程：{pattern} ({'運行中' if running else '未運行'})")
    return running


def test_json_structure(path, required_keys, description):
    """測試 JSON 文件結構"""
    try:
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        missing_keys = [key for key in required_keys if key not in data]
        if missing_keys:
            print(f"❌ {description}: 缺少鍵 {missing_keys}")
            return False
        else:
            print(f"✅ {description}: 結構正確")
            return True
    except Exception as e:
        print(f"❌ {description}: {e}")
        return False


def test_integration_script():
    """測試整合腳本"""
    print("\n" + "="*70)
    print("測試整合腳本")
    print("="*70)
    
    cmd = [
        'python3',
        'integrate_face_asrx_speaker.py',
        '/tmp/face_long.json',
        '/tmp/asrx_charade_optimized.json',
        '--threshold', '3.0',
        '--stats'
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    
    # 檢查輸出
    if '99.8%' in result.stdout:
        print("✅ 整合腳本：匹配率正確 (99.8%)")
        return True
    else:
        print("❌ 整合腳本：匹配率異常")
        print(result.stdout)
        return False


def test_gui_startup():
    """測試 GUI 啟動"""
    print("\n" + "="*70)
    print("測試 GUI 啟動")
    print("="*70)
    
    # 檢查進程
    running = check_process_running('speaker_player_gui_face')
    
    if running:
        print("✅ GUI 進程：正常運行")
        return True
    else:
        print("❌ GUI 進程：未運行")
        return False


def main():
    """主測試函數"""
    print("="*70)
    print("GUI Face Player 自動化測試")
    print("="*70)
    
    # 測試文件
    print("\n" + "="*70)
    print("測試文件")
    print("="*70)
    
    files_ok = True
    files_ok &= check_file_exists('/tmp/charade_audio.wav', '音頻文件')
    files_ok &= check_file_exists('/tmp/asrx_charade_optimized.json', 'ASRX 結果')
    files_ok &= check_file_exists('/tmp/face_long.json', 'Face 結果')
    files_ok &= check_file_exists('/tmp/charade_integrated.json', '整合結果')
    
    # 測試 JSON 結構
    print("\n" + "="*70)
    print("測試 JSON 結構")
    print("="*70)
    
    json_ok = True
    json_ok &= test_json_structure(
        '/tmp/asrx_charade_optimized.json',
        ['segments', 'n_speakers'],
        'ASRX 結果'
    )
    json_ok &= test_json_structure(
        '/tmp/face_long.json',
        ['frames', 'frame_count'],
        'Face 結果'
    )
    json_ok &= test_json_structure(
        '/tmp/charade_integrated.json',
        ['integrated_segments', 'speaker_stats'],
        '整合結果'
    )
    
    # 測試整合腳本
    integration_ok = test_integration_script()
    
    # 測試 GUI
    gui_ok = test_gui_startup()
    
    # 總結
    print("\n" + "="*70)
    print("測試總結")
    print("="*70)
    
    all_ok = files_ok and json_ok and integration_ok and gui_ok
    
    if all_ok:
        print("✅ 所有測試通過！")
    else:
        print("❌ 部分測試失敗")
        if not files_ok:
            print("  - 文件測試失敗")
        if not json_ok:
            print("  - JSON 結構測試失敗")
        if not integration_ok:
            print("  - 整合腳本測試失敗")
        if not gui_ok:
            print("  - GUI 啟動測試失敗")
    
    print("\n" + "="*70)
    
    return all_ok


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