#!/usr/bin/env python3
"""cover_mouthing.py — cut away over the stretches where he mouths to silence.

THIS IS NOT A SYNC DEFECT, which is why neither sync gate can catch it. A window can be
perfectly on its bar and still be wrong, because for part of it the song is not singing
anything and the performer is mouthing away regardless. Correlation against silence is
meaningless rather than bad, so no offset threshold flags it — and a re-render does not
fix it either, because the model was asked for a performance and delivered one.

The only fix is to not be looking at his face during those seconds.

Found by an operator watching a delivered master: "there is no lyric here and he's
moving his lips". The transcript agreed exactly — words stopped at 88.6s and did not
resume until 99.6s, so the first 3.6s of the 96-104s window was a performance to
nothing. Three separate gates had passed that film.

WHY A COMPOSITE CLIP RATHER THAN SPLITTING THE SECTION. The obvious move is to split
the window into a short instrumental section plus a shorter performance one. But the
assembler fills an instrumental window with whole cuts of one global length, and a 3.6s
section does not divide by it — the remainder is dropped and the film comes up short.
That is exactly the bug that once produced a 118.5s master out of a 122.25s song.
Building ONE clip that is B-roll for its head and the real performance for its tail
leaves the window its full length and the assembler untouched.

ALIGNMENT IS PRESERVED, which is the whole point. Film time (start + t) still shows
performer-clip time t for every t past the cover, because the cover occupies exactly
the seconds it replaces. Slide the performance to make room instead and every remaining
word lands in the wrong place.

TRUST THE TRANSCRIPT, NOT AN ENERGY MAP, for where the vocal actually stops. An
energy-based vocal map is silently wrong on a dense instrumental — on this film the
break measured 1.11x the speech-band energy of the sung sections. Whisper word timings
are the source of truth for "is anyone singing here".

Usage:
  cover_mouthing.py --selection <selection-<style>.json> --vocal-map <vocal-map.json>
                    --stage <dir> --broll <dir> [--cover wNN=<file> ...] [--min-cover 1.0]

Rewrites the covered clips in place inside --stage, so run it AFTER sync_shift.py and
BEFORE the cut.
"""
from __future__ import annotations

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


# A performer piece shorter than this beside a cutaway is a flash frame: it joins the cutaway.
MIN_PERF_PIECE_S = 0.5
# A pause cutaway shorter than this reads as a glitch, not an edit — --pause-cover pads a
# measured silence up to this length, and folds a remainder shorter than it (against the
# window's own end) into the cutaway rather than leaving a flash of closed-mouth performer.
MIN_PAUSE_COVER_S = 1.2


def should_exempt_from_full_window_sync(covered: float, span: float) -> bool:
    """A composite with any cutaway is no longer a full-window sync sample.

    The pre-cover sync gate has already measured the original performance. After a
    cutaway replaces even a short silent stretch, correlating the composite's entire
    audio envelope against the song can only measure the edit, not the performer's
    timing. Word-level QA receives the exact cutaway spans separately.
    """
    return span > 0 and covered > 0

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sync_profile import clip_resolver  # noqa: E402


def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        raise SystemExit(f"ffmpeg failed:\n{r.stderr[-1500:]}")


def has_audio(path: str) -> bool:
    """Silent clips are legitimate (intros render with generateAudio off); a filtergraph
    that references [N:a] on one dies with 'Stream specifier :a ... Invalid argument'
    (2026-08-24, w00). Their audio leg is synthesised silence instead."""
    r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a",
                        "-show_entries", "stream=codec_type", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    return r.returncode == 0 and bool(r.stdout.strip())


def probe(path: str) -> str:
    return subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
                           "-of", "csv=p=0", path], capture_output=True, text=True).stdout.strip()


def overlaps(x, ys):
    return any(min(x[1], y[1]) > max(x[0], y[0]) for y in ys)


def find_silences(path: str, start: float, end: float, min_len: float, min_db: float = -30.0) -> list[tuple[float, float]]:
    """Silences in `path` inside [start, end) (absolute seconds), each at least
    `min_len` long — ffmpeg's own silencedetect (stderr parsed), not a second envelope
    implementation. `-ss` BEFORE `-i` resets the filter's own timestamps to the seek
    point (verified: a silence physically at absolute 7.0-7.8s reads as 4.0-4.8s when
    seeking to 3.0 first), so the reported times are rebased onto `start` here."""
    dur = end - start
    if dur <= 0 or not os.path.isfile(path):
        return []
    r = subprocess.run(
        ["ffmpeg", "-v", "info", "-ss", f"{start:.3f}", "-t", f"{dur:.3f}", "-i", path,
         "-af", f"silencedetect=noise={min_db}dB:d={min_len:.3f}", "-f", "null", "-"],
        capture_output=True, text=True)
    starts = [float(m) for m in re.findall(r"silence_start:\s*(-?[\d.]+)", r.stderr)]
    ends = [float(m) for m in re.findall(r"silence_end:\s*([\d.]+)", r.stderr)]
    out: list[tuple[float, float]] = []
    for i, s0 in enumerate(starts):
        e0 = ends[i] if i < len(ends) else dur   # a trailing silence has no silence_end line
        s0, e0 = max(0.0, s0), min(dur, e0)
        if e0 > s0:
            out.append((round(start + s0, 3), round(start + e0, 3)))
    return out


def pause_cover_spans(stem: str, short_gaps: list[tuple[float, float]], silent: list[tuple[float, float]],
                      start: float, end: float, min_len: float) -> list[tuple[float, float]]:
    """Where the vocal falls silent inside [start, end) (absolute seconds), each at
    least `min_len` long. Measured against the vocal-only stem when one exists — a real
    silence, not just a quiet instrumental section under it; without a stem, falls back
    to the vocal map's own gap lists (shortGaps: the small gaps too short for the
    standing --min-cover; silentStretches: the same ones the main derived-cover pass
    already covers, included here too so a --pause-cover shorter than --min-cover still
    reaches them) at the same minimum length."""
    if stem and os.path.isfile(stem):
        return find_silences(stem, start, end, min_len)
    out: list[tuple[float, float]] = []
    for gs, ge in short_gaps + silent:
        lo, hi = max(gs, start), min(ge, end)
        if hi - lo >= min_len:
            out.append((lo, hi))
    return out


def coalesce_spans(spans: list[tuple[float, float, str, str]]) -> list[tuple[float, float, str, str]]:
    """Merge derived spans that touch (or overlap) and share the same cover into one —
    a pause immediately beside a silent-stretch cutaway (or another pause) reads as ONE
    cut with one record, not two abutting ones that happen to play back to back."""
    out: list[tuple[float, float, str, str]] = []
    for lo, hi, cvr, why in sorted(spans, key=lambda x: x[0]):
        if out and out[-1][2] == cvr and lo <= out[-1][1] + 1e-6:
            plo, phi, pc, pwhy = out[-1]
            out[-1] = (plo, max(phi, hi), pc, pwhy if pwhy == why else f"{pwhy}; {why}")
        else:
            out.append((lo, hi, cvr, why))
    return out


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--selection", required=True)
    ap.add_argument("--vocal-map", required=True)
    ap.add_argument("--stage", required=True)
    ap.add_argument("--broll", required=True, help="directory of cutaway clips")
    ap.add_argument("--cards", default="", help="build/bookends/cards.json — lets a --span use the film clock (1:48-1:53)")
    ap.add_argument("--cover", action="append", default=[],
                    help="wNN=<file> — pin a specific cutaway to a window. Prefer a shot "
                         "from the window's OWN world so it reads as a deliberate cut.")
    ap.add_argument("--span", action="append", default=[],
                    help="wNN:START-END[:BROLL] (song seconds) — cover an EXPLICIT span, "
                         "e.g. the operator heard a take drift or mouth through a short "
                         "gap the auto-derivation will not touch (w03's 1.15s and w10's "
                         "mangled turn both needed a hand rebuild on 2026-08-24). BROLL "
                         "names a file in --broll; omitted, the window's pin/pool cover "
                         "is used. Applies even to lipSyncExempt windows: an explicit "
                         "span IS the operator's direction.")
    ap.add_argument("--min-cover", type=float, default=1.0,
                    help="shorter than this and the cutaway is a flash frame "
                         "(derived spans only — an explicit --span is taken as given)")
    ap.add_argument("--width", type=int, default=720)
    ap.add_argument("--height", type=int, default=1280)
    ap.add_argument("--fps", type=int, default=24)
    ap.add_argument("--no-derived", action="store_true",
                    help="apply only the record's spans and the operator's --span/--cover; derive no "
                         "silent-stretch covers. AUDIO_MODE=vocal-swap: the take's own voice follows its "
                         "mouth, so mouthing over the record's silence is not a defect to cover")
    ap.add_argument("--record", default="",
                    help="write/merge the covered spans here (default: cutaways.json "
                         "beside the selection). This is not bookkeeping — see below.")
    ap.add_argument("--pause-cover", type=float, default=0.0, metavar="SEC",
                    help="cover a silence inside a performer window this long or longer "
                         "(default 0 = off). Measured against the vocal STEM directly "
                         "(build/stems/vocals.wav beside --vocal-map, or --stem), so a "
                         "pause too short to open its own --min-cover section still gets "
                         "a cutaway — he stands silent, the song plays on, and nothing "
                         "upstream of this stage looked for that. Padded to at least "
                         "MIN_PAUSE_COVER_S (1.2s) so the cut reads as an edit.")
    ap.add_argument("--stem", default="",
                    help="the vocal-only stem --pause-cover measures against. Default: "
                         "stems/vocals.wav beside --vocal-map; missing, falls back to the "
                         "vocal map's own shortGaps/silentStretches at the same minimum "
                         "length.")
    a = ap.parse_args()

    sel = json.load(open(a.selection, encoding="utf-8"))
    vm = json.load(open(a.vocal_map, encoding="utf-8"))
    silent = [(float(g["start"]), float(g["end"])) for g in vm.get("silentStretches", [])]
    short_gaps = [(float(g["start"]), float(g["end"])) for g in vm.get("shortGaps", [])]
    # SALVAGED TAILS (lane_render judge, RAP_SALVAGE): absolute-time spans where a kept
    # take sings the right words but drifts off the bar in its tail — covered like a
    # silent stretch, so the take costs a cutaway instead of a ~30-min redraw.
    salvage_path = os.path.join(os.path.dirname(os.path.abspath(a.vocal_map)), "salvage-cover.json")
    salvage_by_window = {}
    if os.path.isfile(salvage_path):
        try:
            _sv = json.load(open(salvage_path, encoding="utf-8")).get("windows", {})
            salvage_by_window = {k: [(float(lo), float(hi)) for lo, hi in v] for k, v in _sv.items()}
        except (OSError, ValueError):
            print("  salvage-cover.json unreadable — ignoring it", file=sys.stderr)
    pinned = dict(c.split("=", 1) for c in a.cover)
    pool = sorted(f for f in os.listdir(a.broll) if f.endswith(".mp4"))
    if not pool:
        print("no B-roll to cut away to — nothing done", file=sys.stderr)
        return 1
    # THE STAGE DIR IS WHERE THE PRISTINE COPY LIVES, so it must exist even when the
    # clips themselves are elsewhere. Under AUDIO_MODE=vocal-swap there is no shifted-<sid>
    # (the slide stage is fit+join), so the runner points --stage at build/clips, which no
    # earlier stage creates — and the first cover died writing its precover there
    # (Baby Ram & Sita, 2026-09-01).
    os.makedirs(a.stage, exist_ok=True)
    resolve = clip_resolver(sel, a.stage)

    # style -> cutaway file, from the broll plan beside the vocal map (absent -> {}),
    # and window -> style from the render plan, so a cover can stay in its own world.
    style_cover, win_style = {}, {}
    bdir = os.path.dirname(os.path.abspath(a.vocal_map))
    stem_path = a.stem or os.path.join(bdir, "stems", "vocals.wav")
    try:
        for j in json.load(open(os.path.join(bdir, "broll-plan.json"), encoding="utf-8")).get("jobs", []):
            f = os.path.join(a.broll, f"{j['id']}.mp4")
            if os.path.isfile(f) and j.get("styleId") and j["styleId"] not in style_cover:
                style_cover[j["styleId"]] = f
        for j in json.load(open(os.path.join(bdir, "plan.json"), encoding="utf-8")).get("jobs", []):
            win_style[j["id"]] = j.get("styleId")
    except (OSError, ValueError):
        pass

    def broll_path(name: str | None, default: str) -> str:
        """A --span/record broll NAME to a path in --broll; None -> the window default."""
        if not name:
            return default
        if os.path.isfile(name):
            return name
        cand = os.path.join(a.broll, name)
        if os.path.isfile(cand):
            return cand
        return cand + ".mp4"

    explicit: dict[str, list] = {}
    for raw in a.span:
        # song seconds or the film clock, the plan's window id or the grid's (raplib.parse_span)
        try:
            ps = raplib.parse_span(raw, cards=a.cards or None, selection=sel)
        except ValueError as e:
            raise SystemExit(f"--span {e}")
        if not ps["window"]:
            raise SystemExit(f"--span {raw!r}: a cover span names its window, wNN:START-END[:BROLL]")
        explicit.setdefault(ps["window"], []).append((ps["start"], ps["end"], ps["broll"]))
    # SAY WHAT WILL NOT BE COVERED. A span whose window resolves to nothing in this
    # cut, or lies outside the section it resolved to, used to vanish without a
    # word — 30 of 32 did on film #3 and the master shipped with no cutaways
    # (2026-09-06). Loud, before any clip is touched.
    _sections = {s.get("performerClip"): (float(s["start"]), float(s["end"]))
                 for s in sel["vocalMap"] if s.get("performerClip")}
    _given = sum(len(v) for v in explicit.values())
    for _w, _spans in explicit.items():
        if _w not in _sections:
            print(f"  --span {_w}: NO SUCH WINDOW in this cut ({len(_spans)} span(s) dropped) — "
                  f"the ids on the page are the plan's; is the selection older than the plan?", file=sys.stderr)
            continue
        _lo, _hi = _sections[_w]
        for _a, _b, _c in _spans:
            if _b <= _lo or _a >= _hi:
                print(f"  --span {_w}:{_a}-{_b}: OUTSIDE its window ({_lo:.2f}-{_hi:.2f}s) — dropped", file=sys.stderr)
    if _given:
        print(f"  explicit spans: {_given} given on {len(explicit)} window(s)", file=sys.stderr)

    # WHAT WAS COVERED HAS TO BE WRITTEN DOWN, and this is the only place that knows it.
    #
    # A covered second has no vocal in the clip BY DESIGN, so the lyric-coverage gate has
    # to exclude it — otherwise every deliberate edit reads as a WRONG-LYRIC and the gate
    # starts crying wolf, which is how people learn to click through gates. That file was
    # hand-written once, by an operator, from memory. Nothing produced it, so on the next
    # film it would simply not exist and the noise would come back.
    # PER STYLE. Derived from the selection's name (selection-<style>.json -> cutaways-
    # <style>.json): one shared record across styles made every style after the first
    # skip its derived covers, because prior spans are keyed by window id and the id is
    # the same in every style (2026-08-29). An unnamed selection keeps the old name.
    sel_dir = os.path.dirname(os.path.abspath(a.selection))
    sel_base = os.path.basename(a.selection)
    m_sid = re.match(r"selection-(.+)\.json$", sel_base)
    record_path = a.record or os.path.join(sel_dir, f"cutaways-{m_sid.group(1)}.json" if m_sid else "cutaways.json")
    try:
        existing = json.load(open(record_path, encoding="utf-8"))
        recorded = [c for c in existing.get("cutaways", []) if isinstance(c, dict)]
    except (OSError, ValueError):
        recorded = []

    done = 0
    cleared = 0
    for i, s in enumerate(sel["vocalMap"]):
        perf = s.get("performerClip")
        if not perf:
            continue
        start, end = float(s["start"]), float(s["end"])
        exp_raw = explicit.get(perf, [])
        # MOUTHING-RISK advisory: gaps below the auto-cover line are recorded by
        # vocal_map as shortGaps, and a take mouthing through one is exactly the defect
        # the operator catches on screen (w03's 1.15s, 2026-08-24). Say where to look.
        risks = [(max(gs, start), min(ge, end)) for gs, ge in short_gaps
                 if min(ge, end) - max(gs, start) > 0.2]
        if risks:
            print(f"  {perf}: MOUTHING-RISK at "
                  + ", ".join(f"{lo:.1f}-{hi:.1f}s" for lo, hi in risks)
                  + f" — short gap(s), not auto-covered; check the take and cover with "
                    f"--span {perf}:START-END if it mouths through", file=sys.stderr)
        # A COVER'S EXEMPTION LASTS ONLY AS LONG AS THE COVER. A run that covered 46 % of a
        # window marked it lipSyncExempt; the cover was reverted (pristine copy restored,
        # record deleted) and the next run skipped it as a "designed no-voice shot" — so
        # vocal_swap left the whole window to the record and his own voice never played
        # with his mouth (Baby Ram & Sita w04, v2/v3, 2026-09-01). With NO record left for
        # this clip the tag is stale: clear it and let this run decide again. A record
        # still on file (a replay, or covers baked in with no pristine copy) keeps it.
        by_cover = s.get("lipSyncExemptBy") == "cover"
        designed_exempt = bool(s.get("lipSyncExempt")) and not by_cover
        if by_cover and not any(c.get("clip") == perf for c in recorded):
            s.pop("lipSyncExempt", None); s.pop("lipSyncExemptBy", None); by_cover = False
            cleared += 1
            # A HALF-REVERT (record deleted, clip not restored) would leave the composite on
            # disk with no exemption and no record: the swap would feed its B-roll audio to
            # Demucs and the film would carry no vocal there (review finding, 2026-09-02).
            # The pristine copy exists for exactly this — put it back.
            _src = resolve(perf)
            _pre = os.path.join(a.stage, f"{perf}.precover.mp4") if _src else None
            if _src and _pre and os.path.isfile(_pre) and os.path.isfile(_pre + ".json"):
                try:
                    made = json.load(open(_pre + ".json", encoding="utf-8")); st = os.stat(_src)
                    if made.get("size") == st.st_size and abs(made.get("mtime", -1) - st.st_mtime) < 1.0:
                        import shutil
                        shutil.copyfile(_pre, _src)
                        print(f"  {perf}: its record is gone but the clip on disk was still the composite — "
                              f"restored the pristine take", file=sys.stderr)
                except (OSError, ValueError):
                    pass
        if designed_exempt and not exp_raw:
            # A window the PLAN sent without a voice is a designed silent performance
            # shot — the entries of this film's whole concept. Covering it 100% with
            # empty B-roll deleted his entry walk and her corridor (2026-08-24). The
            # exemption in the INPUT selection means "the shot holds the face on
            # purpose"; auto-derivation never touches it — but an explicit --span IS
            # the operator's direction and applies even here (the w10 turn fix).
            print(f"  {perf}: designed no-voice shot (lip-sync exempt in the selection) — not covered",
                  file=sys.stderr)
            continue
        src = resolve(perf)
        if src is None:
            print(f"  {perf}: does not resolve to a file — skipped", file=sys.stderr)
            continue
        # SAME WORLD FIRST. A cutaway from the window's own style reads as a deliberate
        # cut; the round-robin default handed every cover the same three shots and the
        # operator saw the repeat (2026-08-29). broll-plan.json names each cutaway's
        # style; a pin still wins, and the round-robin remains the fallback.
        default_cover = pinned.get(perf) or style_cover.get(s.get("styleId") or win_style.get(perf)) \
            or os.path.join(a.broll, pool[i % len(pool)])
        prior = [c for c in recorded if c.get("clip") == perf]
        # Three origins of window-relative (lo, hi, cover, why):
        #   prior    — already-recorded cutaways, re-applied only on a pristine rebuild
        #   derived  — silent stretches inside the window (never on an exempt window).
        #              ANY span inside the window, not just the head: on the birthday
        #              film all three holes began mid-window and the head-only version
        #              reported nothing while 18s of mouthing shipped.
        #   explicit — the operator's --span, taken as given
        prior_spans = [(float(p["startSec"]) - start, float(p["endSec"]) - start,
                        broll_path(p.get("broll"), default_cover),
                        p.get("why") or "recorded cutaway")
                       for p in prior]
        derived = []
        if not designed_exempt and not a.no_derived:
            for gs, ge in silent:
                lo, hi = max(gs, start) - start, min(ge, end) - start
                if hi - lo >= a.min_cover:
                    derived.append((lo, hi, default_cover,
                                    f"{hi - lo:.1f}s of mouthing over an instrumental "
                                    f"stretch — the song is not singing here, so no "
                                    f"re-render can fix it"))
            wid = os.path.splitext(os.path.basename(str(perf)))[0].split("-")[0]
            for gs, ge in salvage_by_window.get(wid, []):
                lo, hi = max(gs, start) - start, min(ge, end) - start
                if hi - lo >= a.min_cover:
                    derived.append((lo, hi, default_cover,
                                    f"{hi - lo:.1f}s salvaged tail — right words, "
                                    f"drifted off the bar; covered instead of redrawn"))
            # A PAUSE THAT NEVER REACHES --min-cover STILL SHOWS. The gaps above only
            # cover an instrumental SECTION; a performer window can carry its own short
            # silences too (a breath, a line that lands early) where he keeps performing
            # to nothing. --pause-cover measures the vocal stem directly rather than
            # waiting for the section-level gap, and pads a genuine but short silence up
            # to MIN_PAUSE_COVER_S so the cutaway reads as a real edit, not a glitch — a
            # pause ending within that same margin of the window's own end takes it all
            # the way to the end (the performer piece it would leave is a flash frame).
            if a.pause_cover > 0 and not a.no_derived and not s.get("lipSyncExempt"):
                window_len = end - start
                for ps, pe in pause_cover_spans(stem_path, short_gaps, silent, start, end, a.pause_cover):
                    lo, hi = max(ps, start) - start, min(pe, end) - start
                    if hi <= lo:
                        continue
                    measured = hi - lo
                    if hi - lo < MIN_PAUSE_COVER_S:
                        hi = min(window_len, lo + MIN_PAUSE_COVER_S)
                    if window_len - hi < MIN_PAUSE_COVER_S:
                        hi = window_len
                    if hi <= lo:
                        continue
                    derived.append((lo, hi, default_cover,
                                    f"{measured:.1f}s pause in the vocal — he stands silent "
                                    f"here; the song plays on (--pause-cover)"))
                derived = coalesce_spans(derived)
        exp_spans = [(max(lo, start) - start, min(hi, end) - start,
                      broll_path(br, default_cover), "operator-directed cover (--span)")
                     for lo, hi, br in exp_raw if min(hi, end) > max(lo, start)]

        # IDEMPOTENT REBUILDS COME FROM A PRISTINE COPY. Baking covers into the stage
        # clip in place meant a re-run composited B-roll over B-roll and "extend this
        # cover a second earlier" needed a hand rebuild from the queue clip (w10,
        # 2026-08-24). The first cover of a clip saves <clip>.precover.mp4; every run
        # after that rebuilds from it, re-applying the recorded spans with THEIR OWN
        # B-roll plus whatever is new.
        # NEVER COMPOSITE OVER AN ORIGINAL RENDER. The stage's copies (shifted-/fitted-/
        # joined-) are ours to rewrite; a clip still under queue/ is the take itself, the
        # file every store keys on. Cover a copy in the stage dir and point the selection
        # at it (review finding, 2026-09-02).
        if os.sep + "queue" + os.sep in src:
            import shutil
            copy = os.path.join(a.stage, os.path.basename(src))
            if not os.path.isfile(copy):
                shutil.copyfile(src, copy)
            for c in sel.get("clips", []):
                if c.get("id") == perf:
                    c["path"] = copy
            src = copy
        pre = os.path.join(a.stage, f"{perf}.precover.mp4")
        # THE PRISTINE COPY IS KEYED TO THE COMPOSITE IT PRODUCED. A name-keyed precover
        # outlived --replace / --replan / a re-fit and the next cover rebuilt the window
        # from the OLD take and wrote it over the NEW one (proved with a red/blue take,
        # review finding 2026-09-02). The sidecar records the composite we wrote; if the
        # clip on disk is not that file, someone rewrote it and the precover is stale.
        side = pre + ".json"
        if os.path.isfile(pre):
            try:
                made = json.load(open(side, encoding="utf-8"))
                st = os.stat(src)
                fresh = (made.get("size") == st.st_size and abs(made.get("mtime", -1) - st.st_mtime) < 1.0)
            except (OSError, ValueError):
                fresh = False
            if not fresh:
                print(f"  {perf}: the clip on disk is not the composite the pristine copy produced "
                      f"— a re-fit or a replaced take; discarding the stale precover", file=sys.stderr)
                os.remove(pre)
                for f in (side,):
                    if os.path.isfile(f):
                        os.remove(f)
        make_precover = False
        if os.path.isfile(pre):
            build_src = pre
            spans = prior_spans + [d for d in derived if not overlaps(d, prior_spans)] + exp_spans
        elif prior:
            print(f"  {perf}: covers already baked in with no pristine copy (pre-dates "
                  f"precover) — new spans composite ON TOP; idempotent rebuilds start "
                  f"with this clip's next fresh cover", file=sys.stderr)
            build_src = src
            spans = [d for d in derived if not overlaps(d, prior_spans)] + exp_spans
        else:
            build_src = src
            make_precover = True
            spans = derived + exp_spans
        spans = [x for x in spans if x[1] - x[0] > 1.0 / a.fps]
        if not spans:
            continue
        spans.sort(key=lambda x: x[0])
        missing = [c for _, _, c, _ in spans if not os.path.isfile(c)]
        if missing:
            print(f"  {perf}: cover {missing[0]} missing — skipped", file=sys.stderr)
            continue
        tmp = src + ".covered.tmp.mp4"
        span = end - start
        # Alternate performer / B-roll across the window. The pieces are built in ORDER
        # and concatenated, so total length is preserved exactly — that matters more
        # than it sounds: the assembler asserts the built master against the planned
        # duration to the frame, and a cover that shortened its clip by a hair would
        # surface three stages later as "assembly drift", blaming the cutter.
        # WORK IN WHOLE FRAMES. Each trim is rounded to a frame boundary, so three pieces
        # cut at arbitrary times lose up to a frame each and the composite comes up
        # short — measured: a 14.00s window rebuilt as 13.75s, which the assembler then
        # reports as "assembly drift" naming the cutter. Quantising the boundaries first
        # makes the pieces sum to the window's frame count by construction, and the last
        # piece absorbs any remainder so the total cannot drift at all.
        total_f = round(span * a.fps)
        bounds = []
        for lo, hi, cvr, why in spans:
            bounds.append((max(0, round(lo * a.fps)), min(total_f, round(hi * a.fps)), cvr, why))
        pieces, cursor_f, cov_f, applied = [], 0, 0, []
        for lo_f, hi_f, cvr, why in bounds:
            if hi_f <= cursor_f:
                continue
            if lo_f > cursor_f:
                pieces.append(("perf", cursor_f, lo_f, None))
            lo_c = max(lo_f, cursor_f)
            pieces.append(("broll", lo_c, hi_f, cvr))
            applied.append((lo_c, hi_f, cvr, why))
            cov_f += hi_f - lo_c
            cursor_f = hi_f
        if cursor_f < total_f:
            pieces.append(("perf", cursor_f, total_f, None))
        # a sliver shorter than a frame is not a piece; fold it into its neighbour
        pieces = [(k, s, e, c) for k, s, e, c in pieces if e > s]
        # A PERFORMER SLIVER AGAINST A CUTAWAY IS A FLASH FRAME. A cover that ended 0.29 s
        # before the window's end left seven frames of the take — the model's end-of-clip
        # pose, a close-up with arms wide — between the branch cutaway and the cut to the
        # other performer: "goes funny and quickly goes to Sita" (operator, Baby Ram &
        # Sita v6, 2026-09-02). A performer piece shorter than MIN_PERF_PIECE_S beside a
        # cutaway is given to that cutaway, at either edge of the window or between two.
        min_f = int(round(MIN_PERF_PIECE_S * a.fps))
        folded: list = []
        for idx, (k, s_, e, c) in enumerate(pieces):
            if k == "perf" and e - s_ < min_f:
                if folded and folded[-1][0] == "broll":
                    pk, ps, _, pc = folded[-1]
                    folded[-1] = (pk, ps, e, pc)
                    continue
                if idx + 1 < len(pieces) and pieces[idx + 1][0] == "broll":
                    nk, _, ne, nc = pieces[idx + 1]
                    pieces[idx + 1] = (nk, s_, ne, nc)
                    continue
            folded.append((k, s_, e, c))
        pieces = folded
        assert sum(e - s for _, s, e, _ in pieces) == total_f, "pieces must tile the window"
        # THE CLIP IS SHOWN FROM ITS HEAD, NOT FROM ZERO. The assembler starts each cut at
        # the section's headSec (a fitted take: 0; a no-voice window or a pool clip: the
        # plan's trim), but the pieces above tile the window from clip time 0 — so on a
        # window with a 0.6 s head the cover landed 0.6 s early and the last 0.4 s of it
        # showed as a flash frame between the pool cut and the take (film #3 v2, body
        # 250.58–250.96 s, 2026-09-06). Shift every piece by the head and keep the head
        # itself as untouched performer in front: it is never shown, but the clip keeps
        # its geometry and the assembler's in-point stays right.
        head_f = int(round(float(s.get("headSec") or 0.0) * a.fps))
        if head_f > 0:
            pieces = [(k, s_ + head_f, e + head_f, c) for k, s_, e, c in pieces]
            pieces.insert(0, ("perf", 0, head_f, None))
        # the record and the messages follow the pieces as folded, not the spans as asked
        applied = [(s_, e, c, next((why for lo_f, hi_f, cvr, why in bounds
                                    if cvr == c and lo_f < e and hi_f > s_), "cover"))
                   for k, s_, e, c in pieces if k == "broll"]
        cov_f = sum(e - s_ for k, s_, e, _ in pieces if k == "broll")
        cov = cov_f / a.fps

        # READ THE B-ROLL FROM ITS OWN START, not from the window's offset. Using the
        # window offset would ask a 14.08s cutaway for the span 0.74-14.0s and get
        # 13.26s of it — a piece shorter than the hole it fills, so the concat comes up
        # short and the assembler reports "assembly drift" three stages later, naming
        # the cutter. Refuse up front instead, with the number that is wrong.
        covers = sorted({c for k, _, _, c in pieces if k == "broll"})
        cover_len = {c: float(probe(c) or 0.0) for c in covers}
        # the fold above may widen a hole by up to MIN_PERF_PIECE_S per edge; the B-roll
        # wraps from its own start for that much (b_cursor below), so only a hole longer
        # than the cover by MORE than the fold is a real shortfall
        short_cover = next(
            (c for c in covers if cover_len[c] + 2 * MIN_PERF_PIECE_S < max(
                (e - s_) / a.fps for k, s_, e, cc in pieces
                if k == "broll" and cc == c) - 1e-3), None)
        if short_cover:
            longest = max((e - s_) / a.fps for k, s_, e, cc in pieces
                          if k == "broll" and cc == short_cover)
            print(f"  {perf}: {os.path.basename(short_cover)} is "
                  f"{cover_len[short_cover]:.2f}s but the hole is {longest:.2f}s — "
                  f"render B-roll at least as long as the longest vocal-free stretch, "
                  f"or the film comes up short", file=sys.stderr)
            continue

        if make_precover:
            import shutil
            shutil.copyfile(src, pre)
            build_src = pre
        # THE CLIP KEEPS ITS FULL LENGTH. The pieces tile the WINDOW; a clip longer than its
        # window (a fitted take with a spare tail) came out of here at the window's length,
        # while the selection still recorded the old durationSec — so the assembler's
        # in-point clamp over-read the clip and the film came up 15 frames short, reported
        # as "assembly drift" and blamed on the cutter (Baby Ram & Sita, 2026-09-01). The
        # remainder past the window rides along as a final performer piece, and the
        # selection's durationSec is refreshed from the built file below.
        src_len = float(probe(build_src) or 0.0)                 # probed once; reused below
        shown_f = total_f + head_f                                # head + the tiled window
        clip_f = max(shown_f, int(round(src_len * a.fps)))
        if clip_f > shown_f:
            pieces.append(("perf", shown_f, clip_f, None))
        out_len = clip_f / a.fps
        inputs = covers + [build_src]
        idx_of = {p: n for n, p in enumerate(inputs)}
        audio_have = {n: has_audio(p) for n, p in enumerate(inputs)}
        sil_i = len(inputs)
        parts, vlabels, alabels = [], [], []
        b_cursor = {c: 0.0 for c in covers}
        for n, (kind, lo_f, hi_f, cvr) in enumerate(pieces):
            length = (hi_f - lo_f) / a.fps
            if kind == "broll":
                if b_cursor[cvr] + length > cover_len[cvr]:
                    b_cursor[cvr] = 0.0     # wrap rather than run off the end
                src_idx, t0, t1 = idx_of[cvr], b_cursor[cvr], b_cursor[cvr] + length
                b_cursor[cvr] += length
            else:
                src_idx, t0, t1 = idx_of[build_src], lo_f / a.fps, hi_f / a.fps
            a_idx = src_idx if audio_have[src_idx] else sil_i
            at0, at1 = (t0, t1) if a_idx == src_idx else (0.0, length)   # silence: only the length matters
            parts.append(
                f"[{src_idx}:v]trim=start={t0}:end={t1},setpts=PTS-STARTPTS,"
                f"scale={a.width}:{a.height},fps={a.fps}[v{n}];"
                f"[{a_idx}:a]atrim=start={at0}:end={at1},asetpts=PTS-STARTPTS[a{n}]")
            vlabels.append(f"[v{n}]"); alabels.append(f"[a{n}]")
        n = len(pieces)
        # PAD, THEN CUT TO LENGTH. Trimming and concatenating at frame boundaries still
        # loses frames to ffmpeg's own rounding — arithmetic that tiles the window
        # exactly on paper still produced 13.75s for a 14.00s window. Rather than fight
        # it, clone the last frame past the end and let `-t` cut back to exactly the
        # window: the output length is then correct by construction, whatever the
        # pieces did. A composite even a few frames short reappears three stages later
        # as "assembly drift", naming the cutter.
        graph = (";".join(parts)
                 + ";" + "".join(vlabels) + f"concat=n={n}:v=1:a=0,"
                   "tpad=stop_mode=clone:stop_duration=1[v]"
                 + ";" + "".join(alabels) + f"concat=n={n}:v=0:a=1,apad[aud]")
        silence_in = ([] if all(audio_have.values()) else
                      ["-f", "lavfi", "-t", f"{out_len + 2:.3f}", "-i", "anullsrc=r=44100:cl=stereo"])
        in_args = []
        for p in inputs:
            in_args += ["-i", p]
        run(["ffmpeg", "-v", "error", "-y", *in_args, *silence_in,
             "-filter_complex", graph, "-map", "[v]", "-map", "[aud]", "-t", f"{out_len:.6f}",
             "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p",
             "-c:a", "aac", "-b:a", "192k", tmp])
        os.replace(tmp, src)
        try:
            st = os.stat(src)
            json.dump({"size": st.st_size, "mtime": st.st_mtime, "composite": os.path.basename(src)},
                      open(side, "w", encoding="utf-8"))
        except OSError:
            pass
        head = cov          # what the record and the caller call the covered amount
        where = ", ".join(f"{start + lo_f / a.fps:.1f}-{start + hi_f / a.fps:.1f}s"
                          for lo_f, hi_f, _, _ in applied)
        built = float(probe(src) or 0.0)
        if abs(built - out_len) > 1.5 / a.fps:
            print(f"  {perf}: WARNING composite is {built:.3f}s for a {out_len:.3f}s clip "
                  f"({span:.3f}s window) — the assembler will report this as drift", file=sys.stderr)
        for c in sel.get("clips", []):
            if c.get("id") == perf and c.get("durationSec") is not None:
                # never more than the take's REAL audio: a clip shorter than its window is
                # padded to it here, and reporting the padded length hid the shortfall from
                # the assembler's guard and let the swap carve the record over silence
                c["durationSec"] = round(min(built, src_len), 3)
        print(f"  {perf}: covered {where} ({cov:.1f}s) with "
              f"{', '.join(sorted({os.path.basename(c) for c in covers}))} -> {built:.6f}s")
        # ONE RECORD PER SPAN, in SONG TIME — `word_sync` tests each word
        # against every entry (`any(...)`), so several per clip is the supported shape.
        # Writing a single head-shaped record would tell the lyric gate to ignore the
        # WRONG seconds: the head of the window rather than the middle that was covered,
        # so the covered span would still read as a missing lyric and the untouched
        # opening would be excused.
        # A COMPOSITE IS NOT A FULL-WINDOW PERFORMANCE SAMPLE. The original take was
        # measured before this stage. Once even a short silent stretch is replaced,
        # whole-window correlation measures the edit and can push a proven take below
        # threshold (W03 fell from 0.80 to 0.52 after a 2.2s city cutaway). The exact
        # covered spans are recorded below for word-level QA, so exempt this composite
        # from the assembler's incompatible full-window check.
        if should_exempt_from_full_window_sync(cov, span):
            s["lipSyncExempt"] = True
            if not designed_exempt:               # never re-label a designed no-voice shot as ours
                s["lipSyncExemptBy"] = "cover"    # ours to clear when no record is left for it
            print(f"  {perf}: {cov / span:.0%} cutaway — exempt from full-window "
                  f"lip-sync; uncovered words remain checked against cutaways.json")

        recorded = [c for c in recorded if c.get("clip") != perf]     # re-run replaces
        for lo_f, hi_f, cvr, why in applied:
            recorded.append({
                "clip": perf,
                "startSec": round(start + lo_f / a.fps, 3),
                "endSec": round(start + hi_f / a.fps, 3),
                "broll": os.path.splitext(os.path.basename(cvr))[0],
                "why": why,
            })
        done += 1

    if recorded:
        with open(record_path, "w", encoding="utf-8") as handle:
            json.dump({
                "_comment": "Spans where a CUTAWAY intentionally replaces the performer. "
                            "The lyric-coverage gate MUST exclude these: a covered second "
                            "has no vocal in the clip by design, so counting it as a "
                            "missing word turns every deliberate edit into a false "
                            "WRONG-LYRIC and the gate starts crying wolf. Pass this to "
                            "word_sync.py --cutaways.",
                "cutaways": sorted(recorded, key=lambda c: c.get("startSec", 0)),
            }, handle, indent=1)
    if recorded or cleared:
        # a cleared exemption must reach disk even when nothing was covered this run
        json.dump(sel, open(a.selection, "w", encoding="utf-8"), indent=1)
    print(f"  recorded {len(recorded)} cutaway span(s) -> {record_path}")
    if not done:
        print("  no window has a silent head long enough to cover")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
