"""Pull still photography for the content pages out of the source videos.

Most frames of both clips carry burnt-in caption text or glowing VFX overlays,
so the usable stills are hand-picked by frame number rather than sampled. Each
still still needs the watermark patched, and the delogo box is tied to the
source resolution, hence the per-video settings below.

Usage:
    python scripts/extract_stills.py
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import imageio_ffmpeg

ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = ROOT / "public" / "images"

# name -> (video, frame, delogo box in that video's pixels)
STILLS = {
    "sky-blue": ("Solar_energy.mp4", 0, "1698:848:88:100"),
    "sky-warm": ("solar-video.mp4", 0, "1132:560:62:76"),
    "house-dusk": ("solar-video.mp4", 238, "1132:560:62:76"),
    "house-wide": ("solar-video.mp4", 232, "1132:560:62:76"),
}

WIDTH = 1920
QUALITY = 3  # -q:v, 2 is best; 3 is visually identical at half the bytes


def main() -> int:
    ff = imageio_ffmpeg.get_ffmpeg_exe()
    OUT_DIR.mkdir(parents=True, exist_ok=True)

    for name, (video_name, frame, delogo) in STILLS.items():
        video = ROOT / video_name
        if not video.exists():
            print("skip {}: {} not found".format(name, video_name), file=sys.stderr)
            continue

        vf = r"select='eq(n\,{})'".format(frame)
        vf += ",delogo=x={}:y={}:w={}:h={}".format(*delogo.split(":"))
        vf += ",scale={}:-2:flags=lanczos".format(WIDTH)

        dest = OUT_DIR / "{}.jpg".format(name)
        result = subprocess.run(
            [ff, "-hide_banner", "-loglevel", "error", "-y", "-i", str(video),
             "-vf", vf, "-vsync", "0", "-frames:v", "1", "-q:v", str(QUALITY),
             str(dest)],
            capture_output=True, text=True,
        )
        if result.returncode != 0:
            print(result.stderr.strip(), file=sys.stderr)
            return result.returncode
        kb = dest.stat().st_size / 1024
        print("{:12} <- {} frame {:>3}   {:.0f} KB".format(name, video_name, frame, kb))

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
