#!/usr/bin/env python3
"""select_cut.py — choose a clip per window, refuse a cut that cannot be right.

This replaces the glob the `cut` stage used to select B-roll with
(`ls "$P/outputs/"*"$sid"*.mp4` — which, incidentally, cannot match what
`brs-render-film.sh` actually writes). Selection happens in three deliberate layers:

  * the window PLAN is derived from the transcript — deterministic, no judgement;
  * the window -> clip ASSIGNMENT is authored, by an agent reading the contact-strip
    gallery or by an operator editing the same file by hand;
  * this script VALIDATES and refuses, `check_sync.py` MEASURES, and the runner's
    re-run is the operator's approval.

Two things it exists to make impossible:

**A clip on the wrong bar.** `synced` is CARRIED, never inferred from a picture — a
contact strip can show that a mouth is open, not that it is open to the right words.
It comes from an explicit override, a flag, or render provenance, and every window
records which (`syncedBy`) so the decision is auditable.

**A cut the assembler will quietly mangle.** `vocal-sync-plan.ts` seeks a performer
clip to time-WITHIN-SECTION, so this emits an explicit `vocalMap` with one section per
window, each carrying its own `performerClip` — the section boundary and the clip's
zero then coincide, which is the only arrangement where the mouth lands on its own
words. `--verify-plan` then re-reads the assembler's real plan and refuses if it stops
matching, because that pinning depends on planner internals (see `cutLengths` below).

Usage:
  select_cut.py --project P --style SID --index … --hook-json … --transcript …
                [--assign build/cut-SID.json] [--auto] --out-selection … --out-manifest …
  select_cut.py --verify-plan --config build/mv-SID.json [--selection …]
Exit 0 ok · 2 bad input · 4 REFUSED (unapplicable cut) · 5 plan mismatch · 6 no assignment
"""
from __future__ import annotations

import argparse
import html
import json
import math
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
import raplib  # noqa: E402
from make_plan import max_clip_for  # noqa: E402
import os
import re
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lane_nav import inject_nav  # noqa: E402
from lane_page import page as shell  # noqa: E402

# Every third cut is forced to B-roll even with a performerClip pinned
# (`vocal-sync-plan.ts`: `if (sec.performerClip && cutIdx % 3 !== 2)`). Setting the cut
# length longer than any window makes the first cut clip to the section boundary, so
# each window yields exactly one cut and the quirk never fires. It is a dependency on
# planner internals, which is why --verify-plan is not optional.
CUT_ROLES = ("rap", "hook", "instrumental", "outro")
LABEL_RE = re.compile(r"^cut (\d+) (performer|b-roll) (\S+) @([\d.]+)s ×([\d.]+)s$")


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


def refuse(problems: list[str]) -> None:
    print("select_cut: REFUSED — this cut is not applicable:", file=sys.stderr)
    for p in problems:
        print(f"  {p}", file=sys.stderr)
    print("  nothing was written.", file=sys.stderr)
    raise SystemExit(4)


def derive_windows(transcript: str, hook: dict, fps: int,
                   lo: float, hi: float) -> list[dict]:
    """Slice the transcript to the hook, rebase to zero, and walk it into windows.

    Boundaries snap to whole frames because the picture must cover the vocal exactly;
    a sub-frame boundary is where drift starts."""
    start, end = float(hook["start"]), float(hook["end"])
    raw = json.load(open(transcript, encoding="utf-8"))
    segs = raw.get("segments") if isinstance(raw, dict) else raw
    spans = []
    for s in segs or []:
        a, b = float(s["start"]), float(s["end"])
        if b <= start or a >= end:
            continue
        spans.append((max(a, start) - start, min(b, end) - start,
                      str(s.get("text", "")).strip()))
    if not spans:
        die("no transcript segments fall inside the hook window — the hook.json and "
            "the transcript are not from the same song")
    spans.sort()

    total = end - start
    wins, cur_a, cur_b, texts = [], spans[0][0], spans[0][1], [spans[0][2]]
    for a, b, t in spans[1:]:
        if (b - cur_a) > hi and (cur_b - cur_a) >= lo:
            wins.append((cur_a, cur_b, " ".join(texts)))
            cur_a, cur_b, texts = a, b, [t]
        else:
            cur_b, texts = b, texts + [t]
    wins.append((cur_a, cur_b, " ".join(texts)))

    # `hi` was only a SPLIT THRESHOLD: the walk above stops merging once a window
    # would exceed it, but a single transcript segment longer than `hi` is never
    # split at all. A 10.3s ad-lib intro therefore produced a 10.3s window that no
    # 10.1s clip could cover, and the cut was unsatisfiable no matter how the clips
    # were assigned. Make the maximum an actual maximum by cutting any over-long
    # span into equal parts.
    split = []
    for a, b, t in wins:
        n = max(1, math.ceil((b - a) / hi - 1e-9))
        step = (b - a) / n
        for k in range(n):
            split.append((a + k * step, a + (k + 1) * step, t if k == 0 else ""))
    wins = split

    out, prev_end = [], 0.0
    for i, (a, b, t) in enumerate(wins):
        s0 = 0.0 if i == 0 else prev_end
        e0 = total if i == len(wins) - 1 else b
        sf, ef = round(s0 * fps), round(e0 * fps)
        if ef - sf < 1:
            continue
        out.append({
            "i": len(out), "start": round(sf / fps, 6), "end": round(ef / fps, 6),
            "seconds": round((ef - sf) / fps, 6), "text": t,
            # `type` is CADENCE CONTROL, not semantics: alternating it resets the
            # planner's cutIdx at every section, which is half of the one-cut-per-
            # window guarantee. Do not "fix" these into real section types.
            "type": "rap" if len(out) % 2 == 0 else "hook",
            "adlib": False,
        })
        prev_end = round(ef / fps, 6)
    if not out:
        die("the transcript produced no usable window")

    # Split AFTER rebasing, not before. The loop above sets each window's start to
    # the previous window's end so the plan tiles the song with no gaps — which means
    # a window ABSORBS any silence before it and can grow back over the cap that was
    # applied earlier. A 10.12s window (10.0s of speech plus a 0.12s gap) then had no
    # clip long enough to cover it. This is the pass that makes `hi` binding.
    final, idx = [], 0
    for w in out:
        n = max(1, math.ceil(w["seconds"] / hi - 1e-9))
        if n == 1:
            final.append({**w, "i": idx}); idx += 1
            continue
        sf, ef = round(w["start"] * fps), round(w["end"] * fps)
        edges = [round(sf + (ef - sf) * k / n) for k in range(n + 1)]
        for k in range(n):
            final.append({
                "i": idx, "start": round(edges[k] / fps, 6),
                "end": round(edges[k + 1] / fps, 6),
                "seconds": round((edges[k + 1] - edges[k]) / fps, 6),
                "text": w["text"] if k == 0 else "",
                "type": "rap" if idx % 2 == 0 else "hook",
                "adlib": w.get("adlib", False),
            })
            idx += 1
    return final


def load_index(path: str) -> dict:
    if not os.path.isfile(path):
        die(f"no library index at {path} — run index_library.py first")
    doc = json.load(open(path, encoding="utf-8"))
    return {c["id"]: c for c in doc.get("clips", [])}


GAP_SECTION_MIN_S = 0.9   # mirrors plan_coherence #3: a hole this long is a B-roll section
TAIL_TRIM_MAX_FRAMES = 6  # mirrors check_master plan-covers-hook: a plan may stop this many frames short


def pool_clips(index: dict, chosen_ids: set[str], cut_len: float) -> list[dict]:
    """Real B-roll for the pool — never a performance take.

    THE DEFECT THIS FIXES was structural and hit every film with an instrumental
    stretch. A shot-led window is deliberately left unpinned (see load_shot_led), and
    the assembler then fills it from the B-roll POOL. The pool was built as
    `{role: [clips[0]["id"]]}` over a list that holds only PERFORMER clips — so every
    instrumental window got a lip-synced take with its in-point stepped to an arbitrary
    offset: a man mouthing words the song is not singing, which is precisely what the
    `cover` stage exists to prevent, arriving through the assembler's back door.

    Two hard requirements, both learned the expensive way:

      NOT A PINNED PERFORMER. That is the defect above.
      LONGER THAN THE CUT + 0.2s. `emitBroll` steps a pool clip's in-point so a repeat
      does not replay identically, reserving 0.05s in and 0.15s tail. A lane that
      renders everything at one length cannot fill its own cuts, and the failure
      surfaces deep inside the assembler naming a clip but not a fix.

    Returns [] when nothing qualifies; the caller keeps the old non-empty-pool
    behaviour and says so, because an EMPTY pool makes the planner silently SKIP a cut
    and missing film is harder to spot than a wrong clip.
    """
    need = cut_len + 0.2
    out = []
    for cid, c in sorted(index.items()):
        if cid in chosen_ids:
            continue
        origin = str(c.get("origin", "")).lower()
        if "broll" not in origin:
            continue
        # NEVER AUTO-FILL FROM A PARKED CLIP. Parked = an operator or a gate rejected it;
        # the pool is the one path that puts a clip on screen without anyone naming it.
        # (COVER_PINS still pins a parked clip on purpose — that is a named choice.)
        if "parked" in origin or f"{os.sep}superseded{os.sep}" in str(c.get("clip", "")):
            continue
        if float(c.get("seconds") or 0) < need:
            continue
        out.append(c)
    return out


def _open_gap(out: list[dict], a_f: int, b_f: int, fps: int, sid, cap: float | None, outro: bool = False) -> None:
    """Append the gap section(s) for frames a_f..b_f — one, or raplib.gap_pieces of them
    when the hole outruns what one capped cutaway can fill. Frame-exact: the pieces
    tile the hole with whole frames, the first ones a frame longer when it does not
    divide."""
    n = raplib.gap_pieces((b_f - a_f) / fps, cap) if cap else 1
    base, extra = (b_f - a_f) // n, (b_f - a_f) % n
    f0 = a_f
    for k in range(n):
        f1 = f0 + base + (1 if k < extra else 0)
        sec = {
            "i": len(out), "start": round(f0 / fps, 6), "end": round(f1 / fps, 6),
            "seconds": round((f1 - f0) / fps, 6),
            "text": "instrumental outro" if outro else "instrumental gap",
            "type": "rap" if len(out) % 2 == 0 else "hook", "adlib": True,
            "planId": None, "gap": True, "planNoVoice": True, "planVocalMode": "no-voice",
            "styleId": sid,
        }
        if outro:
            sec["outro"] = True
        if n > 1:
            sec["piece"] = f"{k + 1}/{n}"
        out.append(sec)
        f0 = f1


def fill_gaps(windows: list[dict], index: dict, rows: list[dict]) -> list[dict]:
    """Pin a cutaway SLICE to every gap section that has no row.

    GAP SECTIONS TAKE A CUTAWAY. A window the plan never rendered (a hole between
    sung-length windows, or the outro after the last) has no row in cut-<style>.json;
    it takes B-roll — never a performer take (pool_clips' rule).

    A FRESH SLICE, NOT A WHOLE CLIP. This used to consume one whole cutaway per gap
    while the B-roll plan makes one cutaway per WORLD — so the first film with more gaps
    than worlds (seven and six, the duet fixture, 2026-09-02) failed here after every
    render had landed. A 16 s cutaway is footage for several holes: each gap takes the
    next unused stretch of a clip (its in-point rides as the section's headSec, which
    the assembler honours), so nothing is shown twice and a world's cutaway serves that
    world's gaps. The gap's own world is preferred when the index names one; then the
    clip with the most footage left. Returns the rows it added."""
    assigned = {int(r.get("window")) for r in rows if r.get("window") is not None}
    cursor: dict[str, float] = {}
    added: list[dict] = []
    for w in windows:
        if not w.get("gap") or w["i"] in assigned:
            continue
        need = float(w["seconds"]) + 0.2
        left = lambda c: float(c.get("seconds") or 0) - cursor.get(c["id"], 0.0)  # noqa: E731
        fit = [c for c in pool_clips(index, set(), 0.0) if left(c) >= need]
        own = [c for c in fit if w.get("styleId") and c.get("styleId") == w.get("styleId")]
        cands = sorted(own or fit, key=lambda c: -left(c))
        if not cands:
            die(f"w{w['i']:02d}: an instrumental gap of {w['seconds']:.2f}s at {w['start']:.2f}s has no "
                f"B-roll footage left to fill it — the pool's cutaways are used up. Re-run the "
                f"broll-plan stage (make_broll_plan sizes the pool from the plan's holes) or render "
                f"the deferred cutaways (lane_render --plan build/broll-plan.json --only bNN)", 6)
        c = cands[0]
        off = round(cursor.get(c["id"], 0.0), 3)
        w["headSec"] = off                    # the slice's in-point; the section carries it
        row = {"window": w["i"], "clipId": c["id"], "headSec": off}
        rows.append(row)
        added.append(row)
        cursor[c["id"]] = off + float(w["seconds"])
        print(f"select_cut: w{w['i']:02d} is an instrumental {'outro' if w.get('outro') else 'gap'} "
              f"({w['seconds']:.2f}s) — {c['id']} from {off:.2f}s of the B-roll pool", file=sys.stderr)
    return added


def load_shot_led(path: str) -> set[int]:
    """Windows the measurement says have no vocal to sync to.

    `vocal_map.py` writes these. A window over an instrumental cannot earn a sync
    score and must not be judged on one — and pinning a performer clip to it is
    what put a man mouthing words the song was not singing into three places in
    the last film.
    """
    if not path or not os.path.isfile(path):
        return set()
    try:
        doc = json.load(open(path, encoding="utf-8"))
    except Exception:
        return set()
    return {int(w["window"]) for w in doc.get("windows", [])
            if w.get("shotLed") and w.get("window") is not None}


def windows_from_plan(plan_path: str, fps: int, song_end: float | None = None) -> list[dict]:
    """Windows taken from the render plan itself — the only source whose provenance survives.

    `make_plan.py` lays the grid, cuts one voice reference per window from it, and
    every clip is rendered against that grid. Re-deriving windows from the
    transcript afterwards produces a DIFFERENT set of boundaries, so window 10 is
    a different stretch of song than the one the clip was rendered for, and
    `resolve_synced` correctly refuses every provenance claim as `plan-rederived`.
    That is what happened on Great Indian Summer: nothing could claim sync, so
    nothing was gated on it, and clips ended up on the wrong bars.

    Reading the plan back closes the loop. The grid that produced the clips is the
    grid they are cut to.
    """
    doc = json.load(open(plan_path, encoding="utf-8"))
    jobs = sorted(doc.get("jobs", []), key=lambda j: int(j.get("window", 0)))
    if not jobs:
        die(f"{plan_path} has no jobs — it is not a render plan")

    # a hole longer than one cutaway can hold (the route's unsynced cap) opens as
    # several sections, each a slice one clip CAN fill — the same split the B-roll
    # plan and plan_coherence #6b size the pool by (raplib.gap_pieces)
    try:
        cap = float(max_clip_for(str(doc.get("route") or ""), synced=False))
    except Exception:
        cap = None
    out, prev_end, prev_sid = [], None, None
    for j in jobs:
        # `startSec` is where the CLIP's zero sits, which is not where the window
        # sits: `trimStartSec` is how much the assembly skips off the front, and
        # make_plan slides the final window back by exactly that much so it still
        # fits the song. The timeline position is therefore startSec + trim, and
        # the covered duration is seconds - trim. Reading startSec as the window
        # start makes the last two windows overlap by 5.5s.
        trim = float(j.get("trimStartSec", 0.0) or 0.0)
        tail = float(j.get("tailSec", 0.0) or 0.0)
        s0 = float(j.get("startSec", 0.0)) + trim
        # `tailSec` is render slack AFTER the window (make_plan --slack-tail): the
        # clip keeps going past the window so `slide` can advance a late take with
        # real frames instead of a held one. Not part of the covered duration.
        dur = float(j.get("seconds", 0.0)) - trim - tail
        if dur <= 0:
            die(f"plan job {j.get('id')} has no covered duration "
                f"(seconds={j.get('seconds')}, trimStartSec={trim})")
        # Snap to whole frames for the same reason derive_windows does: a sub-frame
        # boundary is where drift starts.
        sf, ef = round(s0 * fps), round((s0 + dur) * fps)
        if prev_end is None and sf > 0:
            # THE FILM STARTS AT ZERO, AND SO MUST THE MAP. The first window opens on its
            # first word (exact onsets), which on film #3 sat at 0.6 s; the loop below only
            # opens holes BETWEEN windows, so the map began at 0.583 and the assembler
            # refused it three stages later ("first section starts at 0.583333, expected
            # 0", 2026-09-06). A leading hole is an instrumental gap like any other — the
            # song's intro before the first word.
            #
            # BUT NOT WHEN THE TAKE ALREADY REACHES BACK OVER IT. make_plan pads the
            # render with head silence before the first word (`startSec = word position -
            # head`), and on a short lead-in that pad does not quite reach song-zero: on
            # film #3 (2026-09-07) w00's take started at song 0.10s, 0.48s of pad short of
            # its 0.58s first word — and this loop, unconditional on length, cut away to a
            # 0.58s B-roll sliver in front of a take that already had the picture. When the
            # hole is under GAP_SECTION_MIN_S AND the take's own render already starts at
            # or near song-zero (within TAIL_TRIM_MAX_FRAMES — the same few-frame slop the
            # outro remainder already tolerates), show the take from its own head instead:
            # widen the window to start at 0.0 and stop trimming the head pad. A slip of a
            # few frames at the very front is the same tolerance the outro remainder gets,
            # and it beats cutting to B-roll for content the take already covers.
            hole_s = sf / fps
            take_start = float(j.get("startSec", 0.0) or 0.0)
            if hole_s < GAP_SECTION_MIN_S and take_start <= TAIL_TRIM_MAX_FRAMES / fps + 1e-9:
                sf, trim = 0, 0.0
            else:
                _open_gap(out, 0, sf, fps, j.get("styleId") or j.get("style"), cap)
                prev_end = sf
        if prev_end is not None and sf > prev_end and (sf - prev_end) / fps >= GAP_SECTION_MIN_S:
            # A HOLE BETWEEN SUNG WINDOWS IS A B-ROLL SECTION. Sung-length renders
            # (2026-08-31) leave the instrumental between lines out of the performance
            # clip on purpose; the assembler fills an unpinned instrumental section from
            # the pool, and build() assigns it a cutaway below.
            _open_gap(out, prev_end, sf, fps, prev_sid, cap)   # the hole belongs to the world before it
            prev_end = sf
        if prev_end is not None and sf != prev_end:
            die(f"plan windows do not tile: {j.get('id')} starts at frame {sf}, "
                f"previous ended at {prev_end}. The picture must cover the vocal "
                "with no gap and no overlap.")
        out.append({
            "i": len(out), "start": round(sf / fps, 6), "end": round(ef / fps, 6),
            # The plan's own window number. Provenance records THAT (lane_render
            # renders plan job N against plan window N); this grid's `i` counts the
            # instrumental-gap sections too, so past the first gap they differ by one
            # and every later take read as unsynced (New Era, 2026-08-31).
            "planWindow": int(j.get("window", len(out))),
            "seconds": round((ef - sf) / fps, 6),
            "text": str(j.get("section", "") or "").strip(),
            # Same cadence-control alternation as derive_windows — resets the
            # planner's cutIdx per window, which is half the one-cut-per-window
            # guarantee. Not a semantic label.
            "type": "rap" if len(out) % 2 == 0 else "hook",
            "adlib": not bool(j.get("synced", True)),
            "planId": j.get("id"),
            # SOURCE SLACK around the window, for `slide`: the clip's frame 0 sits
            # headSec BEFORE the window (the assembly must skip it — the last window's
            # trim was recorded here for weeks and honoured by nothing, so its clip
            # ran 0.5s early), and tailSec of clip remains after the window's end.
            "headSec": round(trim, 3), "tailSec": round(tail, 3),
            # THE PLAN KNOWS WHICH WINDOWS WERE SENT WITHOUT A VOICE. A job with no
            # voiceRef (or synced:false) rendered a closed-mouth shot against no audio;
            # it can never earn a sync score and must not be judged on one. Carried
            # here so the selection pins it exempt BY CONSTRUCTION (see build()).
            "planNoVoice": not j.get("voiceRef") or j.get("synced") is False,
            "voiceRef": j.get("voiceRef") or "",
            # The lines this window sings, for any gate that has to whisper it: an
            # unprimed ear pairs 6 of 14 words and fits a rate off by 0.2 (New Era w07,
            # 2026-08-30). Same string the driver's judge uses.
            "lines": ". ".join(sp.get("text", "").strip()
                               for sp in ((j.get("vocal") or {}).get("spans") or [])
                               if sp.get("text"))[:700],
            "planVocalMode": (j.get("vocal") or {}).get("mode"),
            "styleId": j.get("styleId"),
        })
        prev_end, prev_sid = ef, j.get("styleId")
    # THE OUTRO IS A SECTION TOO. The loop above opens a B-roll section only BETWEEN
    # windows, so a song that plays on after its last sung line ended the film at the
    # last window — and check_master refused the master twenty stages later
    # (plan-covers-hook: planned 67.8s vs hook 70.8s, the duet fixture, 2026-09-02).
    # make_plan leaves whatever follows the last word by GAP_TO_BROLL_S or more to
    # B-roll on purpose; it is opened here like any other hole. Under a second it
    # should have been absorbed into the last render, so that is a plan defect, not a
    # gap to fill; a few frames is the cut cadence's tail trim and is left alone.
    if song_end is not None and prev_end is not None:
        end_f = round(float(song_end) * fps)
        rem = (end_f - prev_end) / fps
        if rem >= GAP_SECTION_MIN_S:
            _open_gap(out, prev_end, end_f, fps, prev_sid, cap, outro=True)
        elif rem > TAIL_TRIM_MAX_FRAMES / fps + 1e-9:
            die(f"the plan ends at {prev_end / fps:.2f}s but the hook runs to {float(song_end):.2f}s — "
                f"{rem:.2f}s of the film has no picture, too short for a cutaway (under "
                f"{GAP_SECTION_MIN_S:g}s). make_plan absorbs a remainder that short into the last "
                f"render; re-run the plan stage.")
    return out


def resolve_synced(win: dict, a: dict, clip: dict, forced: set[int],
                   plan_is_original: bool) -> tuple[bool, str]:
    """Highest-priority source wins, and the source is recorded.

    Provenance is the only automatic route: the clip must have been rendered FOR this
    window, against a voice reference, and have come back with audio. `hasAudio` is
    load-bearing — a batch submitted with the provider's audio off returns silent
    clips that correlate at ~0, and this is where that surfaces as a decision rather
    than as a mystery two hours later."""
    if "synced" in a:
        return bool(a["synced"]), "operator"
    if win["i"] in forced:
        return True, "flag"
    # Provenance records the window INDEX the clip was rendered against. That index
    # only means anything under the SAME window plan — re-derive the plan and window
    # 10 is a different stretch of song, so the clip's mouth is on the wrong bar while
    # provenance still cheerfully claims it is synced. (check_sync caught exactly this
    # on the first end-to-end run; this stops it being claimed in the first place.)
    if not plan_is_original:
        return False, "plan-rederived"
    if (clip.get("window") == win.get("planWindow", win["i"]) and clip.get("voiceRef")
            and clip.get("hasAudio")):
        return True, "provenance"
    return False, "default"


def resolve_lip_sync_exempt(a: dict, synced: bool) -> bool:
    """Carry an intentional editorial exemption from the authored cut.

    An exemption is not a weaker sync claim. It is an explicit statement that the
    assigned clip is visual montage coverage and must therefore also be explicitly
    marked unsynced. Requiring both fields prevents a typo from silently bypassing
    sync QA on a take that still claims to be measured performance.
    """
    if not a.get("lipSyncExempt"):
        return False
    if a.get("synced") is not False or synced:
        raise ValueError("lipSyncExempt requires an explicit synced:false assignment")
    return True


def build(args) -> None:
    fps = args.fps
    hook = json.load(open(args.hook_json, encoding="utf-8"))
    index = load_index(args.index)
    if args.min_window <= 0.35:
        die("--min-window must exceed 0.35s; the planner drops shorter sections")

    # A supplied plan is the one the clips were rendered against; a derived one is not.
    # --plan reads the RENDER plan (make_plan.py's plan.json) directly, which is the
    # grid the voice references were cut from, so provenance stays valid. --windows
    # keeps taking a previously-emitted windows-<sid>.json.
    if args.plan and os.path.isfile(args.plan):
        plan_is_original, windows = True, windows_from_plan(
            args.plan, fps, song_end=float(hook.get("durationSec") or (float(hook["end"]) - float(hook["start"]))))
    elif args.windows and os.path.isfile(args.windows):
        plan_is_original = True
        windows = json.load(open(args.windows, encoding="utf-8"))["windows"]
    else:
        plan_is_original = False
        windows = derive_windows(args.transcript, hook, fps,
                                 args.min_window, args.max_window)

    if args.assign and os.path.isfile(args.assign):
        rows = json.load(open(args.assign, encoding="utf-8"))
        rows = rows.get("assignments", rows)
    elif args.auto:
        # Deterministic fallback so the stage never dead-ends.
        pool = sorted((c for c in index.values()
                       if c.get("aspectOk") and c.get("seconds", 0) > 0),
                      key=lambda c: (-c["seconds"], c["id"]))
        if len(pool) < len(windows):
            die(f"--auto needs {len(windows)} distinct clips, the index has "
                f"{len(pool)} usable ones", 4)
        # PROVENANCE FIRST, length second (2026-08-28). Pure length-pairing put a
        # film's three 16s B-ROLL cutaways into its three biggest SUNG windows and
        # handed w03 the take rendered for w02 — every sync gate then failed on a
        # healthy pipeline (and on the couple film the same by-length draw shipped a
        # wrong-clip v1 past every gate; see run-it-to-find-it). A clip that carries
        # its window's id in the library (live-job sidecars) belongs to that window.
        by_window: dict = {}
        for c in pool:                    # length-sorted, so first hit = longest take
            w = c.get("window")
            if w is not None and int(w) not in by_window:
                by_window[int(w)] = c
        rows, used, remaining = [], set(), []
        for w in windows:
            c = by_window.get(int(w["i"]))
            if c is not None and c["id"] not in used and c["seconds"] >= w["seconds"] - 0.05:
                rows.append({"window": w["i"], "clipId": c["id"]})
                used.add(c["id"])
            else:
                remaining.append(w)
        # The remainder pairs LONGEST windows with LONGEST clips. Walking windows in
        # index order against a length-sorted pool hands a 10s window a 4s clip while
        # a 4s window holds a 10s one, and the assembler refuses a clip shorter than
        # its cut — four windows were dropped that way on the first end-to-end run.
        rest = [c for c in pool if c["id"] not in used]
        if len(rest) < len(remaining):
            die(f"--auto needs {len(remaining)} more clip(s) after provenance "
                f"pinning, the index has {len(rest)}", 4)
        rows += [{"window": w["i"], "clipId": rest[n]["id"]}
                 for n, w in enumerate(sorted(remaining, key=lambda x: -x["seconds"]))]
    else:
        print(f"select_cut: no assignment file at {args.assign}.\n"
              f"  Author one from the contact strips "
              f"(build/library.html), or pass --auto:\n"
              f'  {{"assignments": [{{"window": 0, "clipId": "c012"}}, …]}}',
              file=sys.stderr)
        raise SystemExit(6)

    forced = {int(x) for x in args.force_synced.split(",") if x.strip()} \
        if args.force_synced else set()
    by_i = {w["i"]: w for w in windows}
    fill_gaps(windows, index, rows)
    problems, plan, used, editorial_exempt = [], [], {}, {}
    for a in rows:
        i, cid = a.get("window"), a.get("clipId")
        w = by_i.get(i)
        if w is None:
            problems.append(f"window {i} does not exist"); continue
        c = index.get(cid)
        if c is None:
            problems.append(f"w{i:02d}: unknown clipId {cid!r}"); continue
        if not os.path.isfile(c["clip"]):
            problems.append(f"w{i:02d}: {cid} is missing on disk ({c['clip']})"); continue
        if cid in used and not (w.get("gap") and by_i[used[cid]].get("gap")):
            # a performer take pinned to two windows is a defect; two GAP sections
            # sharing one cutaway are fill_gaps' disjoint slices of it (2026-09-02)
            problems.append(f"{cid} used twice (w{used[cid]:02d} and w{i:02d})"); continue
        if not c.get("aspectOk", True):
            problems.append(f"w{i:02d}: {cid} is {c['w']}x{c['h']}, wrong aspect for "
                            f"this film"); continue
        synced, how = resolve_synced(w, a, c, forced, plan_is_original)
        try:
            editorial_exempt[i] = resolve_lip_sync_exempt(a, synced)
        except ValueError as exc:
            problems.append(f"w{i:02d}: {exc}")
            continue
        if synced and how == "operator" and not c.get("voiceRef"):
            pass  # an explicit human claim is allowed to stand; it is recorded as such
        if synced and how == "flag" and not c.get("hasAudio"):
            problems.append(f"w{i:02d}: {cid} is forced synced but has NO AUDIO — it "
                            f"cannot be correlated, let alone synced")
            continue
        # The assembler THROWS when a performer clip is shorter than its cut
        # (`emitPerformer`), so catch it here with a message that says what to do.
        if c["seconds"] + 1e-6 < w["seconds"]:
            problems.append(
                f"w{i:02d}: {cid} is {c['seconds']:.2f}s but the window is "
                f"{w['seconds']:.2f}s — the assembler REFUSES a clip shorter than its "
                f"cut. Pick a longer clip or shorten the window.")
            continue
        used[cid] = i
        plan.append((w, c, synced, how))

    missing = sorted(set(by_i) - {w["i"] for w, *_ in plan})
    if missing:
        problems.append(f"windows with no clip: {missing}")
    if problems:
        refuse(problems)

    # A NO-VOICE WINDOW IS PINNED TO ITS OWN CLIP, EXEMPT — BY CONSTRUCTION. The plan
    # rendered it closed-mouthed against no audio (make_plan --vocal-brief), so the
    # assigned clip IS the shot for that stretch of film; leaving it unpinned let the
    # assembler fill it from the B-roll pool instead, and the energy map's shot-led
    # list (which measures reverb, not words) decided which windows that happened to.
    # Pinned + `lipSyncExempt` means: hold this clip here, and do not ask check_sync
    # to correlate it against a vocal it was never given. An explicit editorial
    # `lipSyncExempt` in cut-<sid>.json does the same and also overrides shot-led.
    plan_exempt = {w["i"] for w in windows if w.get("planNoVoice")}
    exempt = plan_exempt | {i for i, e in editorial_exempt.items() if e}
    # Shot-led for what remains: the plan's own per-window vocal mode when the plan
    # carries one (it came from the brief — words, not energy), else the energy map.
    if any(w.get("planVocalMode") for w in windows):
        shot_led = {w["i"] for w in windows
                    if w.get("planVocalMode") not in (None, "synced")} - exempt
    else:
        shot_led = load_shot_led(args.vocal_map) - exempt
    if plan_exempt:
        log_ids = ", ".join(f"w{i:02d}" for i in sorted(plan_exempt))
        print(f"select_cut: {len(plan_exempt)} no-voice window(s) from the plan — pinned "
              f"to their own clip, lip-sync exempt: {log_ids}", file=sys.stderr)
    if shot_led:
        log_ids = ", ".join(f"w{i:02d}" for i in sorted(shot_led))
        print(f"select_cut: {len(shot_led)} shot-led window(s) — no vocal to sync to, "
              f"no performer pinned: {log_ids}", file=sys.stderr)

    longest = max(w["seconds"] for w, *_ in plan)
    cut_len = round(math.ceil(longest) + 1.0, 3)
    clips, vocal_map, manifest, prov = [], [], [], {}
    for w, c, synced, how in sorted(plan, key=lambda x: x[0]["i"]):
        wid = f"w{w['i']:02d}"
        clips.append({"id": wid, "path": c["clip"], "durationSec": c["seconds"]})
        # A SHOT-LED window has no vocal under it. Pinning a performer there tells
        # the assembler to hold on a face that is mouthing nothing the song sings,
        # and `synced` would then be carried into provenance and believed. Leave
        # the clip in the pool as B-roll and stop claiming a sync it cannot have.
        led = w["i"] in shot_led
        is_exempt = w["i"] in exempt
        if is_exempt and synced and how != "operator":
            synced, how = False, "plan-no-voice"   # nothing to be synced TO
        # THE FILM STARTS AT ZERO. `--exact-onsets` anchors a window on its first word
        # and the first window's anchor can round one frame BELOW zero (New Era w00:
        # -0.083333); the assembler refuses a vocal map whose first section is negative
        # ("invalid vocal map: first section starts at -0.083333"), three stages later.
        # A frame of head is not content — clamp it here, where the map is written.
        section = {"start": max(0.0, w["start"]), "end": w["end"],
                   "type": "instrumental" if led else w["type"]}
        if w.get("headSec") or w.get("tailSec"):
            section["headSec"], section["tailSec"] = w.get("headSec", 0.0), w.get("tailSec", 0.0)
        if not led:
            section["performerClip"] = wid
            if is_exempt:
                section["lipSyncExempt"] = True
        vocal_map.append(section)
        # THE VOICE SLICE TRAVELS WITH THE ROW. check_sync can then ask rate_fit
        # whether a take that fails correlation is simply SLOW (retimable in `slide`)
        # rather than singing other words — the whole New Era cut was refused for
        # exactly that (2026-08-30).
        manifest.append({"start": max(0.0, w["start"]), "seconds": w["seconds"],
                         # the clip's in-point: the assembler shows it from here, so the
                         # sync measurement must read it from here too (record mode, raw
                         # takes: every window read 0.3–0.7 s late for its head, 2026-09-06)
                         "headSec": round(float(w.get("headSec") or 0.0), 3),
                         "clip": c["clip"], "synced": False if led else synced,
                         "voiceRef": (w.get("voiceRef") or ""),
                         "lines": (w.get("lines") or ""),
                         "lipSyncExempt": is_exempt})
        prov[wid] = {"clipId": c["id"], "origin": c.get("origin", ""),
                     "window": w["i"], "synced": synced, "syncedBy": how,
                     # THE PLAN'S NAME FOR THIS SECTION. Gap sections shift the grid, so
                     # the plan's w04 is the cut's w06; every page and every --span the
                     # operator types says the PLAN's id, and raplib.resolve_window maps it
                     # through here. Without it 30 of 32 cover spans were dropped without
                     # a word and a film shipped with no cutaways (film #3, 2026-09-06).
                     "planId": w.get("planId"), "planWindow": w.get("planWindow"),
                     "lipSyncExempt": is_exempt,
                     "pinnedBy": ("plan-no-voice" if w["i"] in plan_exempt
                                  else "editorial-exempt" if is_exempt
                                  else None if led else "performer"),
                     "adlib": bool(w.get("adlib")), "shotLed": w["i"] in shot_led,
                     "strip": c.get("strip", ""),
                     "text": w.get("text", "")[:120]}

    # REAL B-ROLL FOR THE POOL. Shot-led windows draw from it, so a performance clip
    # here is the mouthing defect by another route.
    broll = pool_clips(index, {p["clipId"] for p in prov.values()}, cut_len)
    if broll:
        for n, b in enumerate(broll):
            bid = f"b{n:02d}"
            clips.append({"id": bid, "path": b["clip"], "durationSec": b["seconds"]})
        pool_ids = [f"b{n:02d}" for n in range(len(broll))]
        print(f"select_cut: pool = {len(pool_ids)} B-roll clip(s) longer than the "
              f"{cut_len:g}s cut", file=sys.stderr)
    else:
        # No qualifying B-roll. Keep the pool NON-EMPTY — an empty one makes the
        # planner silently skip a cut, and missing film is harder to spot than a wrong
        # clip — but say plainly what will happen if it is ever drawn from.
        pool_ids = [clips[0]["id"]]
        unpinned = sum(1 for s_ in vocal_map if not s_.get("performerClip"))
        note = (f"select_cut: NO B-roll longer than the {cut_len:g}s cut, so the pool "
                f"falls back to a PERFORMANCE clip ({pool_ids[0]}).")
        if unpinned:
            note += (f" {unpinned} window(s) are unpinned and WILL draw from it — each "
                     f"will show a lip-synced take stepped to an arbitrary in-point, "
                     f"mouthing words the song is not singing there. Render B-roll "
                     f"longer than {cut_len + 0.2:g}s to fix it.")
        else:
            note += " Every window is pinned, so nothing draws from it."
        print(note, file=sys.stderr)

    selection = {
        "schemaVersion": 1, "style": args.style, "fps": fps,
        "songEnd": max(w["end"] for w, *_ in plan),
        "songRef": hook["hookWav"],
        "_typeIsCadenceControl": True,
        "vocalMap": vocal_map,
        "clips": clips,
        # All four roles draw from the same set: a rap MV of this length has one
        # B-roll set. The schema requires every role, and an EMPTY pool makes the
        # planner silently SKIP a cut — missing film, harder to spot than a wrong clip.
        "pools": {r: list(pool_ids) for r in ("action", "atmo", "trio", "vanish")},
        "cutLengths": {r: cut_len for r in CUT_ROLES},
        "provenance": prov,
    }
    os.makedirs(os.path.dirname(os.path.abspath(args.out_selection)), exist_ok=True)
    json.dump(selection, open(args.out_selection, "w"), indent=2)
    json.dump(manifest, open(args.out_manifest, "w"), indent=2)
    if args.out_windows:
        json.dump({"schemaVersion": 1, "fps": fps, "style": args.style,
                   "windows": windows}, open(args.out_windows, "w"), indent=2)
    if args.gallery:
        write_gallery(args.gallery, prov, manifest, args.style)

    n_sync = sum(1 for m in manifest if m["synced"])
    print(f"select_cut: {len(manifest)} windows, {n_sync} synced, "
          f"cut={cut_len}s -> {args.out_selection}", file=sys.stderr)
    for wid, p in prov.items():
        print(f"  {wid} {p['clipId']:>5} {'SYNC' if p['synced'] else 'broll':<5}"
              f" {p['syncedBy']:<10} {p['origin']}", file=sys.stderr)
    if n_sync < len(manifest):
        print("  unsynced windows carry the closed-mouth rule: frame him waist-up or "
              "closer, face legible, lips together — NOT hidden.", file=sys.stderr)


def write_gallery(path: str, prov: dict, manifest: list[dict], style: str) -> None:
    cards = ""
    for (wid, p), m in zip(prov.items(), manifest):
        badge = ("<b class='s'>LIP-SYNCED</b>" if p["synced"]
                 else "<b class='b'>PINNED · no voice · lips closed</b>" if p.get("lipSyncExempt")
                 else "<b class='b'>B-roll · mouth closed</b>")
        strip = (f'<img loading="lazy" src="{html.escape(p["strip"])}'
                 f'?v={int(os.path.getmtime(p["strip"]))}">'
                 if p.get("strip") and os.path.isfile(p["strip"]) else "")
        cards += (f'<figure>{strip}<figcaption><b>{wid}</b> {badge}'
                  f'<span>{p["clipId"]} · {html.escape(p["origin"])} · '
                  f'{m["seconds"]:.2f}s · via {p["syncedBy"]}</span>'
                  f'<p>{html.escape(p.get("text", ""))}</p></figcaption></figure>')
    open(path, "w", encoding="utf-8").write(shell(
        f"{html.escape(style)} — {len(manifest)} windows, {sum(1 for m in manifest if m['synced'])} lip-synced",
        "The cut: one clip per window, in film order — which take sits where, and whether it is pinned as synced.",
        f'<div class="g">{cards}</div>',
        extra_css=".g{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:14px}"
                  "figure{margin:0;background:var(--panel);border:1px solid var(--line);border-radius:10px;overflow:hidden}"
                  "img{width:100%;display:block;border:0;border-radius:0}figcaption{padding:9px 11px;font-size:12px;color:var(--ink2)}"
                  "figcaption b{color:var(--ink)}.s{color:var(--good)}.b{color:var(--accent)}"
                  "figcaption span{display:block;margin-top:3px}figure p{margin:6px 0 0;color:var(--ink3)}"))
    inject_nav(path)


def verify_plan(args) -> None:
    """Re-read the assembler's OWN plan and refuse if it stopped matching.

    The one-cut-per-window guarantee rests on planner internals (`cutIdx % 3`, section
    boundaries clipping an over-long cut). Depending on that is fine; depending on it
    WITHOUT checking is how a silent wrong-clip ships. This turns that into exit 5."""
    cfg = json.load(open(args.config, encoding="utf-8"))
    if cfg.get("beats"):
        die("the config carries `beats`; cut points would no longer be section "
            "boundaries and the one-cut-per-window property dies", 5)
    vclaw = args.vclaw or os.path.join(
        os.environ.get("MAIN", os.path.expanduser("~/Documents/GitHub/videoclaw-v3")),
        "dist/cli/vclaw.js")
    r = subprocess.run(["node", vclaw, "video", "music-video", "--config", args.config],
                       capture_output=True)
    try:
        plan = json.loads(r.stdout.decode() or "{}")
    except Exception:
        die(f"could not read the dry-run plan (is {vclaw} built?)\n"
            f"{r.stderr.decode()[:400]}", 5)
    labels = [s.get("label", "") for s in (plan.get("steps") or [])]
    # Only CUT steps match; `concat`/`mux` are steps too and counting them as cuts
    # over-reports b-roll.
    cuts = [m for m in (LABEL_RE.match(l) for l in labels) if m]
    perf = [m for m in cuts if m.group(2) == "performer"]
    if not perf:
        die("the plan contains no performer cut at all — nothing is pinned", 5)

    if args.selection:
        sel = json.load(open(args.selection, encoding="utf-8"))
        # Only PINNED windows produce a performer cut: a shot-led window (no vocal
        # under it) carries no performerClip and is drawn from the pool instead, so
        # it must not be expected here. Indexing it KeyError'd the first full-track
        # film whose opening window sat over an instrumental (2026-08-22).
        want = [s["performerClip"] for s in sel["vocalMap"] if s.get("performerClip")]
        exempt_pinned = [s["performerClip"] for s in sel["vocalMap"]
                         if s.get("performerClip") and s.get("lipSyncExempt")]
        got = [m.group(3) for m in perf]
        if exempt_pinned:
            print(f"select_cut: {len(exempt_pinned)} exempt (no-voice) window(s) are pinned "
                  f"and expected as performer cuts: {', '.join(exempt_pinned)}",
                  file=sys.stderr)
        if got != want:
            die(f"the assembler's cut plan no longer matches the selection.\n"
                f"  expected one performer cut per window: {want}\n"
                f"  the plan produced:                     {got}\n"
                f"  planVocalSync's pinning behaviour changed — re-derive before "
                f"spending render time.", 5)
    else:
        # Legacy pools path: ONE hero clip carrying every section. `emitPerformer`
        # seeks to time-WITHIN-SECTION, so a second section replays that clip from its
        # own start while the song has moved on — his mouth on the wrong words,
        # produced by the config builder rather than by a bad clip choice.
        #
        # The signature is per-CLIP, not global: the same clip appearing in more than
        # one performer cut whose in-points do not advance. (Checking only that
        # in-points never go backwards misses the common case, where every section
        # restarts the clip at 0.00s and nothing decreases.)
        seen: dict[str, list[float]] = {}
        for m in perf:
            seen.setdefault(m.group(3), []).append(float(m.group(4)))
        for clip, ins in seen.items():
            for a, b in zip(ins, ins[1:]):
                if b <= a + 1e-6:
                    die(f"clip {clip!r} is pinned to more than one section and the "
                        f"later one seeks back to {b:.2f}s (after {a:.2f}s). The "
                        f"assembler seeks a performer clip to time-WITHIN-SECTION, so "
                        f"that section plays his mouth against the wrong words.\n"
                        f"  Use --selection (windows mode): one section per window, "
                        f"each with its own clip.", 5)
    print(f"select_cut: plan verified — {len(perf)} performer cut(s), "
          f"{len(cuts) - len(perf)} b-roll", file=sys.stderr)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--verify-plan", action="store_true")
    ap.add_argument("--config"), ap.add_argument("--selection"), ap.add_argument("--vclaw")
    ap.add_argument("--project"), ap.add_argument("--style", default="")
    ap.add_argument("--index"), ap.add_argument("--hook-json"), ap.add_argument("--transcript")
    ap.add_argument("--assign", default=""), ap.add_argument("--windows", default="")
    ap.add_argument("--vocal-map", default="", dest="vocal_map",
                    help="vocal_map.py vocal-map.json — windows it marks shotLed get "
                    "no pinned performer and claim no sync")
    ap.add_argument("--plan", default="", help="make_plan.py plan.json — the grid the "
                    "clips were rendered against; keeps provenance sync claims valid")
    ap.add_argument("--fps", type=int, default=24)
    ap.add_argument("--min-window", type=float, default=3.0)
    ap.add_argument("--max-window", type=float, default=10.0)
    ap.add_argument("--auto", action="store_true"), ap.add_argument("--force-synced", default="")
    ap.add_argument("--out-selection", default=""), ap.add_argument("--out-manifest", default="")
    ap.add_argument("--out-windows", default=""), ap.add_argument("--gallery", default="")
    args = ap.parse_args()

    if args.verify_plan:
        if not args.config:
            die("--verify-plan needs --config")
        verify_plan(args)
        return
    for need in ("index", "hook_json", "out_selection", "out_manifest"):
        if not getattr(args, need):
            die(f"--{need.replace('_', '-')} is required")
    if not args.transcript and not args.windows:
        die("--transcript is required unless --windows is given")
    build(args)


if __name__ == "__main__":
    main()
