#!/usr/bin/env python3
"""Benchmark OpenCV frame sampling at max_frames=16 vs 24 (FakeEngine / no DeepFace).

Usage (from repo root, venv active):
  python scripts/bench_video_frames.py

This is NOT part of the default pytest suite.
"""

from __future__ import annotations

import statistics
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

import cv2
import numpy as np

from app.services.face.video_frames import extract_frames_from_bytes


def _make_video(*, frames: int = 120, size: int = 160, fps: float = 10.0) -> bytes:
    path = Path("/tmp/tj_bench_video.avi")
    fourcc = cv2.VideoWriter_fourcc(*"MJPG")
    writer = cv2.VideoWriter(str(path), fourcc, fps, (size, size))
    assert writer.isOpened()
    for i in range(frames):
        writer.write(np.full((size, size, 3), (i % 200, 80, 140), dtype=np.uint8))
    writer.release()
    data = path.read_bytes()
    path.unlink(missing_ok=True)
    return data


def _run_once(data: bytes, *, max_frames: int, sample_fps: float) -> dict:
    t0 = time.perf_counter()
    extracted = extract_frames_from_bytes(
        data, sample_fps=sample_fps, max_frames=max_frames
    )
    elapsed = time.perf_counter() - t0
    n = len(extracted.frames_bgr)
    extracted.cleanup()
    return {"elapsed_s": elapsed, "frames": n}


def main() -> None:
    data = _make_video()
    results = {}
    for max_frames in (16, 24):
        samples = [_run_once(data, max_frames=max_frames, sample_fps=2.0) for _ in range(5)]
        times = [s["elapsed_s"] for s in samples]
        results[max_frames] = {
            "frames": samples[0]["frames"],
            "mean_s": statistics.mean(times),
            "stdev_s": statistics.pstdev(times),
            "min_s": min(times),
            "max_s": max(times),
        }

    print("=== Video frame extraction benchmark (OpenCV only; no DeepFace) ===")
    for mf, row in results.items():
        print(
            f"max_frames={mf}: sampled={row['frames']} "
            f"mean={row['mean_s']*1000:.1f}ms "
            f"stdev={row['stdev_s']*1000:.1f}ms "
            f"range=[{row['min_s']*1000:.1f},{row['max_s']*1000:.1f}]ms"
        )
    t16 = results[16]["mean_s"]
    t24 = results[24]["mean_s"]
    if t24 > 0:
        print(f"relative_mean_16_vs_24={t16 / t24:.3f} (1.0 = same speed)")
    print("Note: CV inference (DeepFace) cost scales roughly with sampled frame count.")


if __name__ == "__main__":
    main()
