#!/usr/bin/env python3
import json
import subprocess
import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]


def duration(path):
    result = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(path)],
        check=True,
        capture_output=True,
        text=True,
    )
    return float(result.stdout.strip())


def frame(source, output, timestamp):
    output.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run(
        ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{timestamp:.3f}", "-i", str(source), "-frames:v", "1", str(output)],
        check=True,
    )


def main():
    if len(sys.argv) != 2 or sys.argv[1] not in {"intro", "footage", "final", "upload"}:
        raise SystemExit("usage: extract-qa-frames.py intro|footage|final|upload")
    kind = sys.argv[1]
    mapping = {
        "intro": PROJECT / "output/intro/intro.mp4",
        "footage": PROJECT / "output/footage/footage.mp4",
        "final": PROJECT / "output/final.mp4",
        "upload": PROJECT / "output/final-upload.mp4",
    }
    source = mapping[kind]
    if not source.exists():
        raise SystemExit(f"missing {source}")
    total = duration(source)
    if kind == "intro":
        stamps = [("start", min(0.5, total / 4)), ("middle", total / 2), ("end", max(0, total - 0.5))]
    elif kind in {"final", "upload"}:
        stamps = [("intro", min(1.0, total / 10)), ("transition", min(20.0, total / 5)), ("middle", total / 2), ("end", max(0, total - 1.0))]
    else:
        stamps = [("start", 1.0), ("middle", total / 2), ("end", max(0, total - 1.0))]
    outputs = []
    for label, stamp in stamps:
        output = PROJECT / "log" / f"{kind}-check" / f"frame-{label}.png"
        frame(source, output, stamp)
        outputs.append({"label": label, "timestamp": stamp, "path": str(output.relative_to(PROJECT)), "bytes": output.stat().st_size})
    print(json.dumps({"kind": kind, "source": str(source.relative_to(PROJECT)), "duration": total, "frames": outputs}, ensure_ascii=False))


if __name__ == "__main__":
    main()
