#!/usr/bin/env python3
"""
處理器效能評估測試
測試所有處理器模組的處理時間
"""

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

VIDEO_SHORT = "/Users/accusys/momentry/var/sftpgo/data/demo/ExaSAN PCIe series - Director Ou Yu-Zhi Shares His Experience.mp4"
VIDEO_LONG = "/Users/accusys/momentry/var/sftpgo/data/demo/Old_Time_Movie_Show_-_Charade_1963.HD.mov"

OUTPUT_DIR = Path("/tmp/processor_performance_test")
OUTPUT_DIR.mkdir(exist_ok=True)

PROCESSORS = {
    "asr": {
        "script": "asr_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "asr_short.json")],
        "timeout": 600,
    },
    "ocr": {
        "script": "ocr_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "ocr_short.json")],
        "timeout": 300,
    },
    "yolo": {
        "script": "yolo_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "yolo_short.json")],
        "timeout": 600,
    },
    "face": {
        "script": "face_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "face_short.json")],
        "timeout": 600,
    },
    "pose": {
        "script": "pose_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "pose_short.json")],
        "timeout": 600,
    },
    "cut": {
        "script": "cut_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "cut_short.json")],
        "timeout": 300,
    },
    "asrx": {
        "script": "asrx_processor.py",
        "args": [VIDEO_SHORT, str(OUTPUT_DIR / "asrx_short.json")],
        "timeout": 600,
    },
    "scene": {
        "script": "scene_classifier.py",
        "args": [
            VIDEO_SHORT,
            str(OUTPUT_DIR / "scene_short.json"),
            "--sample-interval",
            "2",
        ],
        "timeout": 120,
    },
}


def test_processor(name: str, config: dict) -> dict:
    """測試單個處理器"""
    script_path = Path(__file__).parent / config["script"]

    if not script_path.exists():
        print(f"[{name}] ✗ Script not found: {script_path}")
        return {
            "processor": name,
            "status": "error",
            "error": "Script not found",
            "duration": 0,
        }

    cmd = ["python3", str(script_path)] + config["args"]

    print(f"\n[{name}] Testing...")
    print(f"[{name}] Command: {' '.join(cmd)}")

    start_time = time.time()

    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=config["timeout"],
        )

        elapsed = time.time() - start_time

        if result.returncode == 0:
            print(f"[{name}] ✓ Completed in {elapsed:.2f}s")

            # Read output file for stats
            output_file = config["args"][1]
            stats = {}
            if Path(output_file).exists():
                with open(output_file) as f:
                    output_data = json.load(f)
                    stats = {
                        "frame_count": output_data.get("frame_count", 0),
                        "fps": output_data.get("fps", 0),
                        "duration": output_data.get("metadata", {}).get("duration", 0),
                    }

            return {
                "processor": name,
                "status": "success",
                "duration": elapsed,
                "returncode": result.returncode,
                "stats": stats,
            }
        else:
            print(f"[{name}] ✗ Failed with code {result.returncode}")
            print(f"[{name}] Error: {result.stderr[:200]}")
            return {
                "processor": name,
                "status": "error",
                "duration": elapsed,
                "returncode": result.returncode,
                "error": result.stderr[:500],
            }

    except subprocess.TimeoutExpired:
        elapsed = time.time() - start_time
        print(f"[{name}] ✗ Timeout after {elapsed:.2f}s")
        return {
            "processor": name,
            "status": "timeout",
            "duration": elapsed,
            "timeout": config["timeout"],
        }

    except Exception as e:
        elapsed = time.time() - start_time
        print(f"[{name}] ✗ Exception: {e}")
        return {
            "processor": name,
            "status": "error",
            "duration": elapsed,
            "error": str(e),
        }


def main():
    """主函數"""
    print("=" * 60)
    print("處理器效能評估測試")
    print("=" * 60)
    print(f"測試日期: {datetime.now().isoformat()}")
    print(f"短影片: {VIDEO_SHORT}")
    print(f"長影片: {VIDEO_LONG}")
    print(f"輸出目錄: {OUTPUT_DIR}")
    print("=" * 60)

    results = []

    # Test each processor
    for name, config in PROCESSORS.items():
        result = test_processor(name, config)
        results.append(result)

    # Summary
    print("\n" + "=" * 60)
    print("測試結果摘要")
    print("=" * 60)

    video_duration_short = 159.6  # ExaSAN

    print("\n影片: ExaSAN (159.6秒)")
    print("\n| 處理器 | 狀態 | 處理時間 | 加速比 |")
    print("|--------|------|----------|--------|")

    for r in results:
        status_icon = "✓" if r["status"] == "success" else "✗"
        duration = r["duration"]
        speedup = video_duration_short / duration if duration > 0 else 0

        print(
            f"| {r['processor']} | {status_icon} | {duration:.2f}s | {speedup:.1f}x |"
        )

    # Save results
    output_file = OUTPUT_DIR / "performance_report.json"
    with open(output_file, "w") as f:
        json.dump(
            {
                "test_date": datetime.now().isoformat(),
                "video_short": VIDEO_SHORT,
                "video_long": VIDEO_LONG,
                "video_duration_short": video_duration_short,
                "results": results,
            },
            f,
            indent=2,
        )

    print(f"\n報告已保存: {output_file}")
    print("=" * 60)


if __name__ == "__main__":
    main()
