#!/usr/bin/env python3
"""rap_thumbnail.py — the YouTube thumbnail, from the film's own pixels and cards.

WHY NOT rhyme-factory's make-poster.py: it is rhyme-shaped — Devanagari title pair,
"A NURSERY RHYME" kicker, and a `build/hero-1280.png` input this lane never produces.
What IS reused is the bookend layer's palette and type helpers (`make_bookends.font`,
`hexcolor`, `env`), so the thumb matches the film's own cards instead of introducing a
third look.

A 9:16 film in a 16:9 thumb: the frame fills the canvas blurred-and-darkened, with the
sharp portrait centred over it — the standard treatment — and the title bottom-left in
the card face. The frame defaults to a beat into the film's body (past the intro cards,
where a performance close-up lives); `THUMB_FRAME_SEC` in the pack overrides it.

Usage:
  rap_thumbnail.py --film <film.mp4> --out <final/thumbnail.png>
                   [--frame-sec <s>] [--title <text>] [--kicker <text>]

Exit 0 written · 2 bad input.
"""
from __future__ import annotations

import argparse
import os
import subprocess
import sys
import tempfile

from PIL import Image, ImageDraw, ImageFilter

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from make_bookends import env, font, hexcolor  # noqa: E402  (the film's own type + palette)

FFMPEG = os.environ.get("FFMPEG_FULL", "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg")
W, H = 1280, 720
FONT_DISPLAY = env("FONT_DISPLAY", "/System/Library/Fonts/Supplemental/Didot.ttc")
FONT_UI = env("FONT_UI", "/System/Library/Fonts/Avenir Next Condensed.ttc:2")


def grab(film: str, at: float, dest: str) -> None:
    r = subprocess.run([FFMPEG, "-v", "error", "-y", "-ss", f"{at}", "-i", film,
                        "-frames:v", "1", dest], capture_output=True, text=True)
    if r.returncode != 0 or not os.path.isfile(dest):
        print(f"rap_thumbnail: could not grab a frame at {at}s:\n{r.stderr[-300:]}",
              file=sys.stderr)
        raise SystemExit(2)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--film", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--frame-sec", type=float,
                    default=float(os.environ.get("THUMB_FRAME_SEC", "10.0")))
    ap.add_argument("--title", default=os.environ.get("BOOKEND_TITLE")
                    or os.environ.get("DISPLAY_NAME") or "")
    ap.add_argument("--kicker", default=os.environ.get("KICKER", ""))
    args = ap.parse_args()

    if not os.path.isfile(args.film):
        print(f"rap_thumbnail: no film at {args.film}", file=sys.stderr)
        raise SystemExit(2)

    paper = hexcolor("BOOKEND_PAPER", "#f7f9fc")
    accent = hexcolor("BOOKEND_ACCENT", "#f2a96c")

    with tempfile.TemporaryDirectory() as tmp:
        frame_png = os.path.join(tmp, "frame.png")
        grab(args.film, args.frame_sec, frame_png)
        frame = Image.open(frame_png).convert("RGB")

        # background: the same frame, filled and softened so the letterbox is the
        # film's own colour rather than black bars
        bg = frame.copy()
        scale = max(W / bg.width, H / bg.height)
        bg = bg.resize((round(bg.width * scale), round(bg.height * scale)))
        bg = bg.crop(((bg.width - W) // 2, (bg.height - H) // 2,
                      (bg.width - W) // 2 + W, (bg.height - H) // 2 + H))
        bg = bg.filter(ImageFilter.GaussianBlur(24)).point(lambda v: int(v * 0.55))

        # foreground: the sharp portrait, centred
        fg = frame.copy()
        fscale = H / fg.height
        fg = fg.resize((round(fg.width * fscale), H))
        canvas = bg
        canvas.paste(fg, ((W - fg.width) // 2, 0))

        d = ImageDraw.Draw(canvas, "RGBA")
        # a left-third scrim so the title reads over any frame
        scrim = Image.new("RGBA", (W, H), (0, 0, 0, 0))
        sd = ImageDraw.Draw(scrim)
        for x in range(W // 2):
            alpha = int(170 * (1 - x / (W / 2)))
            sd.line([(x, 0), (x, H)], fill=(0, 0, 0, alpha))
        canvas = Image.alpha_composite(canvas.convert("RGBA"), scrim).convert("RGB")
        d = ImageDraw.Draw(canvas)

        x, y = 56, H - 96
        if args.title:
            size = 92
            f = font(FONT_DISPLAY, size)
            title = args.title.upper()
            while d.textlength(title, font=f) > W * 0.62 and size > 40:
                size -= 4
                f = font(FONT_DISPLAY, size)
            y = H - 72 - size
            # same rule as the title card: a kicker the title already contains reads
            # as a stutter, not a kicker ("HAPPY BIRTHDAY" over "HAPPY BIRTHDAY KRISH")
            if args.kicker and args.kicker.upper() not in title:
                fk = font(FONT_UI, 30)
                d.text((x + 2, y - 44), args.kicker.upper(), font=fk, fill=accent)
            d.text((x, y), title, font=f, fill=paper)
            d.line([(x + 2, y + size + 14), (x + 240, y + size + 14)],
                   fill=accent, width=3)

        os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
        canvas.save(args.out, "PNG")
        print(f"rap_thumbnail: {W}x{H} from {args.frame_sec:g}s of "
              f"{os.path.basename(args.film)} -> {args.out}")


if __name__ == "__main__":
    main()
