#!/usr/bin/env python3
"""make_bookends.py — compose a film's bookend cards from its pack.

A film that opens on the body master opens on whatever the first shot happens to be.
These cards are the film's manners: an ident, a title, an optional foreword from a
named person, an end card, and an optional partner board. `build_bookends.sh`
animates them and wraps the body in them; nothing here touches video.

Three rules this file exists to honour
--------------------------------------
1. **A MARK IS NEVER GENERATED.** An image model asked to reproduce a crest or a
   wordmark returns something subtly wrong every time. So the badge is the REAL
   file at `CLUB_CREST`, composited; if the pack has no crest the badge is simply
   OMITTED and the card reflows around the gap. It is never substituted with a
   drawn mark, a monogram or an initial in a circle.
2. **PARTNER MARKS ARE COMPOSITED WHOLE.** The supplied strip goes onto a white
   rounded bar exactly as delivered — never keyed, never recoloured, never split
   into individual logos. Keying the page white out of a partner row eats the light
   parts of each mark, and splitting a row cuts through wordmarks. A white bar is
   also what broadcast end boards actually do.
3. **BODY COPY IS NEVER SET IN THE DISPLAY FACE.** `FONT_DISPLAY` is expected to be
   a didone or another high-contrast face; its horizontal strokes are hairlines, so
   at body size reversed out of a dark plate the em-dashes vanish entirely and the
   paragraph reads as thin and broken. `FONT_BODY` must resolve to a different file
   — asserted at startup, on the resolved path, so `Didot.ttc:0` vs `Didot.ttc:1`
   cannot slip through a string compare.

Everything else is data. The cards are built from exported pack vars read out of the
environment, so a pack ships bookends by setting variables and supplying artwork —
never by copying this file.

Cards
-----
ALWAYS: `ident`, `title`, `outro`.
`foreword-N` only when `BOOKEND_FOREWORD_TEXT` or `BOOKEND_FOREWORD_FILE` is
non-empty; it auto-splits into `clamp(1, 3, round(words / 55))` beats that share
fixed furniture (badge, portrait, kicker) so the beats read as ONE card whose text
turns over rather than as separate slides.
`partners` only when `BOOKEND_PARTNERS_STRIP` exists on disk.

A path variable that is UNSET means "this element is not part of this film". A path
variable that is SET but points at nothing is a broken invocation and exits 2 —
silently dropping a card someone asked for is how a film ships without its foreword.
(`BOOKEND_PARTNERS_STRIP` is the one documented exception: its presence on disk IS
the switch, so a missing file warns and omits the board.)

Pack variables
--------------
    shape     ASPECT · BOOKEND_CARD_SIZE (WxH) · MV_FPS
    colour    BOOKEND_INK #0b1426 · BOOKEND_PAPER #f7f9fc
              BOOKEND_ACCENT #f2a96c · BOOKEND_MUTED #96a3b8
              (PALETTE is prose for image prompts and deliberately does NOT drive
               colour here — "navy/apricot" is not a hex value.)
    type      FONT_DISPLAY · FONT_UI · FONT_BODY   (each "path" or "path:index",
              the index selecting a face inside a .ttc collection)
    art       CLUB_CREST · BOOKEND_PLATE_INTRO/_OUTRO/_PARTNERS/_FOREWORD
              (no plate supplied → a gradient + vignette is synthesized, so a bare
               pack still ships a composed card)
    ident     DISPLAY_NAME · KICKER · CLUB_FOUNDED · CLUB_GROUND · BOOKEND_IDENT_LINES
    title     BOOKEND_TITLE · BOOKEND_TITLE_KICKER
    outro     THANKS_LINE · BOOKEND_FACTS · SUBSCRIBE_LINE · BOOKEND_VALUES_LINE
              BOOKEND_CREDIT_NAME/_ROLE/_PORTRAIT/_KICKER/_CROP
    foreword  BOOKEND_FOREWORD_TEXT | _FILE · _KICKER · _NAME · _ROLE · _PORTRAIT/_CROP
              _SECONDS (explicit per-beat override) · _LEAD · _WPS
    partners  BOOKEND_PARTNERS_STRIP · _KICKER · _CAPTION · _FOOTER
    timing    BOOKEND_IDENT_SECONDS 3.9 · _TITLE_SECONDS 3.1 · _OUTRO_SECONDS 9.0
              _PARTNERS_SECONDS 6.0 · BOOKEND_XFADE_INTRO/_FOREWORD/_OUTRO

In any `|`-separated line list, a line wrapped in `*asterisks*` is set in the accent
colour; everything else is muted.

Usage:
  make_bookends.py --out-dir <dir> [--slug <slug>] [--json-out <cards.json>]
Exit 0 = ok, 2 = bad input.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys

from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont


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


def warn(msg: str) -> None:
    print(f"make_bookends: {msg}", file=sys.stderr)


# --------------------------------------------------------------------------- env

def env(name: str, default: str = "") -> str:
    v = os.environ.get(name)
    return v.strip() if v and v.strip() else default


def env_float(name: str, default: float) -> float:
    v = env(name)
    if not v:
        return default
    try:
        return float(v)
    except ValueError:
        die(f"{name} is not a number: {v!r}")
    return default  # unreachable; keeps type checkers quiet


def env_file(name: str, default: str = "") -> str:
    """A path variable. Unset = the element is not part of this film. Set but
    missing = a broken invocation, which fails rather than silently omitting."""
    v = env(name, default)
    if not v:
        return ""
    p = os.path.abspath(os.path.expanduser(v))
    if not os.path.isfile(p):
        die(f"{name} points at nothing: {p}\n"
            f"  Unset it to leave that element out; a set-but-missing path is a typo, "
            f"not a choice.")
    return p


def env_lines(name: str, default: str = "") -> list[tuple[str, bool]]:
    """A `|`-separated line list. `*line*` marks the accent line."""
    out: list[tuple[str, bool]] = []
    for raw in env(name, default).split("|"):
        s = raw.strip()
        if not s:
            continue
        accent = len(s) > 2 and s.startswith("*") and s.endswith("*")
        out.append((s[1:-1].strip() if accent else s, accent))
    return out


def env_crop(name: str, default: tuple[float, float, float]) -> tuple[float, float, float]:
    """A `cx,cy,frac` disc crop, in fractions of the source photo.

    The default is deliberately GENEROUS — a disc that is too wide only shows more of
    the picture, while one that is too tight cuts the top of somebody's head off and
    pulls the caption underneath into the circle, so the "portrait" contains type.
    Look at the card; if the framing is wrong, state the crop rather than swap the
    photo."""
    v = env(name)
    if not v:
        return default
    parts = [p.strip() for p in v.split(",")]
    if len(parts) != 3:
        die(f"{name} must be 'cx,cy,frac' in fractions, e.g. 0.5,0.42,0.86 — got {v!r}")
    try:
        return (float(parts[0]), float(parts[1]), float(parts[2]))
    except ValueError:
        die(f"{name} must be three numbers: {v!r}")
    return default  # unreachable


def hexcolor(name: str, default: str) -> tuple[int, int, int]:
    v = env(name, default).lstrip("#")
    if len(v) == 3:
        v = "".join(c * 2 for c in v)
    if len(v) != 6 or any(c not in "0123456789abcdefABCDEF" for c in v):
        die(f"{name} must be a hex colour like #0b1426, got {env(name)!r}")
    return (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16))


INK = hexcolor("BOOKEND_INK", "#0b1426")
PAPER = hexcolor("BOOKEND_PAPER", "#f7f9fc")
ACCENT = hexcolor("BOOKEND_ACCENT", "#f2a96c")
MUTED = hexcolor("BOOKEND_MUTED", "#96a3b8")
DIM = tuple(round(c * 0.72) for c in MUTED)          # the quietest register on a card
# Body copy sits one step back from the display white, so a headline still leads the
# card. Derived, not literal: every colour on these cards comes from the four vars.
BODY_INK = tuple(round(PAPER[i] + (MUTED[i] - PAPER[i]) * 0.30) for i in range(3))

# --------------------------------------------------------------------------- type

FONT_DISPLAY = env("FONT_DISPLAY", "/System/Library/Fonts/Supplemental/Didot.ttc")
FONT_UI = env("FONT_UI", "/System/Library/Fonts/Avenir Next Condensed.ttc:2")
FONT_BODY = env("FONT_BODY", "/System/Library/Fonts/HelveticaNeue.ttc")

_FONTS: dict[tuple[str, int, int], ImageFont.FreeTypeFont] = {}


def face(spec: str) -> tuple[str, int]:
    """Split a `path:index` font spec. The index selects a face inside a .ttc."""
    m = re.match(r"^(.*):(\d+)$", spec)
    if m and not os.path.isfile(os.path.expanduser(spec)):
        return os.path.abspath(os.path.expanduser(m.group(1))), int(m.group(2))
    return os.path.abspath(os.path.expanduser(spec)), 0


# A FACE MUST HAVE THE GLYPHS, OR THE CARD IS A ROW OF BOXES. The title card set
# "बगिया का दिन" in Didot, which has no Devanagari, and the film opened on eleven
# tofu rectangles under the kicker (Baby Ram & Sita v7, 2026-09-02). PIL draws the
# missing-glyph box without a word; the coverage is read from the font's own cmap
# here, and a title the display face cannot set falls to the first installed face
# that can — named in the log — or the card refuses to render.
FALLBACK_FACES = (
    "/System/Library/Fonts/Supplemental/Kohinoor.ttc",              # Kohinoor Devanagari
    "/System/Library/Fonts/Supplemental/Devanagari Sangam MN.ttc",
    "/System/Library/Fonts/Supplemental/DevanagariMT.ttc",
    "/System/Library/Fonts/Supplemental/NotoSansDevanagari-Regular.ttf",
    "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
)


def covers(spec: str, text: str) -> bool:
    """Every non-space character of `text` has a glyph in the face `spec` names."""
    import logging
    from fontTools.ttLib import TTFont
    logging.getLogger("fontTools").setLevel(logging.ERROR)   # "extra bytes in post.stringData" is not news
    path, idx = face(spec)
    if not os.path.isfile(path):
        return False
    try:
        cmap = TTFont(path, fontNumber=idx, lazy=True).getBestCmap() or {}
    except Exception:
        return False
    return all(ord(ch) in cmap for ch in text if not ch.isspace())


def face_for(text: str, spec: str, role: str = "title") -> str:
    """The face to set `text` in: `spec` when it covers the text, else the first
    FALLBACK_FACES entry that does (logged), else a refusal — never tofu."""
    if covers(spec, text):
        return spec
    for alt in FALLBACK_FACES:
        if covers(alt, text):
            print(f"[bookends] {role}: {os.path.basename(face(spec)[0])} has no glyphs for "
                  f"{text!r} — set in {os.path.basename(alt)} instead", file=sys.stderr)
            return alt
    die(f"no installed face can set the {role} {text!r}: {os.path.basename(face(spec)[0])} lacks "
        f"its glyphs and none of the fallbacks cover it. Set FONT_DISPLAY to a face with this "
        f"script, or use the romanised title.")


def font(spec: str, size: int) -> ImageFont.FreeTypeFont:
    path, idx = face(spec)
    key = (path, idx, size)
    if key not in _FONTS:
        if not os.path.isfile(path):
            die(f"font not found: {path}   (from {spec!r})")
        try:
            _FONTS[key] = ImageFont.truetype(path, size, index=idx)
        except OSError as e:
            die(f"cannot open font {path} index {idx}: {e}")
    return _FONTS[key]


if face(FONT_BODY)[0] == face(FONT_DISPLAY)[0]:
    die("FONT_BODY and FONT_DISPLAY resolve to the same file.\n"
        "  FONT_DISPLAY is for headlines only. A high-contrast display face set at body\n"
        "  size, reversed out of a dark plate, loses its hairlines — em-dashes disappear\n"
        "  and the paragraph reads as broken. Point FONT_BODY at a sturdier face.")

# -------------------------------------------------------------------------- shape

_ASPECTS = {"9:16": (720, 1280), "16:9": (1280, 720), "1:1": (1080, 1080),
            "4:5": (1024, 1280), "3:4": (960, 1280)}


def card_size() -> tuple[int, int]:
    spec = env("BOOKEND_CARD_SIZE")
    if spec:
        m = re.match(r"^(\d+)[xX](\d+)$", spec)
        if not m:
            die(f"BOOKEND_CARD_SIZE must look like 720x1280, got {spec!r}")
        return int(m.group(1)), int(m.group(2))
    a = env("ASPECT", "9:16")
    if a not in _ASPECTS:
        die(f"ASPECT {a!r} has no card size; set BOOKEND_CARD_SIZE=WxH")
    return _ASPECTS[a]


OUT_W, OUT_H = card_size()
# Type is scaled off the SHORT edge, so a 16:9 card gets the same reading size as a
# 9:16 one instead of type sized to its very long width.
S = min(OUT_W, OUT_H) / 720.0
SAFE = 0.86              # keep every line inside the title-safe area
BAND = (round(OUT_H * 0.06), round(OUT_H * 0.95))


def sz(n: float) -> int:
    return max(7, round(n * S))


def vh(n: float) -> int:
    """A vertical measure, in px of the reference 1280-high card, scaled to THIS
    card's height. Type is sized off the short edge; furniture — badges, portraits,
    the partner bar — has to be sized off the height instead, or a landscape card
    runs out of room before it runs out of copy."""
    return max(8, round(n / 1280.0 * OUT_H))


# ------------------------------------------------------------------------ drawing

def measure(d: ImageDraw.ImageDraw, text: str, f, track: float) -> float:
    return sum(d.textlength(ch, font=f) for ch in text) + track * (len(text) - 1)


def fit(d: ImageDraw.ImageDraw, text: str, f, track: int,
        limit: float | None = None) -> tuple[ImageFont.FreeTypeFont, int]:
    """Shrink the face and its tracking together until the line sits inside the
    title-safe width.

    Hand-placed tracking makes it very easy to run a line past the frame edge (the
    WICC outro's club name did exactly that, touching both margins), and hand-tuning
    a point size per line does not survive a change of pack. So the fit is automatic
    and conservative: `textlength` measures ADVANCE, not ink, so a face whose glyphs
    overhang their advance width (italics, swashes, a heavy didone's terminals) can
    still paint a pixel or two outside what was measured. SAFE=0.86 is the margin
    that absorbs it — do not raise it to reclaim width."""
    limit = OUT_W * SAFE if limit is None else limit
    size = f.size
    while measure(d, text, f, track) > limit and size > 10:
        size -= 1
        f = ImageFont.truetype(f.path, size, index=getattr(f, "index", 0))
        track = max(1, int(track * 0.94))
    return f, track


def needs_shaping(text: str) -> bool:
    """A script whose letters combine (Devanagari and the other Indic scripts, Arabic,
    Thai …) cannot be drawn glyph by glyph: the vowel signs lose their base and render
    as dotted circles — the v8 title card, "बग◌ि य◌ा क◌ा" (2026-09-02). Anything past
    Latin Extended is drawn as ONE shaped string (raqm), tracking forgone."""
    return any(ord(ch) > 0x024F for ch in text)


def tracked(d: ImageDraw.ImageDraw, xy, text: str, f, fill, track: int, anchor="mm"):
    """Draw letterspaced text. PIL has no tracking, so glyphs are placed by hand.
    Wide tracking on small caps is what separates a title card from a caption."""
    if needs_shaping(text):
        # Item 16: the tool looks before a human has to. Without raqm PIL draws a
        # combining script unshaped — the same dotted circles as glyph-by-glyph — and
        # the card would ship to "SOMEONE MUST LOOK AT". Refuse at the source instead.
        from PIL import features
        if not features.check("raqm"):
            die(f"cannot set {text!r}: this Pillow has no raqm (complex-script shaping). "
                f"Install Pillow with libraqm, or set BOOKEND_TITLE to the romanised title (TITLE_ROMAN).")
        f, _ = fit(d, text, f, 0)
        total = d.textlength(text, font=f)
        x = xy[0] - total / 2 if anchor[0] == "m" else xy[0]
        asc, desc = f.getmetrics()
        y = xy[1] - (asc + desc) / 2 if anchor[1] == "m" else xy[1]
        d.text((x, y), text, font=f, fill=fill)
        return total
    f, track = fit(d, text, f, track)
    widths = [d.textlength(ch, font=f) for ch in text]
    total = sum(widths) + track * (len(text) - 1)
    x = xy[0] - total / 2 if anchor[0] == "m" else xy[0]
    asc, desc = f.getmetrics()
    y = xy[1] - (asc + desc) / 2 if anchor[1] == "m" else xy[1]
    for ch, w in zip(text, widths):
        d.text((x, y), ch, font=f, fill=fill)
        x += w + track
    return total


def wrap(d: ImageDraw.ImageDraw, text: str, f, width: float) -> list[str]:
    """Greedy wrap to a pixel width — measured, not guessed at a character count."""
    out, line = [], ""
    for word in text.split():
        trial = f"{line} {word}".strip()
        if d.textlength(trial, font=f) <= width or not line:
            line = trial
        else:
            out.append(line)
            line = word
    if line:
        out.append(line)
    return out


def tracked_wrap(d: ImageDraw.ImageDraw, text: str, f, track: int,
                 max_lines: int = 3) -> list[str]:
    """Wrap a tracked display line onto at most `max_lines`, measuring WITH the
    tracking. A club name is broken across lines rather than shrunk to a whisper."""
    words, out, line = text.split(), [], ""
    limit = OUT_W * SAFE
    for word in words:
        trial = f"{line} {word}".strip()
        if measure(d, trial, f, track) <= limit or not line:
            line = trial
        else:
            out.append(line)
            line = word
    if line:
        out.append(line)
    if len(out) > max_lines:      # too long to break — let fit() shrink it instead
        return [" ".join(words[:0] or words)] if max_lines == 1 else out[:max_lines - 1] + [
            " ".join(out[max_lines - 1:])]
    return out


def rule(im: Image.Image, y: int, halfwidth: int, alpha: int = 200) -> None:
    """A hairline that fades out at both ends, so it reads as light on the card
    rather than as a drawn box."""
    band = Image.new("L", (OUT_W, OUT_H), 0)
    x0, x1 = max(0, OUT_W // 2 - halfwidth), min(OUT_W, OUT_W // 2 + halfwidth)
    for x in range(x0, x1):
        t = abs(x - OUT_W / 2) / halfwidth
        band.putpixel((x, y), int(alpha * (1 - t ** 2)))
    im.paste(Image.new("RGB", (OUT_W, OUT_H), ACCENT), (0, 0), band)


# --------------------------------------------------------------------------- art

def _cover(im: Image.Image) -> Image.Image:
    scale = max(OUT_W / im.width, OUT_H / im.height)
    im = im.resize((max(OUT_W, round(im.width * scale)),
                    max(OUT_H, round(im.height * scale))), Image.LANCZOS)
    left, top = (im.width - OUT_W) // 2, (im.height - OUT_H) // 2
    return im.crop((left, top, left + OUT_W, top + OUT_H))


def _synth_plate(kind: str) -> Image.Image:
    """No art supplied: build the plate rather than fail.

    A pack with nothing but text and a crest still has to ship a composed card, so
    the fallback is a vertical gradient — accent-tinted at the top, sinking to ink —
    under a soft vignette. The tint shifts a little per card so the three plates are
    siblings rather than the same image three times."""
    lift = {"intro": 0.26, "foreword": 0.14, "outro": 0.20, "partners": 0.10}.get(kind, 0.18)
    top = tuple(round(INK[i] + (ACCENT[i] - INK[i]) * lift) for i in range(3))
    bot = tuple(round(INK[i] * 0.72) for i in range(3))
    grad = Image.new("RGB", (1, OUT_H))
    for y in range(OUT_H):
        t = (y / max(1, OUT_H - 1)) ** 0.85   # pool the light in the upper third
        grad.putpixel((0, y), tuple(round(top[i] + (bot[i] - top[i]) * t) for i in range(3)))
    im = grad.resize((OUT_W, OUT_H), Image.BILINEAR)
    v = Image.new("L", (OUT_W, OUT_H), 0)
    ImageDraw.Draw(v).ellipse([-OUT_W * 0.35, -OUT_H * 0.16,
                               OUT_W * 1.35, OUT_H * 1.16], fill=255)
    v = v.filter(ImageFilter.GaussianBlur(OUT_W * 0.11))
    return Image.composite(im, Image.new("RGB", (OUT_W, OUT_H),
                                         tuple(round(c * 0.55) for c in bot)), v)


PLATES = {k: env_file(f"BOOKEND_PLATE_{k.upper()}")
          for k in ("intro", "outro", "partners", "foreword")}


def has_plate(kind: str) -> bool:
    return bool(PLATES.get(kind) or PLATES.get("intro"))


def plate(kind: str, darken: float, blur: float = 0.0) -> Image.Image:
    """Load a backplate, crop it to the card and push it down so type reads."""
    src = PLATES.get(kind) or PLATES.get("intro")
    if src:
        im = _cover(Image.open(src).convert("RGB"))
    else:
        # The synthesized plate is already built to sit under type, so the darkening
        # figures tuned for a bright photographic plate would take it to near-black.
        im = _synth_plate(kind)
        darken = 0.55 + 0.45 * darken
    if blur:
        im = im.filter(ImageFilter.GaussianBlur(blur))
    return ImageEnhance.Brightness(im).enhance(darken)


CREST = env_file("CLUB_CREST")


def badge(size: int) -> Image.Image | None:
    """The REAL mark, cut out of whatever backing it arrived on. Never drawn.

    Alpha is checked FIRST. A file that already carries meaningful transparency is a
    cutout somebody made on purpose — trim it to its own ink and leave it alone,
    because the disc walk below would re-crop it, and a mark that is not circular (a
    shield, a wordmark) would lose its corners. Only a flat opaque file gets the disc
    treatment: full-resolution logo files are routinely 100% opaque, and dropping one
    straight onto a plate puts a hard SQUARE behind the mark, which is the first
    thing an eye lands on."""
    if not CREST:
        return None
    b = Image.open(CREST).convert("RGBA")
    w, h = b.size
    clear = sum(b.getchannel("A").histogram()[:32]) / float(w * h)
    if clear > 0.02:
        bb = b.getchannel("A").getbbox()
        if bb:
            b = b.crop(bb)
            w, h = b.size
    else:
        bg = b.getpixel((2, 2))[:3]
        mid, r = h // 2, w // 2
        for x in range(w // 2):          # walk in from the edge to find the disc
            px = b.getpixel((x, mid))[:3]
            if sum(abs(a - c) for a, c in zip(px, bg)) > 40:
                r = w // 2 - x
                break
        mask = Image.new("L", (w * 4, h * 4), 0)
        ImageDraw.Draw(mask).ellipse([(w // 2 - r) * 4, (h // 2 - r) * 4,
                                      (w // 2 + r) * 4, (h // 2 + r) * 4], fill=255)
        b.putalpha(mask.resize((w, h), Image.LANCZOS).filter(ImageFilter.GaussianBlur(1.2)))
    return b.resize((size, max(1, round(h * size / w))), Image.LANCZOS)


def disc(path: str, size: int, cx: float = 0.5, cy: float = 0.42,
         frac: float = 0.52) -> Image.Image:
    """A circular crop of a photo, feathered so it sits on the plate. A source that
    is already a feathered cutout is only resized — cropping it again would eat the
    edge somebody already made."""
    im = Image.open(path).convert("RGBA")
    w, h = im.size
    if sum(im.getchannel("A").histogram()[:32]) / float(w * h) > 0.02:
        return im.resize((size, size), Image.LANCZOS)
    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)
    face_im = im.crop(box).resize((size, size), Image.LANCZOS)
    mask = Image.new("L", (size * 4, size * 4), 0)
    ImageDraw.Draw(mask).ellipse([6, 6, size * 4 - 6, size * 4 - 6], fill=255)
    face_im.putalpha(mask.resize((size, size), Image.LANCZOS).filter(
        ImageFilter.GaussianBlur(0.8)))
    return face_im


# ------------------------------------------------------------------------- layout

class Stack:
    """A vertical flow of blocks, centred in a band.

    Cards are composed rather than positioned. This is what makes rule 1 real: when
    `CLUB_CREST` is unset the badge block is simply never added and everything below
    moves up, instead of leaving a crest-shaped hole at a hardcoded y."""

    def __init__(self, name: str) -> None:
        self.name = name
        self.items: list[tuple[float, object]] = []

    def gap(self, h: float) -> None:
        self.items.append((h, None))

    def add(self, h: float, fn) -> None:
        self.items.append((h, fn))

    @property
    def height(self) -> float:
        return sum(h for h, _ in self.items)

    def draw(self, top: float | None = None, band: tuple[int, int] | None = None,
             align: str = "center") -> float:
        if band is not None:
            bt, bb = band
            avail = bb - bt
            if self.height > avail:
                # Gaps are air, copy is not: squeeze the air first — to no less than
                # half — before refusing. tracked() protects the side margins and
                # nothing else protects the top and bottom, so once the air is gone an
                # over-full card fails LOUDLY rather than drawing its last line off
                # the frame, where a still would never show it.
                gaps = sum(h for h, fn in self.items if fn is None)
                ink = self.height - gaps
                if gaps <= 0 or ink + gaps * 0.5 > avail:
                    die(f"card '{self.name}' does not fit: {self.height:.0f}px of content "
                        f"in a {avail}px band.\n"
                        f"  Shorten the copy, or raise BOOKEND_CARD_SIZE.")
                k = (avail - ink) / gaps
                self.items = [(h * k, fn) if fn is None else (h, fn) for h, fn in self.items]
            top = bt if align == "top" else bt + (avail - self.height) / 2
        y = float(top or 0)
        for h, fn in self.items:
            if fn is not None:
                fn(y, h)
            y += h
        return y


def line_block(stack: Stack, d: ImageDraw.ImageDraw, text: str, spec: str, size: int,
               fill, track: int, lead: float = 1.0) -> None:
    """Add one tracked line, measured at its FITTED size so the stack height is real."""
    f, tr = fit(d, text, font(spec, size), track)
    asc, desc = f.getmetrics()
    stack.add((asc + desc) * lead,
              lambda y, h, t=text, ff=f, c=fill, k=tr: tracked(
                  d, (OUT_W // 2, y), t, ff, c, k, anchor="ma"))


def image_block(stack: Stack, im: Image.Image, art: Image.Image, x: int | None = None,
                gap_after: float = 0.0) -> None:
    px = (OUT_W - art.width) // 2 if x is None else x
    stack.add(art.height, lambda y, h: im.alpha_composite(art, (px, int(y))))
    if gap_after:
        stack.gap(gap_after)


def rule_block(stack: Stack, im: Image.Image, halfwidth: int, alpha: int = 200) -> None:
    stack.add(sz(2), lambda y, h: rule(im, int(y), halfwidth, alpha))


# -------------------------------------------------------------------------- cards

DISPLAY_NAME = env("DISPLAY_NAME") or env("CHANNEL") or env("PACK_NAME") or "UNTITLED"


def card_ident() -> Image.Image:
    """Beat 1 — the mark, the name, the year. The film's opening frame, so it is
    composed from the first frame: never a fade up from black, which hands YouTube a
    grey card for a thumbnail."""
    im = plate("intro", 0.78).convert("RGBA")
    b = badge(vh(300))
    if b is not None:
        # a soft pool of light under the badge so it sits in the scene, not on top
        glow = Image.new("RGBA", (OUT_W, OUT_H), (0, 0, 0, 0))
        gy = round(OUT_H * 0.36)
        ImageDraw.Draw(glow).ellipse(
            [OUT_W // 2 - sz(250), gy, OUT_W // 2 + sz(250), gy + vh(340)],
            fill=MUTED + (60,))
        im = Image.alpha_composite(im, glow.filter(ImageFilter.GaussianBlur(sz(70))))
    d = ImageDraw.Draw(im)
    st = Stack("ident")
    if b is not None:
        image_block(st, im, b, gap_after=vh(56))
    for ln in tracked_wrap(d, DISPLAY_NAME.upper(), font(FONT_DISPLAY, sz(46)), sz(9), 2):
        line_block(st, d, ln, FONT_DISPLAY, sz(46), PAPER, sz(9), 1.18)
    st.gap(vh(22))
    rule_block(st, im, sz(150))
    st.gap(vh(30))
    lines = env_lines("BOOKEND_IDENT_LINES")
    if not lines:
        if env("KICKER"):
            lines.append((env("KICKER").upper(), False))
        if env("CLUB_FOUNDED"):
            lines.append((f"ESTABLISHED {env('CLUB_FOUNDED')}", True))
        if env("CLUB_GROUND"):
            lines.append((env("CLUB_GROUND").upper(), False))
    for text, accent in lines:
        line_block(st, d, text, FONT_UI, sz(22), ACCENT if accent else MUTED,
                   sz(12) if accent else sz(9), 1.7)
    st.draw(band=BAND)
    return im.convert("RGB")


def card_title() -> Image.Image:
    """Beat 2 — the title. The plate is blurred so nothing competes with the words."""
    im = plate("intro", 0.42, blur=sz(14)).convert("RGBA")
    d = ImageDraw.Draw(im)
    title = env("BOOKEND_TITLE", DISPLAY_NAME).upper()
    kicker = env("BOOKEND_TITLE_KICKER", env("KICKER")).upper()
    st = Stack("title")
    if kicker and kicker != title:
        line_block(st, d, kicker, FONT_UI, sz(24), ACCENT, sz(14), 1.0)
        st.gap(vh(60))
    title_face = face_for(title, FONT_DISPLAY, "title")
    for ln in tracked_wrap(d, title, font(title_face, sz(76)), sz(4), 3):
        line_block(st, d, ln, title_face, sz(76), PAPER, sz(4), 1.10)
    st.gap(vh(24))
    rule_block(st, im, sz(120), 190)
    st.gap(vh(34))
    # the film's own name under the rule — unless the film IS named after the pack,
    # in which case printing it twice on one card just reads as a mistake
    if DISPLAY_NAME.upper() != title:
        line_block(st, d, DISPLAY_NAME.upper(), FONT_UI, sz(20), MUTED, sz(9))
    st.draw(band=BAND)
    return im.convert("RGB")


def card_outro() -> Image.Image:
    """The end card — the name, the club's own line, its facts, and the credit."""
    im = plate("outro", 0.88).convert("RGBA")
    if has_plate("outro"):
        # A photographic plate's own horizon tends to run straight through where the
        # small print sits, and letterspaced caps on a bright band lose their
        # contrast. Lay a soft scrim over the middle, feathered so it never reads as
        # a rectangle. The synthesized plate has no horizon to tame, and a scrim on
        # a smooth gradient only shows its own edges — so it gets none.
        scrim = Image.new("RGBA", (OUT_W, OUT_H), (0, 0, 0, 0))
        ImageDraw.Draw(scrim).rectangle(
            [0, round(OUT_H * 0.23), OUT_W, round(OUT_H * 0.78)],
            fill=(INK[0] // 2, INK[1] // 2, INK[2] // 2, 165))
        im = Image.alpha_composite(im, scrim.filter(ImageFilter.GaussianBlur(sz(60))))
    d = ImageDraw.Draw(im)
    st = Stack("outro")
    b = badge(vh(150))
    if b is not None:
        image_block(st, im, b, gap_after=vh(46))
    for ln in tracked_wrap(d, DISPLAY_NAME.upper(), font(FONT_DISPLAY, sz(38)), sz(6), 2):
        line_block(st, d, ln, FONT_DISPLAY, sz(38), PAPER, sz(6), 1.20)
    st.gap(vh(18))
    rule_block(st, im, sz(170))
    st.gap(vh(30))
    if env("THANKS_LINE"):
        for ln in wrap(d, env("THANKS_LINE").upper(), font(FONT_UI, sz(23)),
                       OUT_W * SAFE * 0.96):
            line_block(st, d, ln, FONT_UI, sz(23), PAPER, sz(5), 1.5)
        st.gap(vh(26))
    for text, accent in env_lines("BOOKEND_FACTS"):
        line_block(st, d, text, FONT_UI, sz(18), ACCENT if accent else MUTED, sz(6), 1.85)

    name = env("BOOKEND_CREDIT_NAME")
    if name:
        st.gap(vh(30))
        portrait = env_file("BOOKEND_CREDIT_PORTRAIT") or env_file("PORTRAIT")
        if portrait:
            art = disc(portrait, vh(132), *env_crop("BOOKEND_CREDIT_CROP",
                                                   (0.50, 0.42, 0.86)))
            ring = Image.new("RGBA", (OUT_W, OUT_H), (0, 0, 0, 0))
            rd = ImageDraw.Draw(ring)
            st.add(art.height, lambda y, h, a=art, r=ring, rr=rd: (
                rr.ellipse([OUT_W // 2 - a.width // 2 - sz(5), int(y) - sz(5),
                            OUT_W // 2 + a.width // 2 + sz(5), int(y) + a.height + sz(5)],
                           outline=ACCENT + (140,), width=max(2, sz(2))),
                im.alpha_composite(r), im.alpha_composite(a, (OUT_W // 2 - a.width // 2,
                                                              int(y)))))
            st.gap(vh(24))
        line_block(st, d, env("BOOKEND_CREDIT_KICKER", "PERFORMED BY"), FONT_UI, sz(16),
                   MUTED, sz(8), 1.7)
        line_block(st, d, name.upper(), FONT_DISPLAY, sz(32), PAPER, sz(5), 1.35)
        if env("BOOKEND_CREDIT_ROLE"):
            line_block(st, d, env("BOOKEND_CREDIT_ROLE").upper(), FONT_UI, sz(15),
                       MUTED, sz(6), 1.8)
    if env("SUBSCRIBE_LINE"):
        st.gap(vh(24))
        line_block(st, d, env("SUBSCRIBE_LINE").upper(), FONT_UI, sz(28), ACCENT, sz(14), 1.5)
    if env("BOOKEND_VALUES_LINE"):
        line_block(st, d, env("BOOKEND_VALUES_LINE").upper(), FONT_UI, sz(15), DIM, sz(6), 1.8)
    st.draw(band=BAND)
    return im.convert("RGB")


def card_partners(strip_path: str) -> Image.Image:
    """The end board. The marks are the SUPPLIED artwork, composited WHOLE onto a
    white bar — never redrawn, never recoloured, never split. These marks are drawn
    for light backgrounds, so keying the page white out of them makes their own light
    parts transparent and their dark type vanishes against a dark card."""
    im = plate("partners", 0.95).convert("RGBA")
    d = ImageDraw.Draw(im)
    st = Stack("partners")
    b = badge(vh(120))
    if b is not None:
        image_block(st, im, b, gap_after=vh(50))
    line_block(st, d, DISPLAY_NAME.upper(), FONT_UI, sz(21), MUTED, sz(9), 1.6)
    st.gap(vh(26))
    line_block(st, d, env("BOOKEND_PARTNERS_KICKER", "PROUDLY SUPPORTED BY"),
               FONT_UI, sz(26), ACCENT, sz(14), 1.5)
    st.gap(vh(40))

    strip = Image.open(strip_path).convert("RGB")
    bar_w = int(OUT_W * 0.84)
    pad = sz(28)
    # A wide card runs out of HEIGHT before it runs out of width, so cap the bar by
    # how tall a full-width strip would make it rather than letting it eat the card.
    max_h = OUT_H * 0.30
    if strip.height * (bar_w - pad * 2) / strip.width + pad * 2 > max_h:
        bar_w = int((max_h - pad * 2) * strip.width / strip.height) + pad * 2
    sw = bar_w - pad * 2
    strip = strip.resize((sw, max(1, round(strip.height * sw / strip.width))), Image.LANCZOS)
    bar_h = strip.height + pad * 2
    bar = Image.new("RGBA", (bar_w, bar_h), PAPER + (255,))
    # round the corners so the bar reads as a designed panel, not a pasted screenshot
    mask = Image.new("L", (bar_w * 4, bar_h * 4), 0)
    ImageDraw.Draw(mask).rounded_rectangle([0, 0, bar_w * 4, bar_h * 4],
                                           radius=sz(28) * 4, fill=255)
    bar.putalpha(mask.resize((bar_w, bar_h), Image.LANCZOS))
    bar.paste(strip, (pad, pad))
    bx = OUT_W // 2 - bar_w // 2

    def draw_bar(y: float, h: float) -> None:
        shadow = Image.new("RGBA", (OUT_W, OUT_H), (0, 0, 0, 0))
        ImageDraw.Draw(shadow).rounded_rectangle(
            [bx - sz(6), int(y) + sz(8), bx + bar_w + sz(6), int(y) + bar_h + sz(14)],
            radius=sz(30), fill=(0, 0, 0, 130))
        im.alpha_composite(shadow.filter(ImageFilter.GaussianBlur(sz(18))))
        im.alpha_composite(bar, (bx, int(y)))

    st.add(bar_h, draw_bar)
    st.gap(vh(50))
    line_block(st, d, env("BOOKEND_PARTNERS_CAPTION", "PRINCIPAL PARTNERS"),
               FONT_UI, sz(19), MUTED, sz(10), 1.7)
    if env("SUBSCRIBE_LINE"):
        st.gap(vh(40))
        line_block(st, d, env("SUBSCRIBE_LINE").upper(), FONT_UI, sz(30), ACCENT, sz(15), 1.5)
    footer = env("BOOKEND_PARTNERS_FOOTER", "SPONSORSHIP ENQUIRIES WELCOME")
    if footer:
        line_block(st, d, footer.upper(), FONT_UI, sz(15), DIM, sz(6), 1.8)
    st.draw(band=BAND)
    return im.convert("RGB")


# ----------------------------------------------------------------------- foreword

def foreword_text() -> str:
    inline = env("BOOKEND_FOREWORD_TEXT")
    path = env_file("BOOKEND_FOREWORD_FILE")
    if inline and path:
        die("set BOOKEND_FOREWORD_TEXT or BOOKEND_FOREWORD_FILE, not both")
    if path:
        return open(path, encoding="utf-8").read()
    return inline


def words_in(text: str) -> int:
    """Count words, not tokens: a bare em-dash between clauses is punctuation and
    must not buy the card another beat."""
    return len([t for t in text.split() if any(c.isalnum() for c in t)])


def split_foreword(text: str) -> list[list[str]]:
    """Split the foreword into 1-3 beats of whole paragraphs.

    `round(words / 55)` is the shape: ~90 words on a single card flashes past unread,
    and a 17-second wall of type is not a message, it is a document. Paragraphs are
    never broken across beats — a beat that starts mid-thought reads as a page turn."""
    paras = [" ".join(p.split()) for p in re.split(r"\n\s*\n", text.strip()) if p.strip()]
    if not paras:
        die("the foreword is empty — unset BOOKEND_FOREWORD_TEXT/_FILE to leave it out")
    total = words_in(text)
    n = max(1, min(3, round(total / 55)))
    n = min(n, len(paras))
    beats: list[list[str]] = [[] for _ in range(n)]
    target = total / n
    i, run = 0, 0.0
    for k, p in enumerate(paras):
        beats[i].append(p)
        run += words_in(p)
        left = len(paras) - k - 1
        # move on once this beat has had its share — or sooner, if the paragraphs
        # still to place would otherwise leave a later beat empty
        if i < n - 1 and (run >= target * (i + 1) or left <= n - 1 - i):
            i += 1
    return [b for b in beats if b]


def foreword_seconds(beats: list[list[str]]) -> list[float]:
    """Seconds per beat.

    `BOOKEND_FOREWORD_SECONDS` (comma-separated) is authoritative when set — the
    delivered WICC beats were hand-timed at 9.5s and 7.0s, which is ~8 words/sec and
    deliberately tighter than reading pace because the card is TAKEN IN under a bed,
    not read aloud. Nothing predicts a hand-timed beat, so the pack states it.

    The derived default is honest reading pace instead: a lead-in while the portrait
    and the kicker land, then words at BOOKEND_FOREWORD_WPS (3.4 w/s ≈ 200 wpm)."""
    override = env("BOOKEND_FOREWORD_SECONDS")
    if override:
        vals = [v.strip() for v in override.split(",") if v.strip()]
        if len(vals) != len(beats):
            die(f"BOOKEND_FOREWORD_SECONDS has {len(vals)} value(s) but the foreword "
                f"split into {len(beats)} beat(s): {override!r}")
        try:
            return [round(float(v), 2) for v in vals]
        except ValueError:
            die(f"BOOKEND_FOREWORD_SECONDS must be numbers: {override!r}")
    lead = env_float("BOOKEND_FOREWORD_LEAD", 1.6)
    wps = env_float("BOOKEND_FOREWORD_WPS", 3.4)
    if wps <= 0:
        die("BOOKEND_FOREWORD_WPS must be > 0")
    return [round(max(4.0, lead + words_in(" ".join(b)) / wps), 1) for b in beats]


def card_foreword(paras: list[str], sign_off: bool) -> Image.Image:
    """One beat of the foreword.

    The furniture — badge, portrait, kicker — is drawn at FIXED positions on every
    beat, and only the body flows. That is what makes two beats read as one card
    whose text turns over rather than as two separate slides."""
    im = plate("foreword", 0.95).convert("RGBA")
    d = ImageDraw.Draw(im)
    portrait = env_file("BOOKEND_FOREWORD_PORTRAIT")
    kicker = env("BOOKEND_FOREWORD_KICKER", "A MESSAGE FROM OUR CHAIRMAN").upper()

    def build_head(with_badge: bool) -> Stack:
        head = Stack("foreword-head")
        b = badge(vh(96)) if with_badge else None
        if b is not None:
            image_block(head, im, b, gap_after=vh(60))
        if portrait:
            art = disc(portrait, vh(188), *env_crop("BOOKEND_FOREWORD_CROP",
                                                    (0.50, 0.42, 0.86)))
            ring = Image.new("RGBA", (OUT_W, OUT_H), (0, 0, 0, 0))
            rd = ImageDraw.Draw(ring)
            head.add(art.height, lambda y, h, a=art, r=ring, rr=rd: (
                rr.ellipse([OUT_W // 2 - a.width // 2 - sz(6), int(y) - sz(6),
                            OUT_W // 2 + a.width // 2 + sz(6), int(y) + a.height + sz(6)],
                           outline=ACCENT + (150,), width=max(2, sz(3))),
                im.alpha_composite(r),
                im.alpha_composite(a, (OUT_W // 2 - a.width // 2, int(y)))))
            head.gap(vh(38))
        if kicker:
            line_block(head, d, kicker, FONT_UI, sz(21), ACCENT, sz(13), 1.4)
        return head

    # Nothing is painted until draw(), so the head can be measured and rebuilt. On a
    # short card the badge is the first thing to go: it is decorative here (it is
    # already on the ident and the end card) and the message is not.
    head = build_head(with_badge=True)
    top = BAND[0] + sz(30)
    if BAND[1] - (top + head.height + sz(58)) < OUT_H * 0.42:
        head = build_head(with_badge=False)
    head_bottom = head.draw(top=top)

    # The body starts at a FIXED y under the furniture on every beat. Centring it
    # would drift the first line by however much the beat's own copy weighs, and the
    # beats would stop reading as one card whose text turns over.
    body_band = (round(head_bottom + sz(58)), BAND[1])

    def build_sign() -> Stack:
        """The sign-off, measured rather than estimated — a guessed reserve is how the
        body ends up sized to fit a block that turns out taller than the guess."""
        sign = Stack("foreword-signoff")
        if not sign_off:
            return sign
        sign.gap(vh(40))
        rule_block(sign, im, sz(110), 190)
        sign.gap(vh(34))
        if env("BOOKEND_FOREWORD_NAME"):
            line_block(sign, d, env("BOOKEND_FOREWORD_NAME").upper(), FONT_DISPLAY,
                       sz(40), PAPER, sz(6), 1.30)
        if env("BOOKEND_FOREWORD_ROLE"):
            line_block(sign, d, env("BOOKEND_FOREWORD_ROLE").upper(), FONT_UI, sz(20),
                       ACCENT, sz(12), 1.7)
        line_block(sign, d, DISPLAY_NAME.upper(), FONT_UI, sz(16), MUTED, sz(6), 1.7)
        return sign

    sign_h = build_sign().height
    size, leading = sz(25), sz(38)
    fb = font(FONT_BODY, size)
    width = OUT_W * 0.80
    lines: list[list[str]] = [wrap(d, p, fb, width) for p in paras]
    # Auto-fit the body the way tracked() auto-fits a line: a foreword is written by
    # a person, not sized to a template, so shrink the face before refusing the card.
    while size > sz(17):
        need = sum(len(g) for g in lines) * leading + (len(lines) - 1) * sz(22) + sign_h
        if need <= body_band[1] - body_band[0]:
            break
        size -= 1
        leading = round(leading * 0.97)
        fb = font(FONT_BODY, size)
        lines = [wrap(d, p, fb, width) for p in paras]

    body = Stack("foreword-body")
    for gi, group in enumerate(lines):
        for ln in group:
            body.add(leading, lambda y, h, t=ln, f=fb: d.text(
                (OUT_W // 2, y), t, font=f, fill=BODY_INK, anchor="ma"))
        if gi < len(lines) - 1:
            body.gap(sz(22))
    body.items.extend(build_sign().items)
    body.draw(band=body_band, align="top")
    return im.convert("RGB")


# --------------------------------------------------------------------------- main

ZOOM = {"ident": 1.055, "title": 1.040, "outro": 1.045, "partners": 1.030,
        "foreword": 1.030}


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out-dir", required=True, help="where the card PNGs are written")
    ap.add_argument("--slug", default="", help="recorded in the manifest, for traceability")
    ap.add_argument("--json-out", default="",
                    help="write the card/block manifest here (build_bookends.sh reads it, "
                         "so no duration is ever hardcoded in the shell)")
    args = ap.parse_args()
    os.makedirs(args.out_dir, exist_ok=True)

    cards: list[dict] = []
    blocks: list[dict] = []

    def emit(cid: str, im: Image.Image, seconds: float, zoom: float) -> None:
        if im.size != (OUT_W, OUT_H):
            die(f"card {cid} came out {im.size}, expected {(OUT_W, OUT_H)}")
        name = f"card-{cid}.png"
        im.save(os.path.join(args.out_dir, name))
        cards.append({"id": cid, "file": name, "seconds": round(seconds, 3), "zoom": zoom})
        print(f"  {name}  {seconds:.2f}s")

    def block(bid: str, ids: list[str], xfade: float, audio: str) -> None:
        secs = {c["id"]: c["seconds"] for c in cards}
        total = sum(secs[i] for i in ids) - xfade * (len(ids) - 1)
        blocks.append({"id": bid, "cards": ids, "xfade": round(xfade, 3) if len(ids) > 1
                       else 0.0, "seconds": round(total, 3), "audio": audio})

    order: list[str] = []

    # --- foreword (optional) -------------------------------------------------
    text = foreword_text()
    if text.strip():
        beats = split_foreword(text)
        secs = foreword_seconds(beats)
        ids = []
        for n, (paras, s) in enumerate(zip(beats, secs), start=1):
            cid = f"foreword-{n}"
            emit(cid, card_foreword(paras, sign_off=(n == len(beats))), s, ZOOM["foreword"])
            ids.append(cid)
        block("FOREWORD", ids, env_float("BOOKEND_XFADE_FOREWORD", 0.5), "bed")
        order.append("FOREWORD")

    # --- intro (always) ------------------------------------------------------
    emit("ident", card_ident(), env_float("BOOKEND_IDENT_SECONDS", 3.9), ZOOM["ident"])
    emit("title", card_title(), env_float("BOOKEND_TITLE_SECONDS", 3.1), ZOOM["title"])
    block("INTRO", ["ident", "title"], env_float("BOOKEND_XFADE_INTRO", 0.45), "riser")
    order += ["INTRO", "BODY"]

    # --- end (outro always; partner board when its artwork exists) -----------
    emit("outro", card_outro(), env_float("BOOKEND_OUTRO_SECONDS", 9.0), ZOOM["outro"])
    end_ids = ["outro"]
    strip = env("BOOKEND_PARTNERS_STRIP")
    if strip:
        strip = os.path.abspath(os.path.expanduser(strip))
        if os.path.isfile(strip):
            emit("partners", card_partners(strip),
                 env_float("BOOKEND_PARTNERS_SECONDS", 6.0), ZOOM["partners"])
            end_ids.append("partners")
        else:
            # documented exception: presence on disk IS the switch for this board, so
            # a missing file omits it — but never silently.
            warn(f"BOOKEND_PARTNERS_STRIP not on disk, no partner board: {strip}")
    block("OUTRO", end_ids, env_float("BOOKEND_XFADE_OUTRO", 0.6), "tail")
    order.append("OUTRO")

    manifest = {
        "schemaVersion": 1,
        "slug": args.slug,
        "card": {"width": OUT_W, "height": OUT_H},
        "fps": env_float("MV_FPS", 24.0),
        # the animator renders the still large and zooms INTO it, so a slow push never
        # samples above the source
        "renderScale": 3,
        "cards": cards,
        "blocks": blocks,
        "order": order,
        "bookendSeconds": round(sum(b["seconds"] for b in blocks), 3),
    }
    if args.json_out:
        os.makedirs(os.path.dirname(os.path.abspath(args.json_out)) or ".", exist_ok=True)
        with open(args.json_out, "w", encoding="utf-8") as fh:
            json.dump(manifest, fh, indent=2)
            fh.write("\n")
        print(f"  {os.path.basename(args.json_out)}  "
              f"{len(cards)} card(s), {manifest['bookendSeconds']:.2f}s of bookend")


if __name__ == "__main__":
    main()
