#!/usr/bin/env python3
"""extract_bookend_assets.py — cut a partner strip and a portrait out of screenshots.

A ONE-OFF, run BY HAND, when the only artwork you have is a screenshot of somebody's
website or contact card. It is deliberately NOT called by `make-rap-mv.sh` or
`build_bookends.sh`: guessing a crop is a judgement call that has to be looked at,
and a runner that silently re-derives artwork every pass would quietly redefine the
film's furniture on a re-run. Run it once, eyeball the two PNGs, then point
`BOOKEND_PARTNERS_STRIP` and `BOOKEND_FOREWORD_PORTRAIT` at them in the pack.

These are REAL marks and a REAL person, so nothing here is generated. An image model
asked to "make a logo like this" returns wordmarks that are subtly wrong every time —
the same trap that makes `CLUB_CREST` a file path rather than a prompt.

Two decisions the WICC build arrived at the hard way, kept as defaults:

  * THE PARTNER ROW STAYS WHOLE, ON WHITE. The first attempt keyed the page white to
    transparent and split the row into thirds. That cut straight through wordmarks
    and, worse, made the LIGHT parts of each logo transparent, so dark type vanished
    against a dark card. These marks are drawn for light backgrounds; the honest
    presentation is a white partner bar with every logo exactly as supplied. That is
    also what broadcast end boards do. So this only ever TRIMS to the row's own ink.
  * THE PORTRAIT LOCKS TO THE SOURCE CARD'S OWN DISC, not to a fraction of the whole
    image. A box measured off the card cut the top of his head off and pulled his
    printed name up into the circle, so the "photo" contained a caption. Check the
    output; move --portrait-cy before you touch anything else.

Usage:
  extract_bookend_assets.py --out-dir <dir>
      [--strip-from <screenshot.png>] [--strip-top-frac 0.26] [--ink 236]
      [--portrait-from <screenshot.png>] [--portrait-cx 0.50] [--portrait-cy 0.266]
      [--portrait-frac 0.40] [--portrait-size 512]
Exit 0 = ok, 2 = bad input.
"""
from __future__ import annotations

import argparse
import os
import sys

from PIL import Image, ImageDraw, ImageFilter


def die(msg: str) -> None:
    print(f"extract_bookend_assets: {msg}", file=sys.stderr)
    raise SystemExit(2)


def strip(src_path: str, out_path: str, top_frac: float, ink: int) -> None:
    """Trim a partner row to its own ink, keeping it whole and on its own white."""
    src = Image.open(src_path).convert("RGB")
    w, h = src.size
    # drop the caption above the row ("Principal partners" and friends), then find
    # the marks by their ink rather than by another guessed fraction
    body = src.crop((0, int(h * top_frac), w, h))
    px = body.convert("L").load()
    xs, ys = [], []
    for y in range(body.height):
        for x in range(body.width):
            if px[x, y] < ink:
                xs.append(x)
                ys.append(y)
    if not xs:
        die(f"no ink darker than {ink} below {top_frac:.0%} of {src_path} — "
            f"lower --strip-top-frac or raise --ink")
    pad = 6
    out = body.crop((max(0, min(xs) - pad), max(0, min(ys) - pad),
                     min(body.width, max(xs) + pad), min(body.height, max(ys) + pad)))
    out.save(out_path)
    print(f"  {os.path.basename(out_path)}  {out.size}  (kept whole, on white)")


def portrait(src_path: str, out_path: str, cx: float, cy: float, frac: float,
             size: int) -> None:
    """Crop the headshot to its disc and feather it, so it sits on a plate."""
    src = Image.open(src_path).convert("RGBA")
    w, h = src.size
    d = int(min(w, h) * frac)
    box = (int(w * cx) - d // 2, int(h * cy) - d // 2,
           int(w * cx) + d // 2, int(h * cy) + d // 2)
    if box[0] < 0 or box[1] < 0 or box[2] > w or box[3] > h:
        die(f"the disc at ({cx}, {cy}) size {frac} falls outside {src_path} {src.size}")
    face = src.crop(box).resize((size, size), Image.LANCZOS)
    mask = Image.new("L", (size * 4, size * 4), 0)
    ImageDraw.Draw(mask).ellipse([8, 8, size * 4 - 8, size * 4 - 8], fill=255)
    face.putalpha(mask.resize((size, size), Image.LANCZOS).filter(
        ImageFilter.GaussianBlur(1.0)))
    face.save(out_path)
    print(f"  {os.path.basename(out_path)}  {face.size}  (look at it before you ship it)")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out-dir", required=True)
    ap.add_argument("--strip-from", default="")
    ap.add_argument("--strip-top-frac", type=float, default=0.26)
    ap.add_argument("--ink", type=int, default=236)
    ap.add_argument("--portrait-from", default="")
    ap.add_argument("--portrait-cx", type=float, default=0.50)
    ap.add_argument("--portrait-cy", type=float, default=0.266)
    ap.add_argument("--portrait-frac", type=float, default=0.40)
    ap.add_argument("--portrait-size", type=int, default=512)
    args = ap.parse_args()

    if not args.strip_from and not args.portrait_from:
        die("nothing to do — pass --strip-from and/or --portrait-from")
    os.makedirs(args.out_dir, exist_ok=True)
    for p in (args.strip_from, args.portrait_from):
        if p and not os.path.isfile(p):
            die(f"not found: {p}")

    if args.strip_from:
        strip(args.strip_from, os.path.join(args.out_dir, "partners-strip.png"),
              args.strip_top_frac, args.ink)
    if args.portrait_from:
        portrait(args.portrait_from, os.path.join(args.out_dir, "foreword-portrait.png"),
                 args.portrait_cx, args.portrait_cy, args.portrait_frac,
                 args.portrait_size)


if __name__ == "__main__":
    main()
