"""Build the services showcase sequence from Solar_panel.mp4.

The clip is a clean studio render — no caption text, just a sparkle + "Veo"
wordmark in the bottom-right corner. That mark sits only a few pixels from the
frame edge, which is too tight for ffmpeg's delogo (it samples the box border),
so it is inpainted instead. The backdrop there is a smooth grey gradient, which
inpainting reconstructs exactly.

Usage:
    python scripts/build_services_frames.py
"""

from __future__ import annotations

import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

import cv2
import imageio_ffmpeg
import numpy as np

ROOT = Path(__file__).resolve().parent.parent
VIDEO = ROOT / "Solar_panel.mp4"
OUT_DIR = ROOT / "public" / "frames-services"

WIDTH, HEIGHT = 1920, 1080
QUALITY = 85

# Sparkle + "Veo", measured at source 1280x720 and scaled by 1.5, with padding.
# A plain rectangle is fine because the backdrop behind it is featureless.
MARK = (1802, 952, 1912, 1070)   # x0, y0, x1, y1 at 1920x1080
INPAINT_RADIUS = 10


def main() -> int:
    if not VIDEO.exists():
        print("Video not found: {}".format(VIDEO), file=sys.stderr)
        return 1

    ff = imageio_ffmpeg.get_ffmpeg_exe()
    total, secs = imageio_ffmpeg.count_frames_and_secs(str(VIDEO))
    print("Source  : {}  ({} frames, {:.2f}s)".format(VIDEO.name, total, secs))

    tmp = Path(tempfile.mkdtemp())
    subprocess.run(
        [ff, "-hide_banner", "-loglevel", "error", "-y", "-i", str(VIDEO),
         "-vf", "scale={}:{}:flags=lanczos".format(WIDTH, HEIGHT),
         "-q:v", "2", "-start_number", "1", str(tmp / "raw_%04d.jpg")],
        check=True,
    )
    raw = sorted(tmp.glob("raw_*.jpg"))
    print("Extracted: {} frames at {}x{}".format(len(raw), WIDTH, HEIGHT))

    mask = np.zeros((HEIGHT, WIDTH), np.uint8)
    x0, y0, x1, y1 = MARK
    mask[y0:y1, x0:x1] = 255
    print("Inpaint : {} ({:.3f}% of frame)".format(MARK, 100.0 * (mask > 0).sum() / mask.size))

    if OUT_DIR.exists():
        shutil.rmtree(OUT_DIR)
    OUT_DIR.mkdir(parents=True)

    for i, src in enumerate(raw, start=1):
        img = cv2.imread(str(src))
        out = cv2.inpaint(img, mask, INPAINT_RADIUS, cv2.INPAINT_TELEA)
        cv2.imwrite(str(OUT_DIR / "frame_{:04d}.jpg".format(i)), out,
                    [cv2.IMWRITE_JPEG_QUALITY, QUALITY])

    shutil.rmtree(tmp, ignore_errors=True)

    written = sorted(OUT_DIR.glob("frame_*.jpg"))
    mb = sum(f.stat().st_size for f in written) / (1024 * 1024)
    print("Wrote   : {} frames, {:.1f} MB".format(len(written), mb))

    missing = [i + 1 for i in range(len(written))
               if not (OUT_DIR / "frame_{:04d}.jpg".format(i + 1)).exists()]
    if missing:
        print("Gaps at: {}".format(missing[:5]), file=sys.stderr)
        return 1

    print("FRAME_COUNT = {}".format(len(written)))
    return 0


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