#!/usr/bin/env python3
"""Caption and render primitives for kirupa.com podcast highlight clips.

The reusable builder imports this module for the proven caption layout: Born2bSportyV10, white text, soft drop shadow, landscape captions at 60 px, and vertical captions at 66 px nested in the landscape line breaks. The legacy CLI at the bottom is kept only for compatibility with the original Dave workflow.
"""

from __future__ import annotations

import argparse
import functools
import json
import math
import re
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

from PIL import Image, ImageDraw, ImageFilter, ImageFont

SOURCE = Path("source.mp4")
FILES = Path(__file__).resolve().parent
TOKENS_PATH = FILES / "clips-work" / "editorial_tokens.json"
WITNESS_DIR = FILES / "witness"
WORK_ROOT = FILES / "clips-work" / "build"
OUTPUT_DIR = FILES / "out"
CAPTION_FONT = Path.home() / "Library" / "Fonts" / "Born2bSportyV10.ttf"

SOURCE_W, SOURCE_H = 3840, 2160
CROP_W = 1216  # 9:16 window over the 2160-tall source, kept even for yuv420p



@dataclass(frozen=True)
class Format:
    key: str
    width: int
    height: int
    font_size: int
    center_y: int
    max_width: int
    spacing: int
    shadow_offset: tuple[int, int]
    max_chars: int
    max_words: int
    bitrate: tuple[str, str, str]
    short_chars: int = 15
    nest_in: Optional[str] = None
    center_x: Optional[int] = None

    @property
    def suffix(self) -> str:
        return f"{self.width}x{self.height}"


LANDSCAPE = Format(
    key="landscape-16x9",
    width=1920,
    height=1080,
    font_size=60,
    center_y=900,
    max_width=1500,
    spacing=10,
    shadow_offset=(6, 8),
    max_chars=56,
    max_words=12,
    bitrate=("9M", "13M", "18M"),
)

VERTICAL = Format(
    key="vertical-9x16",
    width=1080,
    height=1920,
    font_size=66,
    center_y=1480,
    max_width=870,
    spacing=12,
    shadow_offset=(6, 8),
    max_chars=36,
    max_words=8,
    bitrate=("8M", "12M", "16M"),
    short_chars=9,
    nest_in="landscape",
    center_x=525,
)

FORMATS = {"landscape": LANDSCAPE, "vertical": VERTICAL}


@dataclass(frozen=True)
class Override:
    """Swap editorial words for what the clip's audio actually says."""

    near: float
    match: tuple[str, ...]
    words: tuple[tuple[str, float, float], ...]


@dataclass(frozen=True)
class Clip:
    slug: str
    title: str
    start: float
    end: float
    post_hook: str
    crop_x: dict[str, int] = field(default_factory=dict)
    overrides: tuple[Override, ...] = ()
    fade_in: float = 0.04
    fade_out: float = 0.06

    @property
    def duration(self) -> float:
        return round(self.end - self.start, 3)


# The reusable highlighter passes speakers and clips in its own JSON specs.
# Legacy Dave-only constants from the original engine were intentionally removed.
WITNESSES: dict[str, tuple[tuple[str, float], ...]] = {}
CLIPS: list[Clip] = []

GLYPH_MAP = [
    ("\u2019", "'"),
    ("\u2018", "'"),
    ("\u201c", '"'),
    ("\u201d", '"'),
    ("\u2014", " - "),
    ("\u2013", "-"),
    ("\u2026", "..."),
]

SENTENCE_END = re.compile(r"[.!?\u2026][\"'\u201d\u2019)]*$")
CLAUSE_END = re.compile(r"([,;:]|\u2014)[\"'\u201d\u2019)]*$")
CONJUNCTIONS = {
    "and", "but", "because", "that", "which", "where", "when", "so", "if", "or", "while",
    "who", "what", "how", "once", "until", "unless", "although", "though", "since",
    "whether", "otherwise", "instead",
}
PREPOSITIONS = {
    "to", "in", "on", "for", "with", "from", "about", "after", "before", "into", "across",
    "through", "without", "during",
}
NEXT_GLUE = {"of"}
KEEP_TOGETHER = [
    phrase.split()
    for phrase in (
        "at the end of the day",
        "back in the day",
        "in the first place",
        "this day and age",
        "taking care of",
        "takes hold of",
        "dancing on the keyboard",
        "the pilot of a plane",
        "lots and lots of people",
        "a bit like",
        "the starter of the banquet",
        "above all else",
        "this latest monologue",
        "the one kernel",
        "the digital side of our world",
        "ironsmiths blacksmiths",
        "my point of view on that",
        "is that i think",
        "very distinct camps",
        "able to hide behind",
        "on the other end of the spectrum",
        "lots more questions",
        "is going to",
        "a basic understanding",
        "when there were",
        "of making horseshoes",
        "of my thinking",
        "yearn for",
    )
]
GLUE = {
    "a", "an", "the", "this", "that", "your", "my", "our", "their", "his", "her", "its",
    "so", "very", "of", "to", "and", "or", "how", "what", "with", "in", "on", "for",
    "from", "by", "at", "is", "are", "was", "were", "be", "i", "i'm", "we", "you",
    "they", "it's", "all", "that's", "there's", "who's", "what's", "he's", "she's",
    "i'd", "we'd", "you'd", "they'd", "i've", "we've", "you've", "they've", "i'll",
    "we'll", "you'll", "they'll", "we're", "you're", "they're", "because",
}
QUOTE_MARKS = re.compile("[\"\u201c\u201d]")
DETERMINERS = {
    "a", "an", "the", "this", "these", "those", "my", "your", "our", "their", "his", "her",
    "its", "such", "every", "each",
}


def normalize(word: str) -> str:
    return re.sub(r"[^a-z']", "", word.lower().replace("\u2019", "'"))


@functools.lru_cache(maxsize=None)
def witness_words(name: str, offset: float) -> tuple[tuple[float, float, str], ...]:
    data = json.loads((WITNESS_DIR / name).read_text(encoding="utf-8"))
    segments = data["segments"] if isinstance(data, dict) else data
    return tuple(
        (word["start"] + offset, word["end"] + offset, normalize(word["word"]))
        for segment in segments
        for word in segment.get("words", [])
    )


def witness_time(speaker: str, text: str, low: float, high: float) -> Optional[tuple[float, float]]:
    """Where the witnesses heard this word between two known neighbors.

    Whisper tends to stretch words into the silence around them, so take the
    latest start and the earliest end that any witness reports.
    """
    starts, ends = [], []
    for name, offset in WITNESSES[speaker]:
        hits = [word for word in witness_words(name, offset) if word[2] == text and low <= word[0] and word[1] <= high]
        if len(hits) == 1:
            starts.append(hits[0][0])
            ends.append(hits[0][1])
    if not starts:
        return None
    start = max(starts)
    return start, max(start + 0.05, min(ends))


def split_dashes(tokens: list[dict]) -> list[dict]:
    """Split words joined by an em dash so the dash can become a caption break.

    The editorial joined these words, so the alignment never anchored them.
    Re-time each half from the witnesses, falling back to a character-weighted
    split of the interpolated span.
    """
    result: list[dict] = []
    for index, token in enumerate(tokens):
        parts = re.split(r"(?<=\u2014)(?=\S)", token["text"])
        if len(parts) == 1:
            result.append(token)
            continue
        previous = tokens[index - 1] if index else None
        following = tokens[index + 1] if index + 1 < len(tokens) else None
        low = previous["end"] - 0.3 if previous and previous["speaker"] == token["speaker"] else token["start"] - 2.0
        high = following["start"] + 0.3 if following and following["speaker"] == token["speaker"] else token["end"] + 2.0
        timed = [witness_time(token["speaker"], normalize(part), low, high) for part in parts]
        if all(timed) and all(a[1] <= b[0] + 0.02 for a, b in zip(timed, timed[1:])):
            result.extend({**token, "text": part, "start": start, "end": end} for part, (start, end) in zip(parts, timed))
            continue
        weights = [max(1, len(re.sub(r"\W", "", part))) for part in parts]
        span = token["end"] - token["start"]
        cursor = token["start"]
        for part, weight in zip(parts, weights):
            piece_end = cursor + span * weight / sum(weights)
            result.append({**token, "text": part, "start": cursor, "end": piece_end})
            cursor = piece_end
    return result


def load_tokens() -> list[dict]:
    """Editorial words in transcript order (never re-sorted), with usable timings."""
    raw = json.loads(TOKENS_PATH.read_text(encoding="utf-8"))
    tokens = [
        {"text": item["text"], "start": float(item["start"]), "end": float(item["end"]), "speaker": item["speaker"]}
        for item in raw
    ]
    for index, token in enumerate(tokens):
        if token["end"] - token["start"] >= 0.05:
            continue
        following = tokens[index + 1] if index + 1 < len(tokens) else None
        if following and following["speaker"] == token["speaker"] and following["start"] > token["start"] + 0.05:
            token["end"] = min(token["start"] + 0.6, following["start"])
        else:
            token["end"] = token["start"] + 0.12
    tokens = split_dashes(tokens)
    for previous, token in zip(tokens, tokens[1:]):
        if token["speaker"] == previous["speaker"] and token["start"] < previous["end"]:
            token["start"] = previous["end"]
            token["end"] = max(token["end"], token["start"] + 0.05)
    return tokens


def apply_override(words: list[dict], override: Override) -> list[dict]:
    size = len(override.match)
    for index in range(len(words) - size + 1):
        window = words[index:index + size]
        if tuple(word["text"] for word in window) == override.match and abs(window[0]["start"] - override.near) < 1.5:
            speaker = window[0]["speaker"]
            replacement = [
                {"text": text, "start": start, "end": end, "speaker": speaker}
                for text, start, end in override.words
            ]
            return words[:index] + replacement + words[index + size:]
    raise SystemExit(f"Override {override.match} not found near {override.near}")


def caption_words(tokens: list[dict], clip: Clip, end: Optional[float] = None) -> list[dict]:
    """Words spoken inside the clip, in editorial order, ending on a full sentence."""
    stop = clip.end if end is None else end
    indexes = [index for index, token in enumerate(tokens) if token["end"] > clip.start and token["start"] < stop]
    words = [dict(tokens[index]) for index in indexes]
    for override in clip.overrides:
        words = apply_override(words, override)
    if end is None:
        last = max((index for index, word in enumerate(words) if SENTENCE_END.search(word["text"])), default=None)
        if last is not None:
            words = words[: last + 1]
    if indexes and indexes[0] > 0 and not SENTENCE_END.search(tokens[indexes[0] - 1]["text"]):
        print(f"warning: {clip.slug} starts mid-sentence at {words[0]['text']!r}")
    return words


def balance_quotes(text: str) -> str:
    """Keep curly quotes only when both halves land in the same caption."""
    keep = [True] * len(text)
    open_index: Optional[int] = None
    for index, char in enumerate(text):
        if char == "\u201c":
            if open_index is not None:
                keep[open_index] = False
            open_index = index
        elif char == "\u201d":
            if open_index is None:
                keep[index] = False
            else:
                open_index = None
    if open_index is not None:
        keep[open_index] = False
    return "".join(char for char, kept in zip(text, keep) if kept)


def clean_caption(text: str) -> str:
    for original, replacement in GLYPH_MAP:
        text = text.replace(original, replacement)
    text = re.sub(r"\s+([,.!?;:])", r"\1", text)
    text = re.sub(r"\s{2,}", " ", text)
    text = re.sub(r"^[\s,.;:-]+", "", text)
    text = re.sub(r"\s+-$", "", text.strip())
    return text.strip()


def caption_text(words: list[dict]) -> str:
    return clean_caption(balance_quotes(" ".join(word["text"] for word in words)))


@functools.lru_cache(maxsize=None)
def caption_font(size: int) -> ImageFont.FreeTypeFont:
    return ImageFont.truetype(str(CAPTION_FONT), size)


_MEASURE = ImageDraw.Draw(Image.new("RGBA", (8, 8)))


@functools.lru_cache(maxsize=None)
def text_width(text: str, size: int) -> int:
    left, _, right, _ = _MEASURE.textbbox((0, 0), text, font=caption_font(size))
    return right - left


def chunk_run(words: list[dict], fmt: Format) -> list[dict]:
    """Split one speaker's words into single-line captions with the cheapest breaks."""
    count = len(words)
    ends = [bool(SENTENCE_END.search(word["text"])) for word in words]
    plain = [normalize(word["text"]) for word in words]
    protected = [False] * count  # protected[i]: never break between word i and i + 1
    for phrase in KEEP_TOGETHER:
        size = len(phrase)
        for index in range(count - size + 1):
            if plain[index:index + size] == phrase:
                for inner in range(index, index + size - 1):
                    protected[inner] = True
    short_target = 0.45 * fmt.max_chars

    def break_cost(index: int) -> float:
        if ends[index]:
            return -2.0
        previous, following = words[index]["text"], words[index + 1]["text"]
        cost = 6.0
        if CLAUSE_END.search(previous):
            cost -= 6
        elif plain[index] in DETERMINERS:
            cost += 16
        elif plain[index] in GLUE:
            cost += 8
        elif previous[:1].isupper() and following[:1].isupper() and plain[index] != "i":
            cost += 6
        if plain[index + 1] in CONJUNCTIONS:
            cost -= 3
        elif plain[index + 1] in PREPOSITIONS:
            cost -= 1
        elif plain[index + 1] in NEXT_GLUE:
            cost += 8
        if protected[index]:
            cost += 20
        gap = words[index + 1]["start"] - words[index]["end"]
        if gap > 0.5:
            cost -= 8
        elif gap > 0.25:
            cost -= 3
        return cost

    def chunk_cost(first: int, stop: int) -> Optional[float]:
        interior = sum(ends[first:stop - 1])
        if interior and not (ends[stop - 1] and (first == 0 or ends[first - 1])):
            return None
        text = caption_text(words[first:stop])
        if stop - first > 1 and (len(text) > fmt.max_chars or text_width(text, fmt.font_size) > fmt.max_width):
            return None
        cost = 10.0 + 4 * interior
        if len(text) < fmt.short_chars:
            cost += 10
        if len(text) < short_target:
            cost += (short_target - len(text)) * 0.15
        if stop - first == 1:
            cost += 15
        if len(QUOTE_MARKS.findall(" ".join(word["text"] for word in words[first:stop]))) % 2:
            cost += 3  # prefer breaks that keep a quotation on one line
        duration = words[stop - 1]["end"] - words[first]["start"]
        if duration > 3.4:
            cost += (duration - 3.4) * 4
        elif duration < 0.6:
            cost += (0.6 - duration) * 10  # discourage captions that only flash
        return cost

    best = [math.inf] * (count + 1)
    best[0] = 0.0
    back = [0] * (count + 1)
    for stop in range(1, count + 1):
        for first in range(stop - 1, max(-1, stop - 1 - fmt.max_words), -1):
            cost = chunk_cost(first, stop)
            if cost is None:
                continue
            total = best[first] + cost + (break_cost(stop - 1) if stop < count else 0.0)
            if total < best[stop]:
                best[stop], back[stop] = total, first

    spans: list[tuple[int, int]] = []
    stop = count
    while stop > 0:
        spans.append((back[stop], stop))
        stop = back[stop]
    return [
        {
            "start": words[first]["start"],
            "end": words[stop - 1]["end"],
            "text": caption_text(words[first:stop]),
            "speaker": words[first]["speaker"],
            "words": words[first:stop],
        }
        for first, stop in reversed(spans)
    ]


def time_events(chunks: list[dict], clip_start: float, duration: float) -> list[dict]:
    """Give every caption a readable slot, delaying a reply that talks over the last line."""
    events: list[dict] = []
    previous: Optional[dict] = None
    for chunk in chunks:
        natural = chunk["start"] - clip_start
        speech_end = chunk["end"] - clip_start
        delayed = previous is not None and natural < previous["protect"]
        if delayed:
            start = previous["protect"] + 0.04
            previous["end"] = previous["protect"]
        else:
            start = max(0.0, natural)
            if previous is not None:
                previous["end"] = min(previous["end"], max(previous["protect"], start - 0.04))
        protect = max(start + 0.35, speech_end - 0.04)
        if delayed:
            # A late caption still gets enough time on screen to be read.
            protect = max(protect, start + min(1.5, max(0.6, len(chunk["text"]) / 28)))
        crosstalk = delayed and previous is not None and previous["speaker"] != chunk["speaker"]
        if crosstalk:
            protect = max(protect, start + 1.0)
        end = max(speech_end + 0.12, protect) if delayed else speech_end + 0.12
        event = {"start": start, "end": end, "protect": protect, "text": chunk["text"], "speaker": chunk["speaker"]}
        events.append(event)
        previous = event
    for event in events:
        event["start"] = min(event["start"], duration)
        event["end"] = min(max(event["end"], event["start"]), duration)
        del event["protect"]
    return events


def caption_events(words: list[dict], clip: Clip, duration: float, fmt: Format) -> list[dict]:
    def chunk(run: list[dict]) -> list[dict]:
        if fmt.nest_in is None:
            return chunk_run(run, fmt)
        return [piece for line in chunk_run(run, FORMATS[fmt.nest_in]) for piece in chunk_run(line["words"], fmt)]

    chunks: list[dict] = []
    run: list[dict] = []
    for word in words:
        if run and word["speaker"] != run[-1]["speaker"]:
            chunks.extend(chunk(run))
            run = []
        run.append(word)
    if run:
        chunks.extend(chunk(run))
    return time_events(chunks, clip.start, duration)


class Captioner:
    def __init__(self, fmt: Format) -> None:
        self.fmt = fmt
        self.font = caption_font(fmt.font_size)
        self.notdef = self._mask("\u2014")

    def _mask(self, char: str) -> bytes:
        image = Image.new("L", (self.fmt.font_size * 2, self.fmt.font_size * 2), 0)
        ImageDraw.Draw(image).text((4, 4), char, font=self.font, fill=255)
        return image.tobytes()

    def check_glyphs(self, text: str) -> None:
        for char in set(text):
            if char.isspace() or ord(char) < 128 and char.isalnum():
                continue
            if self._mask(char) == self.notdef:
                raise ValueError(f"Caption font has no glyph for {char!r} in {text!r}")

    def wrap(self, draw: ImageDraw.ImageDraw, text: str) -> str:
        lines: list[str] = []
        current = ""
        for word in text.split():
            candidate = f"{current} {word}".strip()
            left, _, right, _ = draw.textbbox((0, 0), candidate, font=self.font)
            if current and right - left > self.fmt.max_width:
                lines.append(current)
                current = word
            else:
                current = candidate
        if current:
            lines.append(current)
        return "\n".join(lines)

    def render(self, path: Path, caption: Optional[str] = None) -> int:
        fmt = self.fmt
        image = Image.new("RGBA", (fmt.width, fmt.height), (0, 0, 0, 0))
        if not caption:
            image.save(path, optimize=True)
            return 0

        self.check_glyphs(caption)
        measure = ImageDraw.Draw(image)
        wrapped = self.wrap(measure, caption)
        bbox = measure.multiline_textbbox((0, 0), wrapped, font=self.font, spacing=fmt.spacing, align="center")
        text_width_px = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        center_x = fmt.center_x if fmt.center_x is not None else fmt.width / 2
        text_x = center_x - text_width_px / 2 - bbox[0]
        text_y = fmt.center_y - text_height / 2 - bbox[1]

        shadow = Image.new("RGBA", image.size, (0, 0, 0, 0))
        ImageDraw.Draw(shadow).multiline_text(
            (text_x + fmt.shadow_offset[0], text_y + fmt.shadow_offset[1]),
            wrapped,
            font=self.font,
            fill=(0, 0, 0, 220),
            spacing=fmt.spacing,
            align="center",
        )
        image.alpha_composite(shadow.filter(ImageFilter.GaussianBlur(radius=3)))
        ImageDraw.Draw(image).multiline_text(
            (text_x, text_y),
            wrapped,
            font=self.font,
            fill=(255, 255, 255, 255),
            spacing=fmt.spacing,
            align="center",
            stroke_width=1,
            stroke_fill=(0, 0, 0, 180),
        )
        image.save(path, optimize=True)
        return wrapped.count("\n") + 1


def write_caption_timeline(events: list[dict], duration: float, fmt: Format, graphics_dir: Path, timeline_path: Path) -> int:
    graphics_dir.mkdir(parents=True, exist_ok=True)
    for stale in graphics_dir.glob("*.png"):
        stale.unlink()
    captioner = Captioner(fmt)
    base_path = graphics_dir / "base.png"
    captioner.render(base_path)

    max_lines = 0
    caption_paths: list[Path] = []
    for index, event in enumerate(events):
        caption_path = graphics_dir / f"caption-{index:03d}.png"
        max_lines = max(max_lines, captioner.render(caption_path, event["text"]))
        caption_paths.append(caption_path)

    entries: list[tuple[Path, float]] = []
    cursor = 0.0
    for event, caption_path in zip(events, caption_paths):
        event_start = max(cursor, min(duration, event["start"]))
        event_end = max(event_start, min(duration, event["end"]))
        if event_start - cursor > 0.01:
            entries.append((base_path, event_start - cursor))
        if event_end - event_start > 0.01:
            entries.append((caption_path, event_end - event_start))
        cursor = event_end
    if duration - cursor > 0.01:
        entries.append((base_path, duration - cursor))
    if not entries:
        entries.append((base_path, duration))

    lines = ["ffconcat version 1.0\n"]
    for image_path, entry_duration in entries:
        lines.append(f"file '{image_path}'\n")
        lines.append(f"duration {entry_duration:.6f}\n")
    lines.append(f"file '{entries[-1][0]}'\n")
    timeline_path.parent.mkdir(parents=True, exist_ok=True)
    timeline_path.write_text("".join(lines), encoding="utf-8")
    return max_lines


def crop_switches(events: list[dict]) -> list[tuple[float, str]]:
    """The 9:16 crop follows the captions, so the face on screen matches the words."""
    switches: list[tuple[float, str]] = []
    for event in events:
        if not switches or switches[-1][1] != event["speaker"]:
            switches.append((event["start"], event["speaker"]))
    if switches:
        switches[0] = (0.0, switches[0][1])
    return switches


def crop_expression(clip: Clip, events: list[dict]) -> str:
    if len(clip.crop_x) == 1:
        return str(next(iter(clip.crop_x.values())))
    switches = crop_switches(events)
    expression = str(clip.crop_x[switches[0][1]])
    for switch_time, speaker in switches[1:]:
        expression = f"if(gte(t,{switch_time:.3f}),{clip.crop_x[speaker]},{expression})"
    return expression


def build_filter(clip: Clip, fmt: Format, duration: float, crop: Optional[str]) -> str:
    if fmt is VERTICAL:
        video = (
            "[0:v]fps=30,setpts=PTS-STARTPTS,"
            f"crop={CROP_W}:{SOURCE_H}:x='{crop}':y=0,"
            f"scale={fmt.width}:{fmt.height}:flags=lanczos[video]"
        )
    else:
        video = f"[0:v]fps=30,setpts=PTS-STARTPTS,scale={fmt.width}:{fmt.height}:flags=lanczos[video]"
    fade_out_start = max(0.0, duration - clip.fade_out)
    return ";".join(
        [
            video,
            "[1:v]format=rgba,setpts=PTS-STARTPTS[captions]",
            (
                "[video][captions]overlay=x=0:y=0:eof_action=repeat:shortest=0,"
                f"trim=duration={duration:.3f},setpts=PTS-STARTPTS,format=yuv420p[vout]"
            ),
            (
                f"[0:a]atrim=duration={duration:.3f},asetpts=PTS-STARTPTS,"
                "loudnorm=I=-16:LRA=11:TP=-1.5,aresample=48000,"
                f"afade=t=in:st=0:d={clip.fade_in:.3f},"
                f"afade=t=out:st={fade_out_start:.3f}:d={clip.fade_out:.3f}[aout]"
            ),
        ]
    )


def plan_clip(clip: Clip, fmt: Format, tokens: list[dict], sample_seconds: Optional[float] = None) -> tuple[float, list[dict]]:
    duration = min(clip.duration, sample_seconds) if sample_seconds else clip.duration
    words = caption_words(tokens, clip, clip.start + duration if sample_seconds else None)
    return duration, caption_events(words, clip, duration, fmt)


def render_clip(clip: Clip, fmt: Format, tokens: list[dict], output_dir: Path, sample_seconds: Optional[float] = None) -> Path:
    duration, events = plan_clip(clip, fmt, tokens, sample_seconds)
    graphics_dir = WORK_ROOT / fmt.key / clip.slug
    timeline_path = WORK_ROOT / fmt.key / f"{clip.slug}.ffconcat"
    max_lines = write_caption_timeline(events, duration, fmt, graphics_dir, timeline_path)
    crop = crop_expression(clip, events) if fmt is VERTICAL else None

    output_dir.mkdir(parents=True, exist_ok=True)
    suffix = "-sample" if sample_seconds else ""
    output = output_dir / f"{clip.slug}-{fmt.suffix}{suffix}.mp4"
    bitrate, maxrate, bufsize = fmt.bitrate
    command = [
        "ffmpeg", "-y", "-hide_banner", "-loglevel", "warning", "-stats",
        "-hwaccel", "videotoolbox",
        "-ss", f"{clip.start:.3f}", "-t", f"{duration:.3f}", "-i", str(SOURCE),
        "-f", "concat", "-safe", "0", "-i", str(timeline_path),
        "-filter_complex", build_filter(clip, fmt, duration, crop),
        "-map", "[vout]", "-map", "[aout]",
        "-c:v", "h264_videotoolbox", "-b:v", bitrate, "-maxrate", maxrate, "-bufsize", bufsize,
        "-tag:v", "avc1", "-r", "30",
        "-c:a", "aac", "-b:a", "192k",
        "-movflags", "+faststart",
        "-metadata", f"title={clip.title}",
        "-t", f"{duration:.3f}",
        str(output),
    ]
    print(f"Rendering {output.name} ({duration:.2f}s, {len(events)} captions, max {max_lines} lines, crop {crop})")
    subprocess.run(command, check=True)
    return output


def list_events(clip: Clip, fmt: Format, tokens: list[dict]) -> None:
    duration, events = plan_clip(clip, fmt, tokens)
    print(f"\n== {clip.slug} [{fmt.key}] {duration:.2f}s, {len(events)} captions")
    if fmt is VERTICAL and len(clip.crop_x) > 1:
        print("   crop:", ", ".join(f"{time:.2f} {speaker}" for time, speaker in crop_switches(events)))
    previous_speaker = None
    for event in events:
        marker = "*" if event["speaker"] != previous_speaker else " "
        previous_speaker = event["speaker"]
        width = text_width(event["text"], fmt.font_size)
        print(
            f" {marker}{event['start']:6.2f}-{event['end']:6.2f} ({event['end'] - event['start']:4.2f}s "
            f"{len(event['text']):2d}c {width:4d}px)  {event['text']}"
        )


def timecode(seconds: float) -> str:
    hours, rest = divmod(seconds, 3600)
    minutes, secs = divmod(rest, 60)
    if hours:
        return f"{int(hours)}:{int(minutes):02d}:{secs:05.2f}"
    return f"{int(minutes)}:{secs:05.2f}"


def write_manifest(output_dir: Path) -> Path:
    manifest = {
        "source": str(SOURCE),
        "formats": {
            "landscape-16x9": {
                "dimensions": "1920x1080",
                "aspect_ratio": "16:9",
                "platforms": ["LinkedIn", "X", "YouTube"],
                "layout": "Full interview frame",
                "captions": "Embedded Born2bSportyV10 at 60 px with a soft drop shadow",
            },
            "vertical-9x16": {
                "dimensions": "1080x1920",
                "aspect_ratio": "9:16",
                "platforms": ["TikTok", "YouTube Shorts", "Instagram Reels"],
                "layout": "Speaker-focused crop of the interview frame",
                "captions": "Embedded Born2bSportyV10 at 66 px with a soft drop shadow",
            },
        },
        "clips": [
            {
                "slug": clip.slug,
                "title": clip.title,
                "files": [f"{clip.slug}-{fmt.suffix}.mp4" for fmt in (LANDSCAPE, VERTICAL)],
                "source_start_seconds": round(clip.start, 2),
                "source_end_seconds": round(clip.end, 2),
                "source_timecode": f"{timecode(clip.start)}-{timecode(clip.end)}",
                "duration_seconds": round(clip.duration, 2),
                "post_hook": clip.post_hook,
            }
            for clip in CLIPS
        ],
    }
    path = output_dir / "manifest.json"
    path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    return path


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--only", nargs="*", help="Clip slugs or numeric prefixes to render")
    parser.add_argument("--formats", nargs="*", choices=sorted(FORMATS), default=sorted(FORMATS))
    parser.add_argument("--sample-seconds", type=float)
    parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
    parser.add_argument("--list", action="store_true", help="Print caption events without rendering")
    parser.add_argument("--manifest", action="store_true", help="Write manifest.json only")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    tokens = load_tokens()
    clips = [
        clip
        for clip in CLIPS
        if not args.only or any(clip.slug == key or clip.slug.startswith(f"{key}-") for key in args.only)
    ]
    if args.manifest:
        print(write_manifest(args.output_dir))
        return
    for clip in clips:
        for key in args.formats:
            if args.list:
                list_events(clip, FORMATS[key], tokens)
            else:
                render_clip(clip, FORMATS[key], tokens, args.output_dir, args.sample_seconds)


if __name__ == "__main__":
    main()
