#!/usr/bin/env python3
"""make_plan.py — author the free-lane plan.json that explore_queue.py consumes.

THE MISSING HALF. `explore_queue.py` is a supervisor and documents the plan.json
schema it reads, but nothing in this skill WROTE one — that was hand-written per
film, which is how a proven 0-credit path stays unreproducible. route-economics.md
calls this lane the best sync of any route and free; it should not need a private
script in a project folder to reach it.

Given a hook window and the drawn styles, this cuts that window into clips, builds
one black-frame voice video per clip, and emits the plan.

  make_plan.py --project <dir> --styles <styles.json> --drawn <drawn.json>
               --hook <hook.json> --identity-ref <portrait.png>
               [--clip-seconds 8] [--aspect 9:16] [--resolution 720p]
               [--sections <sections.json>] [--out <plan.json>]

WHY A UNIFORM GRID, and not transcript segment boundaries: the boundary is a
PICTURE cut laid over one continuous audio track, so landing mid-word is ordinary
music-video grammar rather than a defect. Sync does not depend on it — each clip's
mouth is driven by its OWN voiceRef, a slice of the same timeline — so a clip is
correct inside its window wherever that window happens to start. Aligning to
segments would only buy tidier prose in the log.

--clip-seconds is the ROUTE's cap, not a preference: seedance_2_5 takes 4-20s and
<= 10 s, and duration:8 is the value the 0.98-correlation result was measured at.

--sections is OPTIONAL and purely editorial: a list of
    [{"start": 0, "end": 23, "styleId": "bus-shelter-rain", "label": "hook-1"}, ...]
mapping song time to a look, so a refrain can keep one home and a verse can have
its own. Without it the drawn styles are dealt round-robin, which is a reasonable
film and a terrible one to argue with; author sections when the cut matters.

Both refs ride in the batch manifest's characterRefs and are split by EXTENSION
downstream: the still becomes imageAssetId1 (@IMG_1), the voice video becomes
videoAssetId (@VID_1). On a route with no audio-reference field the track reaches
the model ONLY as the soundtrack of a video, which is where this trick came from;
seedance-direct additionally accepts it as a real audio reference.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))   # a script loaded by path (tests) still finds its siblings
import raplib  # noqa: E402
import math
import os
import re
import subprocess
import sys


# CLIP LENGTH IS PER ROUTE, and the cap that was here was the WRONG route's.
#
# It read 10s, described in a comment as "the free explore lane" — that was Runway's
# explore limit, and it was applied to every route. Runway has been gone since
# 2026-08-15 (account suspended 08-10), but its number outlived it: a film on
# Higgsfield seedance_2_5, whose engine table gives (4, 20) with the comment "a 20s
# render beats no render", was refused above 10s. On a 112-second song that is
# FOURTEEN renders instead of SIX on a single-slot lane — about six hours against two
# and a half. The stale constant cost more than the dead provider ever did.
#
# Source of truth: engines/seedance-direct/adapter.py MODEL_DURATION_RANGE. Whole
# seconds only — a 7.56s request once rendered 5s, a picture two and a half seconds
# shorter than its own audio, found at assembly.
MIN_CLIP = 4
DEFAULT_MAX_CLIP = 10          # conservative for a route we do not have a number for
ROUTE_MAX_CLIP = {
    "seedance-direct": 20,     # seedance_2_5 (4, 20) — WITHOUT a voice reference
    "dreamina-useapi": 15,     # seedance-2.0 family (4, 15)
}

# A LIP-SYNCED window is capped lower, and the provider only says so at submit time:
#
#   HTTP 422 POST /jobs/v2/seedance_2_5
#   {"detail": "Seedance 2.5 reference audio clips can be at most 30 seconds in total"}
#
# The voice rides as a black-frame video AND is attached on the /audio channel (the
# video is kept as a fallback), so a 20s window spends 40s of that 30s budget and is
# refused. At 8s it was 16s and nobody noticed the ceiling existed. Measured on a live
# film 2026-08-15: 20s refused, and the arithmetic only works at 15s or below.
#
# 15 exactly hits the limit, so the cap is 14 — a ceiling with no margin is a ceiling
# you discover again on the next film.
SYNCED_AUDIO_BUDGET_S = 30
SYNCED_MAX_CLIP = 14


def max_clip_for(route: str, synced: bool = False) -> int:
    """The longest whole-second clip this route will actually accept.

    `synced` means a voice reference is attached, which spends the provider's audio
    budget twice over — see SYNCED_MAX_CLIP.
    """
    cap = ROUTE_MAX_CLIP.get(route, DEFAULT_MAX_CLIP)
    return min(cap, SYNCED_MAX_CLIP) if synced else cap
VALID_NOTE = (f"valid clip lengths are whole seconds from {MIN_CLIP} up to the route's "
              f"cap ({', '.join(f'{r} {n}s' for r, n in sorted(ROUTE_MAX_CLIP.items()))}).")


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


def cite(prompt: str, seconds: float) -> str:
    """ADD the asset citations to the composed prose; never substitute them for it.

    Replacing the visual descriptor WITH '@IMG_1' is a logged identity-drift cause:
    these models lock a face from the prose and treat the tag as a pointer, so a
    prompt that carries only the tag has nothing to lock onto.
    """
    out = prompt.replace("Image 1 is the protagonist portrait",
                         "Image 1 (@IMG_1) is the protagonist portrait", 1)
    # A `both` shot carries a second still; same rule, same exact-match rewrite.
    out = out.replace("Image 2 is the second performer's portrait",
                      "Image 2 (@IMG_2) is the second performer's portrait", 1)
    # The composed prose carries ONE duration for every style, but the last window of
    # a track is short. Rewrite the number as well as adding the tag, so the prompt
    # never claims 8 seconds over a 7.56s voice slice.
    # `<<<audio_1>>>`, INLINE, in the sentence that explains what the track is for.
    #
    # This said `@VID_1` — right when the voice rode the VIDEO channel as a
    # black-frame clip. The voice moved to the AUDIO channel (upload_audio, cited
    # `<<<audio_1>>>`) and this tag never followed, so the prose pointed at a
    # channel nothing was on while the real citation got appended, unexplained,
    # after "Multiple cuts." The lane's own measurement of that difference is
    # 0.261 sync against 0.901 for the same window cited inline.
    return re.sub(r"Audio 1 is the [\d.]+-second rap track",
                  f"Audio 1 (<<<audio_1>>>) is the {round(seconds, 2):g}-second rap track",
                  out, count=1)


_SHA_CACHE: dict[str, str] = {}


def _sha256_file(path: str) -> str:
    """sha256 of a file's bytes, memoised per path (one hook.wav, many windows)."""
    key = os.path.abspath(path)
    if key not in _SHA_CACHE:
        h = hashlib.sha256()
        with open(path, "rb") as fh:
            for chunk in iter(lambda: fh.read(1 << 20), b""):
                h.update(chunk)
        _SHA_CACHE[key] = h.hexdigest()
    return _SHA_CACHE[key]


def probe_seconds(path: str) -> float:
    """Duration of an existing media file, 0.0 if it cannot be read."""
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
                        "-of", "csv=p=0", path], capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except ValueError:
        return 0.0


def build_voice(src_wav: str, start: float, dur: float, dest: str, ffmpeg: str,
                width: int, height: int, mute_head: float = 0.0, mute_tail: float = 0.0,
                source: str = "") -> None:
    """A black frame carrying this window's audio.

    IDEMPOTENT ON THE PARAMETERS, not on the path. It used to return early whenever the
    file existed, whatever length it was — so changing the window size from 8s to 20s
    left four slices at 8 seconds while the plan, the prompt and the submitted render
    all said 20. A 20-second clip driven by an 8-second voice reference has NOTHING to
    lip-sync to for its last twelve seconds: the model mouths silence or invents words,
    and no gate downstream can tell you why, because every artifact agrees with every
    other one. Caught mid-render, with the wrong reference already submitted.

    Third instance of this shape in one session, after the whisper cache keyed on a
    filename and the adapter skipping a download because an mp4 was already there. The
    rule: a cache key must carry everything that changes the OUTPUT.

    FOURTH instance (2026-08-22): the length check above passed a slice cut from the
    WRONG START. A re-plan moved every window, the files were all still the right
    length, so the old audio stayed — w08 correlated 1.00 with the song at its old
    94.5 s and -0.04 at its planned 81.84 s, and the render lip-synced to the wrong
    bar. The key is now the content: a sidecar `<dest>.json` records the song's
    sha256, the start and the length, and the slice is rebuilt whenever the sidecar
    is missing or any field differs.
    """
    want = {"songSha": _sha256_file(src_wav), "startSec": round(float(start), 3),
            "seconds": round(float(dur), 3)}
    if source:
        # WHICH AUDIO THE MODEL HEARS. `mix` = hook.wav, the whole track; `stem` = the
        # Demucs vocal stem. The published Seedance guidance: "dense mixes give the model
        # no clock" — three draws of one window sang the right words at the wrong rhythm
        # against the mix (2026-08-29). songSha already keys on the bytes; the name makes
        # a rebuild's reason readable in the log and in the sidecar.
        want["source"] = source
    if mute_head > 0:
        # THE REFERENCE MUST NOT CARRY A VOCAL BEFORE THIS FACE'S FIRST WORD. With the
        # previous line's tail audible at the top of the slice, the model followed the
        # first vocal it heard and started the verse at the clip's first frame — both
        # w06 draws early by exactly the lead-in, 0.84/0.89 correlation (2026-08-23).
        # "Lips closed" in the prompt did not stop it; silence in the reference does.
        want["muteHead"] = round(float(mute_head), 3)
    if mute_tail > 0:
        # ... and after the last word this take is asked to sing: a line that begins in
        # the slack tail and gets cut off ("Sunehri chhat—" at 9.3 s of a 10 s slice) is
        # not this take's to shape. The operator heard the cut-off and asked (2026-08-23).
        want["muteTail"] = round(float(mute_tail), 3)
    side = dest + ".json"
    if os.path.isfile(dest) and os.path.getsize(dest) > 0:
        have_side = None
        if os.path.isfile(side):
            try:
                have_side = json.load(open(side, encoding="utf-8"))
            except (OSError, ValueError):
                have_side = None
        have = probe_seconds(dest)
        # One frame of tolerance: ffmpeg lands a 20.000s request at 20.02s or so.
        if have_side == want and have and abs(have - dur) <= 0.1:
            return
        if have_side is None:
            why = "no sidecar says what it was cut from"
        elif have_side != want:
            why = (f"it was cut at {have_side.get('startSec')}s for {have_side.get('seconds')}s"
                   f"{'' if have_side.get('songSha') == want['songSha'] else ' of a different song'}"
                   f", this window is {want['startSec']}s for {want['seconds']}s")
        else:
            why = f"it is {have:.2f}s but this window is {dur:.2f}s"
        print(f"  rebuilding {os.path.basename(dest)}: {why}", file=sys.stderr)
    cmd = [ffmpeg, "-y", "-v", "error", "-nostdin",
           "-f", "lavfi", "-t", f"{dur:.3f}", "-i", f"color=c=black:s={width}x{height}:r=24",
           "-ss", f"{start:.3f}", "-t", f"{dur:.3f}", "-i", src_wav,
           "-map", "0:v", "-map", "1:a",
           # apad: a slice that reaches past the song's end (the last window's render
           # rounds up) is padded with silence to the render length, not cut short —
           # plan_coherence #2 refused a 10.16 s slice for a 12 s render (2026-08-23).
           "-af", ",".join(
               ([f"volume=enable='lt(t,{mute_head:.3f})':volume=0"] if mute_head > 0 else [])
               + ([f"volume=enable='gte(t,{mute_tail:.3f})':volume=0"] if mute_tail > 0 else [])
               + ["apad"]),
           "-t", f"{dur:.3f}",
           "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p",
           "-c:a", "aac", "-b:a", "192k", dest]
    if os.path.isfile(side):
        os.remove(side)          # never let a sidecar outlive a failed build
    p = subprocess.run(cmd, stderr=subprocess.PIPE)
    if p.returncode:
        die(f"voiceRef failed for {dest}:\n{p.stderr.decode('utf-8', 'replace')[:400]}")
    with open(side, "w", encoding="utf-8") as fh:
        json.dump(want, fh)


SYNC_MIN = 0.60          # mirrors check_sync.py
MAX_HOLD = 0.60


def build_redo(project: str, report_path: str, plan_path: str, out_path: str,
               hook_wav: str, ffmpeg: str, extra_ids: tuple = (),
               refresh_prompts: str = "") -> None:
    """Emit a re-render plan for the windows check_sync says are unusable.

    Only TWO conditions warrant burning queue time again:
      * corr < SYNC_MIN  — the clip's mouth is on different words. Nothing but a
        re-render fixes that, and a straight re-roll of the same prompt and refs
        fixed 4 of 4 in practice: the fault is the model's, not the setup's.
      * gap > MAX_HOLD   — the clip is too short to fill its window, so the film
        would need a frozen frame to cover the difference.

    An OFFSET is deliberately not on that list. "synced but -425 ms out" means the
    content is right and the cut point is wrong; check_sync's own advice is to move
    the cut. Re-rendering those would have wasted 9 of 24 windows on the film this
    was built for.

    `extra_ids` is the third door, and it exists because those two conditions are
    both about AUDIO. check_sync measures whether a mouth is on the right words; it
    cannot see that a clip came back as an empty cityscape with nobody in it, or
    with the performer a speck on the horizon. Those are real defects, they are
    found by WATCHING, and until now there was no way to ask for them again — the
    operator had to hand-build a redo plan, which is the manual step this whole
    script exists to remove.

    `refresh_prompts` re-reads a rebuilt prompts.json and swaps each window's
    prompt for its current one, so a redo can pick up a corrected register. Without
    it a re-render faithfully reproduces the defect: same prompt, same result. That
    is the "clear stale outputs before any re-render" rule in prompt form.

    Writes the plan and stops. It never submits — the operator reviews what is
    about to be re-rendered first.
    """
    plan = json.load(open(plan_path, encoding="utf-8"))
    jobs = plan.get("jobs", [])
    # A sync report is optional now: --redo-ids alone is a legitimate request.
    report = json.load(open(report_path, encoding="utf-8")) if report_path else []

    picked, skipped = [], []
    for row in report:
        idx = row.get("segment")
        if not isinstance(idx, int) or idx >= len(jobs):
            continue
        corr, gap = row.get("corr"), row.get("gap") or 0.0
        why = None
        if isinstance(corr, (int, float)) and corr < SYNC_MIN:
            why = f"corr {corr:.2f} — mouth on different words"
        elif gap > MAX_HOLD:
            why = f"gap {gap:.2f}s — clip too short to fill the window"
        elif row.get("issues"):
            skipped.append((jobs[idx]["id"], row["issues"][0][:58]))
            continue
        if why:
            picked.append((idx, why))

    # Operator-named windows, deduped against whatever the gate already picked so a
    # window failing BOTH sync and framing is re-rendered once, not twice.
    already = {i for i, _ in picked}
    by_id = {j["id"]: n for n, j in enumerate(jobs)}
    for wid in extra_ids:
        if wid not in by_id:
            die(f"--redo-ids: no window '{wid}' in {plan_path}. "
                f"Known: {', '.join(list(by_id)[:8])}…")
        if by_id[wid] not in already:
            picked.append((by_id[wid], "operator-named — watched and rejected"))
            already.add(by_id[wid])
    picked.sort()

    # Swap in freshly composed prompts so the redo picks up a corrected register.
    if refresh_prompts:
        fresh = json.load(open(refresh_prompts, encoding="utf-8")).get("prompts", [])
        by_style = {p["id"]: p["prompt"] for p in fresh}
        changed = 0
        for idx, _ in picked:
            new = by_style.get(jobs[idx].get("styleId"))
            if new and new != jobs[idx].get("prompt"):
                jobs[idx] = dict(jobs[idx], prompt=cite(new, jobs[idx]["seconds"]))
                changed += 1
        print(f"make_plan --redo-from: refreshed {changed}/{len(picked)} prompt(s) "
              f"from {refresh_prompts}", file=sys.stderr)

    if not picked:
        print("make_plan --redo-from: nothing needs re-rendering.", file=sys.stderr)
        for wid, note in skipped:
            print(f"  {wid}  left alone: {note}", file=sys.stderr)
        return

    build = os.path.join(project, "build")
    voice_dir = os.path.join(build, "voice")
    redo_jobs = []
    print(f"make_plan --redo-from: {len(picked)} window(s) need re-rendering:", file=sys.stderr)
    for idx, why in picked:
        job = dict(jobs[idx])
        job["id"] = f"{job['id']}r"
        # The window is unchanged, so its voice reference already exists and is
        # correct; rebuild only if it has gone missing.
        voice = os.path.join(voice_dir, f"{job['id']}.mp4")
        if not os.path.isfile(job.get("voiceRef", "")):
            build_voice(plan.get("voiceWav") or hook_wav, job["startSec"], job["seconds"], voice,
                        ffmpeg, 720, 1280, source=plan.get("voiceSource") or "")
            job["voiceRef"] = os.path.abspath(voice)
        redo_jobs.append(job)
        print(f"  {job['id']:<6} {why}", file=sys.stderr)
    for wid, note in skipped:
        print(f"  {wid:<6} left alone: {note}", file=sys.stderr)

    redo = dict(plan)
    redo["jobs"] = redo_jobs
    redo["queueDir"] = os.path.join(build, "queue", "redo")
    with open(out_path, "w", encoding="utf-8") as fh:
        json.dump(redo, fh, indent=2)
        fh.write("\n")
    print(f"\n  -> {out_path}\n\n  submit with:\n"
          f"    PLAN={out_path} {build}/run-queue.sh --max-minutes 1440\n"
          f"  (nothing has been submitted)", file=sys.stderr)


# --- per-window vocal direction -----------------------------------------------------
# THE PROMPT MUST SAY WHAT THE AUDIO DOES. Prompts are composed per STYLE, so every
# window of a style carried the same "rapping directly to camera, mouth shaping the
# lyrics" for its whole length — and a window that is mostly instrumental got a vocal
# invented to fill it (operator, 2026-08-22: "W01 has not much vocals and you're telling
# it to do a rap video, so it's making it up"). vocal_brief.py says, per window, which
# lines are sung when and by whom; this rewrites the audio sentence to follow it, and a
# window with (almost) no words is sent with NO voice reference at all.
# THE LYRIC LANGUAGE COMES FROM THE PACK. This line said "Hinglish words" for every
# film on the lane — a leftover from the couple MV that an English song then shipped
# with in all 13 sung windows (2026-08-29, "Smooth Like That"). The prompt names the
# language so the model shapes the right mouth; the pack's LYRIC_LANGUAGE is the truth.
LYRIC_LANGUAGE = os.environ.get("LYRIC_LANGUAGE", "").strip() or "English"
_PRON = {"he": ("he", "his", "He", "him"), "she": ("she", "her", "She", "her"), "they": ("they", "their", "They", "them")}


def _direction(brief: dict, subj: str, poss: str, gender: str, both: bool, obj: str = "him",
               timestamps: bool = True, names: dict | None = None) -> tuple[str, bool]:
    """(sentence, any_mouth) — the per-window lip-sync script in prose.

    ONE CLOCK OR TWO. With `timestamps` (today's text) every part is prefixed by its
    window-relative span, "0.1–5.8s the lead voice sings …". The published Seedance
    guidance is explicit: when the audio is the clock, "avoid a second timing system,
    such as a timestamp list" — and on Smooth Like That three draws of w11 sang the
    right words at the wrong rhythm with exactly that list in the prompt (2026-08-29).
    `timestamps=False` keeps every quoted line, in order, and every lips-closed rule,
    and says nothing about seconds: the track is the only clock. Same anchors either
    way (plan_coherence #9's literal sits around this text; #13 splits it on ";")."""
    secs = brief["seconds"]
    parts, t, any_mouth = [], 0.0, False
    # WHOSE VOICE, IN WORDS. male/female name themselves; a performer letter (a/b — two
    # singers of one gender, Baby Yeh Dosti) is worded by the performer's NAME
    # (--performer-names), never as "the a voice".
    names = names or {}

    def vname(w: str) -> str:
        return f"{names[w]}'s voice" if w in names else f"the {w} voice"

    def at(sp) -> str:
        return f"{sp['start']:.1f}–{sp['end']:.1f}s " if timestamps else ""

    for sp in brief["spans"]:
        if sp["start"] - t >= 0.8:
            if timestamps:
                parts.append(f"{t:.1f}–{sp['start']:.1f}s nothing is sung — lips closed")
            elif t == 0.0:
                parts.append(f"the shot opens on an instrumental — lips closed until {poss} first line")
            else:
                parts.append("a short instrumental pause — lips closed")
        who = sp["who"]
        if sp.get("partialHead"):
            # the end of a line that began before this window: not this take's to sing
            parts.append(f"{at(sp)}the previous line is ending on the track — lips closed, no words"
                         + ("" if timestamps else f", until {poss} first line"))
            t = sp["end"]
            continue
        if sp.get("partialTail"):
            # the next line begins as the shot ends: no line to shape here
            parts.append(f"{at(sp)}the next line begins on the track as the shot ends — no new "
                         f"words, the take simply ends")
            t = sp["end"]
            continue
        mine = who in ("both", "duet", "lead") or who == gender or both
        if mine:
            any_mouth = True
            voice = ("both voices sing" if who == "both" else "the two voices sing" if who == "duet"
                     else f"{vname(who)} {'raps' if sp['how'] == 'rapped' else 'sings'}")
            if not both and who in ("both", "duet"):
                # A UNISON LINE IN A SOLO SHOT IS THIS ONE VOICE. Telling a solo window
                # "both voices sing" had the model render a second, male voice under
                # Sita's face, and vocal-swap carried it into the film (w05, 1:02-1:05,
                # Baby Ram & Sita v7, 2026-09-02). The other voice is on the record,
                # not in this shot.
                voice = (f"{subj} sing{'s' if subj != 'they' else ''} the line alone — it is a "
                         f"{'unison' if who == 'both' else 'duet'} line on the record, but the other "
                         f"voice is not in this shot, so ONE voice, {poss} own")
            if both and who in ("male", "female", "a", "b"):
                # A solo line inside a two-performer shot: ONE mouth moves. "their mouths"
                # here had both faces mouthing a line only one voice sings.
                if who in ("a", "b"):
                    # two boys: "his … his" names nobody — the performers' names do
                    mine_n = names.get(who, f"performer {who.upper()}")
                    other_n = names.get("b" if who == "a" else "a", "the other performer")
                    his, hers = f"{mine_n}'s", f"{other_n}'s"
                else:
                    his, hers = ("his", "hers") if who == "male" else ("her", "his")
                parts.append(f"{at(sp)}{voice} \u201c{sp['text']}\u201d — "
                             f"only {his} mouth shapes the words; {hers} stays closed")
                t = max(t, sp["end"])
                continue
            mouth = ("their mouths shape" if both else f"{poss} mouth shapes")
            parts.append(f"{at(sp)}{voice} \u201c{sp['text']}\u201d — "
                         f"{mouth} exactly these {LYRIC_LANGUAGE} words, {sp['how']}")
        else:
            parts.append(f"{at(sp)}{vname(who)} sings \u201c{sp['text']}\u201d — "
                         f"that is not {obj}: lips closed, listening, moving to it")
        t = max(t, sp["end"])
    if secs - t >= 0.8:
        parts.append(f"{t:.1f}–{secs:.1f}s nothing is sung — lips closed" if timestamps
                     else "after the last line nothing is sung — lips closed to the end")
    # "; then" reads as a sequence without naming a second; "; " alone is what the
    # timestamped script always used (and what plan_coherence #13 splits on — both work).
    return ("; " if timestamps else "; then ").join(parts), any_mouth


MUTE_HEAD_MIN_S = 0.3   # a lead-in shorter than this landed on the bar (w02/w03/w04 at 0.0-0.24 s)
ONSET_LEAD_S = 0.08     # open this much before the first word: the consonant's attack, not a lead-in
# THE RENDER IS AS LONG AS THE SINGING. The model spreads a performance across the whole
# clip it is asked for: a 5.0 s line rendered as 7 s came back sung 1.35x slow, on every
# window of a film (New Era, 2026-08-30; arm A: trimming the audio alone moved it only to
# 1.24 — it fills the VIDEO length; the one window with 0.14 s of slack sang on speed).
# The vendor's guide says the same: "match your generation duration to your audio clip's
# length … the model might compress or stretch visual events". So a window renders at
# ceil(sung + the two pads), never more: HEAD_PAD_S of silence to open the mouth from rest,
# TAIL_PAD_S to close it, and whatever the whole-second round-up leaves is split evenly.
# The instrumental gap to the next line is no longer inside the performance clip — it is a
# silent stretch the cover stage fills from the window's own world.
HEAD_PAD_S = 0.5     # a deliberate lead-in: the mouth starts from rest and the cut point is clean
                     # (operator, 2026-08-31: "add silence at the beginning so the model has time")
TAIL_PAD_S = 0.3
GAP_TO_BROLL_S = 1.0     # a gap after the last word this long or longer is a pool section, not padding
# A SHORT LINE SINGS SLOW AND RUNS OFF ITS CLIP. New Era's only two windows that sang past
# their last frame were the two under 6 s of singing (w03/w06: 4.7 s lines in 6 s clips,
# sung 1.18x). A short single line merges with its neighbour when the gap is short and the
# cap allows (backward first, then forward); one that cannot merge is given the stretch
# the model will take (SHORT_LINE_RATE) so its last word is still inside the clip, and
# fit_takes brings it back to tempo.
MIN_SUNG_S = float(os.environ.get("MIN_SUNG_S", "6.0"))
SHORT_LINE_RATE = float(os.environ.get("SHORT_LINE_RATE", "1.2"))


def plan_constants(max_clip: float, scene_seconds: float) -> dict:
    """THE PLAN CARRIES THE CONSTANTS IT WAS BUILT WITH. plan_coherence once read
    MIN_SUNG_S / SHORT_LINE_RATE from the environment on its own and rounded a margined
    render to-nearest where this module rounds up — two of the author's own constants
    half a second apart refused three bridge lines (2026-09-02). A gate that reads the
    producer's recorded intent is an independent check; one that re-reads the same
    environment is not."""
    return {
        "sungLock": os.environ.get("SUNG_LOCK", "1") != "0",
        "minSungS": MIN_SUNG_S, "shortLineRate": SHORT_LINE_RATE,
        "headPadS": HEAD_PAD_S, "tailPadS": TAIL_PAD_S, "onsetLeadS": ONSET_LEAD_S,
        "muteHeadMinS": MUTE_HEAD_MIN_S, "gapToBrollS": GAP_TO_BROLL_S,
        "minClip": MIN_CLIP, "maxClip": max_clip, "sceneSeconds": scene_seconds,
        "roundingMode": "ceil-with-margin",
        "audioMode": (os.environ.get("AUDIO_MODE") or "record").strip(),
    }

def _landed_for(build: str, i: int, w: dict) -> bool:
    """A clip on disk pins a window's geometry ONLY if it was rendered for this window.
    A re-plan after a finished render found all fifteen old clips and kept every old
    (padded) window untouched (New Era, 2026-08-31). The live-job record says what the
    clip was cut for; no record, or a different start/length, is not "landed here"."""
    clip = os.path.join(build, "queue", "explore", "clips", f"w{i:02d}.mp4")
    if not os.path.isfile(clip):
        return False
    rec_path = os.path.join(build, "queue", "explore", f"w{i:02d}-live-job.json")
    try:
        rec = json.load(open(rec_path, encoding="utf-8"))
    except (OSError, ValueError):
        return True                      # no record: the old rule (a clip is a clip)
    try:
        same_start = abs(float(rec.get("startSec")) - float(w.get("startSec") or w.get("start"))) < 0.05
        same_len = abs(float(rec.get("seconds")) - float(w.get("seconds"))) < 0.05
    except (TypeError, ValueError):
        return True
    return same_start and same_len


def _sung_inside(w: dict, lines: list[dict]) -> float:
    """Seconds of singing inside a window, from its open to the last placed word — the
    number the sizing below is built on."""
    w_start, w_end = max(0.0, float(w["start"])), float(w["end"])
    mine = [ln for ln in lines if w_start - 0.05 <= float(ln["start"]) < w_end - 0.05]
    if not mine:
        return 0.0
    sung_end = max(float(ln.get("end") or ln["start"]) for ln in mine)
    return round(max(0.0, min(sung_end, w_end) - w_start), 3)


def _name_stale_geometry(i: int, w: dict, lines: list[dict], max_clip: float) -> None:
    """A LANDED clip pins its window — and that protection went silent (film #3, 2026-09-04).

    w00 rendered 7 s for 4.4 s of words, stretched 1.65x; the planner was fixed to size
    it 5 s, the re-run reported the SAME numbers, and the operator read it as "the fix
    did nothing": the landed clip had frozen the geometry, the fix reached nothing, and
    nothing said so. Two more re-runs were spent finding that out (ledger rows 15, 19).

    The clip still pins the window (a landed take is a landed take). But when the
    window's SUNG geometry no longer fits the clip it was cut for — the sizing the
    non-landed path would choose differs by a whole second or more — the condition is
    NAMED on the window and on stderr: `geometryStale`, with the two shapes and the
    two commands that re-render it. A named condition instead of a silent freeze.
    """
    sung = _sung_inside(w, lines)
    jid = f"w{i:02d}"
    if sung <= 0:
        # Every placed line has left the window (a re-plan moved the sheet, or the
        # brief lost the line): that is stale geometry too, and the loudest kind —
        # a landed take singing words the plan no longer places here.
        if w.get("sungSec"):
            msg = (f"{jid}: landed clip is {int(round(float(w.get('seconds') or 0)))} s, but no placed line "
                   f"lies inside the window any more (it sang {float(w['sungSec']):.2f} s) — the clip pins "
                   f"the geometry; re-plan or re-render: python3 replace_window.py --windows {jid} && "
                   f"make-rap-mv.sh ... --from plan")
            w["geometryStale"] = {"landedSeconds": int(round(float(w.get("seconds") or 0))), "wouldSeconds": None,
                                  "sungSec": 0.0, "wasSungSec": w.get("sungSec"), "message": msg}
            print(f"  GEOMETRY STALE — {msg}", file=sys.stderr)
        return
    would = max(int(math.ceil(sung + 0.1 - 1e-6)), int(round(sung + HEAD_PAD_S + TAIL_PAD_S)))
    would = max(MIN_CLIP, min(would, int(max_clip)))
    have = int(round(float(w.get("seconds") or 0)))
    was_sung = w.get("sungSec")
    moved = abs(would - have) >= 1 or (was_sung is not None and abs(float(was_sung) - sung) >= 0.5)
    if not moved:
        w.pop("geometryStale", None)
        return
    msg = (f"{jid}: landed clip is {have} s for a window now sized {would} s "
           f"({sung:.2f} s sung{'' if was_sung is None else f', was {float(was_sung):.2f} s'}) — "
           f"the clip pins the geometry, the planner change reached nothing. To re-render: "
           f"python3 replace_window.py --windows {jid} && make-rap-mv.sh ... --from plan")
    w["geometryStale"] = {"landedSeconds": have, "wouldSeconds": would, "sungSec": sung,
                          "wasSungSec": was_sung, "message": msg}
    print(f"  GEOMETRY STALE — {msg}", file=sys.stderr)


def exact_onsets(explicit: list[dict], brief: dict, build: str, slack_tail: float, max_clip: float) -> list[dict]:
    """Move each un-rendered phrase window to open on its first line's word, and its
    predecessor to close there. Geometry (render seconds, trim, tail) is re-derived:
    covered = next start - start; seconds = ceil(covered + slack_tail) <= max_clip;
    tailSec = seconds - covered; trimStartSec = 0 (no head slack: the window opens on
    the word, so the model starts on time by construction)."""
    # ad-libs on the sheet ("(Dav!) (Amisha!)") are sung and start lines too
    lines = [ln for ln in brief.get("lines", []) if ln.get("start") is not None]
    onsets = sorted(float(ln["start"]) for ln in lines)
    wins = [dict(w) for w in explicit]
    n = len(wins)
    landed = [_landed_for(build, i, w) for i, w in enumerate(wins)]
    # 1. starts: a phrase window that is not landed opens on the first onset inside
    #    [start - 0.5, start + 1.5) — the line it was cut for — unless its predecessor is
    #    landed (then it starts where that clip ends, as today).
    for i, w in enumerate(wins):
        if landed[i] or w.get("kind", "phrase") == "intro":
            continue
        if i > 0 and landed[i - 1]:
            continue
        s0 = float(w["startSec"]) + float(w.get("trimStartSec") or 0.0)
        cand = [o for o in onsets if s0 - 0.5 <= o < s0 + 1.5]
        if cand:
            w["start"] = round(cand[0] - ONSET_LEAD_S, 3)
    # 2. ends tile: each window closes where the next opens; the last keeps the song end
    for i in range(n - 1):
        wins[i]["end"] = wins[i + 1]["start"]
    # 2b. A STRANDED SHORT LINE JOINS THE WINDOW BEFORE IT. Phrase windows end at the
    #     next line's START, so a song's last line always lands alone — and a 2.7 s line
    #     in a MIN_CLIP (4 s) render is padded 1.47x, the defect this whole function now
    #     exists to prevent (New Era w07, 2026-08-31). Sized by the singing, the previous
    #     window can usually take it: merge when its sung span + this line + the pads fit
    #     the cap and neither window has landed.
    def _sung_span(a: float, b: float) -> float:
        mine = [ln for ln in lines if a - 0.05 <= float(ln["start"]) < b - 0.05]
        end = max((float(ln.get("end") or ln["start"]) for ln in mine), default=a)
        return min(end, b) - a
    # A MERGE NEVER CROSSES A CHANGE OF VOICE. line_windows cuts the boy's line from the
    # girl's at the handover (43-48 s / 48-53 s); the forward merge below joined them
    # back because it only asked about the gap and the cap — and his face sang her line
    # for 4.6 s, and under vocal-swap his VOICE did (Baby Ram & Sita w04, 2026-09-01).
    # male/female must agree across the merge; both/duet/lead ride with either voice.
    def _one_voice(*groups) -> bool:
        solo = {ln.get("who") for g in groups for ln in g if ln.get("who") in ("male", "female", "a", "b")}
        return len(solo) <= 1
    # From the FIRST window: the loop once began at the second, so a short opening line
    # was never examined and shipped without its margin.
    k = 0
    while k < len(wins):
        w = wins[k]
        prev = wins[k - 1] if k > 0 else None
        if landed[k] or (prev is not None and landed[k - 1]) or w.get("kind", "phrase") == "intro":
            k += 1
            continue
        ws, we = max(0.0, float(w["start"])), float(w["end"])
        own = [ln for ln in lines if ws - 0.05 <= float(ln["start"]) < we - 0.05]
        if len(own) != 1 or _sung_span(ws, we) >= MIN_SUNG_S:
            k += 1
            continue
        # ... and only across a SHORT gap: joining a line to a window across seconds
        # of instrumental would put that instrumental back inside the render.
        if prev is not None:
            prev_start = max(0.0, float(prev["start"]))
            prev_lines = [ln for ln in lines if prev_start - 0.05 <= float(ln["start"]) < ws - 0.05]
            gap_between = float(own[0]["start"]) - (prev_start + _sung_span(prev_start, ws))
            merged = _sung_span(prev_start, we)
            if (merged > 0 and gap_between < GAP_TO_BROLL_S and merged + HEAD_PAD_S + TAIL_PAD_S <= max_clip
                    and _one_voice(prev_lines, own)):
                prev["end"] = we
                del wins[k]
                del landed[k]
                continue
        # backward did not fit: try FORWARD (the short line takes the next window's lines)
        if k + 1 < len(wins) and not landed[k + 1] and wins[k + 1].get("kind", "phrase") != "intro":
            nxt = wins[k + 1]
            n_lines = [ln for ln in lines if float(nxt["start"]) - 0.05 <= float(ln["start"]) < float(nxt["end"]) - 0.05]
            own_end = float(own[0].get("end") or own[0]["start"])
            gap_fwd = (float(n_lines[0]["start"]) - own_end) if n_lines else 99.0
            merged_fwd = _sung_span(ws, float(nxt["end"]))
            if (n_lines and gap_fwd < GAP_TO_BROLL_S and merged_fwd + HEAD_PAD_S + TAIL_PAD_S <= max_clip
                    and _one_voice(own, n_lines)):
                w["end"] = nxt["end"]
                del wins[k + 1]
                del landed[k + 1]
                continue
        w["shortLine"] = True          # a lone short line: sized with the stretch margin below
        k += 1
    n = len(wins)
    # 3. geometry, for the windows that moved or whose end moved (never a landed one).
    #    SIZED BY THE SINGING (see HEAD_PAD_S): the render covers first word .. last word
    #    of the lines inside the window, plus the pads; the rest of the window (the gap to
    #    the next line) stays out of the clip.
    for i, w in enumerate(wins):
        if landed[i]:
            _name_stale_geometry(i, w, lines, max_clip)
            continue
        w_start, w_end = max(0.0, float(w["start"])), float(w["end"])
        covered = round(w_end - w_start, 3)
        if w.get("kind", "phrase") == "intro" and abs(covered - float(w["seconds"])) < 1e-6:
            continue
        mine = [ln for ln in lines if w_start - 0.05 <= float(ln["start"]) < w_end - 0.05]
        sung_end = max((float(ln.get("end") or ln["start"]) for ln in mine), default=w_end)
        sung = round(min(sung_end, w_end) - w_start, 3)        # from the window's open (ONSET_LEAD_S before the word)
        if sung <= 0 or not mine:
            sung = covered                                     # nothing placed here: the old shape
        # Whole seconds, NEAREST to sung + pads — never below the singing plus a breath
        # to close the mouth (rounding UP would hand back the 7 s render for 5.5 s of
        # words that started all this). MIN_CLIP still floors a short last line.
        secs = max(int(math.ceil(sung + 0.1 - 1e-6)), int(round(sung + HEAD_PAD_S + TAIL_PAD_S)))
        if w.pop("shortLine", False) and SHORT_LINE_RATE > 1.0:
            # the model stretches a short line ~SHORT_LINE_RATE; give it the room so the
            # last word is inside the clip (fit_takes retimes it to the record afterwards).
            # SHORT_LINE_RATE <= 1.0 turns the margin OFF, because on some routes the room
            # IS the stretch: film #3's w00 was given 7 s for 4.4 s of words by this very
            # margin and the take sang them at 1.65x, over the judge's 1.25 bar — the model
            # paces to the clip it is handed (the standing "render length = sung length"
            # rule), so a margin here feeds itself. Off, w00 renders 5 s for 4.4 s.
            secs = max(secs, int(math.ceil(HEAD_PAD_S + sung * SHORT_LINE_RATE + TAIL_PAD_S - 1e-6)))
            w["shortLineMargin"] = True
        # A SMALL GAP TO THE NEXT LINE IS ABSORBED, A BIG ONE IS LEFT TO B-ROLL. The gap
        # after the last word belongs to nobody: under ~1 s the assembler has nothing to
        # fill it with (a held frame shows past 0.6 s, a cutaway needs a second), so the
        # render grows to cover it — real frames of a closed mouth, ratio still ≤ ~1.2.
        # A gap of a second or more becomes a pool section and B-roll fills it.
        gap_after = round(w_end - (w_start + sung), 3)
        absorb = gap_after if 0 < gap_after < GAP_TO_BROLL_S else 0.0
        if absorb:
            secs = max(secs, int(math.ceil(sung + absorb + 0.1 - 1e-6)))
        secs = max(MIN_CLIP, min(secs, max_clip))
        if secs < sung + absorb:                               # the cap would clip a word: never
            secs = int(math.ceil(sung + absorb - 1e-6))
        spare = round(secs - sung - absorb, 3)                 # silence the pads can use
        # THE HEAD GETS ITS LEAD-IN FIRST. HEAD_PAD_S of silence before the first word,
        # then whatever is left splits evenly; the tail takes the remainder. Never past
        # the song's start (w00 opens at 0).
        head = min(spare, w_start, max(HEAD_PAD_S, HEAD_PAD_S + (spare - HEAD_PAD_S - TAIL_PAD_S) / 2))
        head = max(0.0, round(head, 3))
        # The assembly covers [w_start, w_start + sung + absorb): the singing plus the
        # absorbed gap (real closed-mouth frames); tailSec is the slack beyond that.
        tail = max(0.0, round(secs - sung - absorb - head, 3))
        w["seconds"] = secs
        w["startSec"] = round(w_start - head, 3)
        w["trimStartSec"] = head                               # the assembly skips the silent head
        w["tailSec"] = tail                                    # ... and ignores what is past the window
        w["sungSec"] = sung
        w["absorbedGapSec"] = absorb
        w["headSpill"] = 0.0
        w["exact"] = True
    return wins


def apply_vocal_brief(jobs: list, brief_path: str, pronouns: str, performer_of: dict,
                      declared: set, hook_wav: str = "", ffmpeg: str = "ffmpeg",
                      voice_source: str = "", timestamps: bool = True,
                      performer_names: str = "") -> None:
    doc = json.load(open(brief_path, encoding="utf-8"))
    by_id = {w["id"]: w for w in doc["windows"]}
    prons = [x.strip() or "he" for x in pronouns.split("|")]
    # A LETTER-TAGGED SHEET. When the sheet names performers ('- A' / '- B') instead of
    # genders, the performer letter IS the voice a solo window owns: two boys are both
    # "he", and gender would have made every line both of theirs (Baby Yeh Dosti).
    letters = any(sp.get("who") in ("a", "b") for w in doc["windows"] for sp in w.get("spans", []))
    name_list = [n.strip() for n in performer_names.split("|")] if performer_names else []
    name_of = {k: n for k, n in zip(("a", "b"), name_list) if n}
    if letters and len(name_of) < 2:
        die("the lyric sheet tags performers by letter (- A / - B) but --performer-names "
            "(PERFORMER_NAMES=\"Name A|Name B\") does not name both")
    for job in jobs:
        b = by_id.get(job["id"])
        if not b:
            continue
        who = job.get("performer") or performer_of.get(job["styleId"], "a")
        both = who == "both"
        pron = "they" if both else prons[1 if who == "b" else 0] if len(prons) > (1 if who == "b" else 0) else "he"
        subj, poss, Subj, obj = _PRON.get(pron, _PRON["he"])
        gender = (who if letters and who in ("a", "b")
                  else "female" if pron == "she" else "male" if pron == "he" else "lead")
        prompt = job["prompt"]
        m = re.search(r"Audio 1 \(<<<audio_1>>>\) is the [\d.]+-second rap track[^.]*\. ", prompt)
        if not m:
            continue
        direction, any_mouth = _direction(b, subj, poss, gender, both, obj, timestamps=timestamps,
                                          names=name_of)
        # THE OTHER PERFORMER'S VOICE IS NOT THIS FACE'S TO SING. When most of the sung
        # time in a solo window belongs to the other voice, the window is a non-singing
        # shot: lips closed, doing the scene's action while the track plays (operator:
        # "the guy doesn't always need to sing — but when he sings it must be his vocal").
        if not both:
            # A `both`/`duet` passage IS this face's to sing. Counting only the solo
            # spans made w12 (his shout + "do kadam, ek dhamak", all `both`) a no-voice
            # shot because 0.6 s of her next line rode in its tail slack (2026-08-23).
            sung = [sp for sp in b["spans"] if sp.get("who") in ("male", "female", "both", "duet", "lead", "a", "b")
                    and not sp.get("partialHead") and not sp.get("partialTail")]
            other = sum(sp["end"] - sp["start"] for sp in sung
                        if sp["who"] in ("male", "female", "a", "b") and sp["who"] != gender)
            own = sum(sp["end"] - sp["start"] for sp in sung
                      if sp["who"] == gender or sp["who"] in ("both", "duet", "lead"))
            if sung and other > own:
                any_mouth = False
                job["otherVoice"] = True
            # A CHANT IS A DANCE SHOT. Every whole span of this face's own singing in the
            # window is tagged `chant` on the sheet → no lip-sync: the window takes the
            # no-voice movement prompt and the record's own vocal plays over it (under
            # vocal-swap the record is kept wherever no take sings). Measured reason: the
            # model scatters onsets on a repeated word (740 ms on w06; 450-480 ms on film
            # #3's chanted verses) and lands melody at 50-70 ms — chant windows fail the
            # sync bar by construction, so they carry the film's dancing instead.
            own_spans = [sp for sp in b["spans"] if sp.get("who") in (gender, "both", "duet", "lead")
                         and not sp.get("partialHead") and not sp.get("partialTail")]
            if own_spans and all(sp.get("how") == "chant" for sp in own_spans) and not job.get("otherVoice"):
                any_mouth = False
                job["chantDance"] = True
        if b["mode"] == "shot-led" or not any_mouth:
            # NO VOICE. Nothing for this face to sing: the track plays over the shot. The
            # prompt is the COMPOSED no-voice register (compose_prompts NO_VOICE_*): the
            # declaration in the audio slot, a movement line with no performance verb —
            # never the motion prompt with its singing verbs regexed out, which
            # plan_coherence #14 then re-read with a different spelling (three refused
            # plans, 2026-08-28..31). An older prompts.json has no such variant: refuse,
            # and say which stage to re-run — a quiet fall-back to the rewriter is what
            # this replaces.
            job.pop("voiceRef", None)
            job["synced"] = False
            variant = "promptOtherVoice" if job.get("otherVoice") else "promptNoVoice"
            composed = job.get(variant)
            if not composed:
                raise SystemExit(f"make_plan: {job['id']} is a no-voice window but its style has no "
                                 f"{variant} — prompts.json predates the composed no-voice register. "
                                 f"Re-run the prompts stage (compose_prompts) and plan again.")
            job["prompt"] = composed
            job.pop("promptSung", None)
            job.pop("promptNoVoice", None)
            job.pop("promptOtherVoice", None)
            sentence = None
        else:
            sentence = (f"Audio 1 (<<<audio_1>>>) is the {b['seconds']:g}-second track for this shot — lip-sync to it "
                        f"EXACTLY and only where words are sung: {direction}. Never mouth words over the parts "
                        f"with no singing, and the final video includes sound. ")
        # WHICH PROMPT THIS WINDOW GETS. A window that carries a voice takes the style's
        # sung prompt (locked medium close-up, no coupling — compose_prompts SUNG_*); an
        # instrumental window keeps the motion prompt. Both carry the identical Audio
        # sentence, so the same replacement lands in either.
        if sentence is not None:
            sung_prompt = job.pop("promptSung", None)
            base = sung_prompt if (sung_prompt and job.get("voiceRef")) else prompt
            job["prompt"] = base.replace(m.group(0), sentence, 1)
        job.pop("promptNoVoice", None)
        job.pop("promptOtherVoice", None)
        if job.get("voiceRef") and hook_wav and os.path.isfile(hook_wav):
            own = [sp for sp in b["spans"] if not sp.get("partialHead") and not sp.get("partialTail")
                   and (both or sp.get("who") in ("both", "duet", "lead", gender))]
            t0 = min((float(sp["start"]) for sp in own), default=0.0)
            # THE TAIL SLACK IS FOR THE PICTURE, NOT THE VOICE. Everything past the
            # window's covered end is silenced — not just a "partial" fragment: w09's
            # 1.9 s tail carried the start of the NEXT window's line, unsilenced, because
            # that fragment was just over the partial threshold (2026-08-23).
            # ... from the NEXT line's onset, not the window's edge: the edge sits
            # ONSET_LEAD_S before that onset and the last word's release runs right up
            # to it ("kamaal" lost its last 60 ms, heard on the slice check).
            covered_end = float(job["seconds"]) - float(job.get("tailSec") or 0.0) + ONSET_LEAD_S + 0.05
            tails = [float(sp["start"]) for sp in b["spans"] if sp.get("partialTail")]
            t1 = min(tails + ([covered_end] if float(job.get("tailSec") or 0.0) > 0 else []), default=0.0)
            head = t0 if t0 >= MUTE_HEAD_MIN_S else 0.0
            if head > 0 or t1 > 0:
                build_voice(hook_wav, float(job["startSec"]), float(job["seconds"]), job["voiceRef"],
                            ffmpeg, 720, 1280, mute_head=head, mute_tail=t1, source=voice_source)
                if head > 0:
                    job["muteHeadSec"] = round(head, 3)
                if t1 > 0:
                    job["muteTailSec"] = round(t1, 3)
        job["vocal"] = {"mode": "no-voice" if not job.get("voiceRef") else "synced",
                        "coverage": b["coverage"], "spans": b["spans"], "silences": b["silences"]}
    # TWO SUNG WINDOWS IN ONE WORLD, BACK TO BACK, MUST NOT SHARE A FRAME (ledger row 30):
    # the second takes the tight head, the third goes back, so every cut inside a world
    # is a change of size. Composed by exact swap of the framing head the sung prompt
    # carries; a prompt without it (an authored `shot`) is left alone.
    from compose_prompts import SUNG_FRAMING_HEAD, SUNG_FRAMING_TIGHT_HEAD
    prev = None
    for job in sorted(jobs, key=lambda j: int(j.get("window", 0) or 0)):
        voiced = bool(job.get("voiceRef"))
        tight = False
        if (prev is not None and voiced and prev.get("voiceRef") and prev.get("styleId") == job.get("styleId")
                and not prev.get("framing") == "tight" and SUNG_FRAMING_HEAD in job.get("prompt", "")):
            job["prompt"] = job["prompt"].replace(SUNG_FRAMING_HEAD, SUNG_FRAMING_TIGHT_HEAD, 1)
            tight = True
        if tight:
            job["framing"] = "tight"
        prev = job


def apply_shot_refs(jobs: list, refs_path: str, portrait: str, pronouns: str, *, motion_donor: bool = False,
                    portrait2: str = "", names: str = "") -> None:
    """Per window, the reference video's own shot (shot_refs.py): the styled keyframe becomes
    @IMG_1 (the frame-zero composition anchor), the portrait rides as @IMG_2 (identity
    reinforcement, and the prose descriptor stays), the measured moves sentence replaces the
    sung performance line, and with `motion_donor` the muted original footage rides as the
    motion reference (@video1 — a separate task field, never in referencePaths, so the voice
    path is untouched). A no-voice window takes the breakdown's timecoded blocks as its
    movement line. Runs AFTER apply_vocal_brief: it edits the prompt that window will send.
    Every rewrite is an exact-substring replace that dies when the substring is missing —
    a silently unrewritten prompt renders the wrong film."""
    from compose_prompts import PRONOUNS, sung_performance_sentence
    doc = json.load(open(refs_path, encoding="utf-8"))
    windows = doc.get("windows") or {}
    prons = [p.strip() for p in (pronouns or "he").split("|")]
    for job in jobs:
        w = windows.get(job["id"])
        if not w:
            continue
        if w.get("problems"):
            die(f"{job['id']}: shot-refs has open problems: {'; '.join(w['problems'])} — fix them in "
                f"shot_refs.py before planning")
        prompt = job.get("prompt", "")
        perf = job.get("performer") or "a"
        both = perf == "both"
        pr = (PRONOUNS["they"] if both else
              PRONOUNS.get(prons[1] if perf == "b" and len(prons) > 1 else prons[0], PRONOUNS["he"]))
        kf = w.get("keyframe")
        if kf and not os.path.isfile(kf):
            die(f"{job['id']}: shot-refs names a keyframe that is not on disk: {kf}")
        # A SHOT FRAME MUST SHOW A FACE TO STAND AS IDENTITY. shot_refs.py draws the
        # keyframe AT the shot's own recorded framing (FRAMING_BY_KIND), and only a
        # NO-VOICE window's framing can come out "wide" (a sung window always draws at
        # FRAMING_SUNG — face large, waist-up). On film #3's two no-voice ending windows
        # the keyframe was a wide landscape with the figure a few dozen pixels tall, and
        # Seedance rendered another man from it (w28, 2026-09-07): locking identity to a
        # shot too wide to show a face is worse than not locking it to the shot at all.
        no_voice = not job.get("voiceRef")
        wide_shot = w.get("shotFraming") == "wide"
        if kf and (no_voice or wide_shot):
            # Leave identityRef at the plan's own portrait (set when the job was built)
            # and the prompt's standing "Image 1 (@IMG_1) is the protagonist portrait"
            # citation untouched — it stays true. The shot still IS this window's
            # location and pose; record it as a secondary reference, not the identity.
            job["shotFrame"] = os.path.abspath(kf)
        elif kf:
            # ANY window with a keyframe opens on it (a sung line or a dance shot alike).
            job["identityRef"] = os.path.abspath(kf)
            if both:
                # TWO FACES: the keyframe is @IMG_1, then BOTH portraits (@IMG_2 = a, @IMG_3 = b).
                if not portrait2:
                    die(f"{job['id']}: a `both` shot-ref window needs --identity-ref-2 (PORTRAIT_2)")
                job["identityRef2"] = os.path.abspath(portrait)
                job["identityRef3"] = os.path.abspath(portrait2)
                m = re.search(r"Image 1 \(@IMG_1\) is the protagonist portrait( — .*?)? — preserve the same facial identity "
                              r"and face shape from the uploaded photo while changing the outfit to .*?\. "
                              r"Image 2 \(@IMG_2\) is the second performer's portrait — (.*?) — preserve that facial "
                              r"identity and face shape as well, in .*?\. "
                              r"(?=Audio 1 |There is no singing|The voice on the track)",
                              prompt, re.S)
                if not m:
                    die(f"{job['id']}: the two-performer identity sentences to rewrite are not in the prompt (cite() changed?)")
                d1 = (m.group(1) or "").strip(" —")
                d2 = (m.group(2) or "").strip(" —")
                nm = [n.strip() for n in (names or "").split("|")] + ["", ""]
                who1 = f"{nm[0]}'s portrait" if nm[0] else "the first performer's portrait"
                who2 = f"{nm[1]}'s portrait" if nm[1] else "the second performer's portrait"
                identity = ("Image 1 (@IMG_1) is the first frame of this shot: the two of them, in exactly this framing, "
                            "poses, camera angle and set — start from it and keep both faces identical. "
                            f"Image 2 (@IMG_2) is {who1} — {d1 + ' — ' if d1 else ''}the same face and hair. "
                            f"Image 3 (@IMG_3) is {who2} — {d2 + ' — ' if d2 else ''}the same face and hair. ")
                prompt = prompt[:m.start()] + identity + prompt[m.end():]
            else:
                # performer b's face is the SECOND portrait (make_plan bound it as Image 1 before)
                job["identityRef2"] = os.path.abspath(portrait2 if (perf == "b" and portrait2) else portrait)
                # The identity sentence: image 1 is now the shot, image 2 the face. The
                # descriptor prose after the dash is kept (Seedance locks a face from the TEXT).
                # The descriptor (IDENTITY_NOTES) and the wardrobe both carry full stops, so the
                # match runs to the sentence that follows ("Audio 1 …"), not to the first period.
                m = re.search(r"Image 1 \(@IMG_1\) is the protagonist portrait( — .*?)? — preserve the same facial identity "
                              r"and face shape from the uploaded photo while changing the outfit to .*?\. "
                              r"(?=Audio 1 |There is no singing|The voice on the track)",
                              prompt, re.S)
                if not m:
                    die(f"{job['id']}: the identity sentence to rewrite is not in the prompt (cite() changed?)")
                descriptor = (m.group(1) or "").strip(" —")
                # `she` reads "her … her face … her portrait": the first film's text, byte for byte
                identity = (f"Image 1 (@IMG_1) is the first frame of this shot: {pr['obj']}, in exactly this framing, pose, "
                            f"camera angle and set — start from it and keep {pr['poss']} face identical. "
                            f"Image 2 (@IMG_2) is {pr['poss']} portrait — {descriptor + ' — ' if descriptor else ''}the same face and hair. ")
                prompt = prompt[:m.start()] + identity + prompt[m.end():]
            job["framing"] = "shot"            # the keyframe decides the size: no tight-head swap
        if job.get("voiceRef"):
            if not kf:
                die(f"{job['id']}: a sung shot-ref window has no keyframe")
            # The performance line → the measured moves sentence.
            style_id = job.get("styleId")
            style = _STYLE_CACHE.get(style_id) or {}
            old = sung_performance_sentence(style, pr)
            moves = (w.get("moves") or "").strip().rstrip(".")
            if not moves:
                die(f"{job['id']}: shot-refs has no moves sentence")
            if old not in prompt:
                die(f"{job['id']}: the sung performance sentence is not in the prompt: {old[:80]!r}")
            # The breakdown writes "The (lead) dancer …" / "The driver …" / "She …"; a solo
            # prompt's subject is the pronoun, so drop the sentence's own generic subject
            # before prefixing it ("They the driver steers" shipped on a contract, 2026-09-06).
            # A TWO-PERSON shot keeps the sentence verbatim: its subjects ("the driver …,
            # the passenger …") say which of the two does what — a pronoun cannot.
            if both:
                prompt = prompt.replace(old, f"{moves[0].upper() + moves[1:]}.", 1)
            else:
                moves = re.sub(r"^(?:the|a)\s+(?:(?:lead|seated|standing|young|second|first)\s+)?"
                               r"(?:dancer|performer|driver|passenger|rider|singer|man|woman|boy|girl|figure)\s+"
                               r"|^(?:she|he|they)\s+", "", moves, flags=re.I)
                prompt = prompt.replace(old, f"{pr['Subj']} {moves[0].lower() + moves[1:]}.", 1)
            if motion_donor and w.get("donorOk") and w.get("donor"):
                job["motionRef"] = os.path.abspath(w["donor"])
                if w.get("donorAudio"):
                    prompt += (f" Video 1 (@video1) carries {pr['poss']} vocal: the exact words {pr['subj']} sing{pr['s']} and their timing — "
                               f"sing precisely to it, every word on its beat, while {pr['subj']} dance{pr['s']} as directed. Take no "
                               "picture, colours or people from @video1; the picture starts from @IMG_1.")
                else:
                    prompt += (" Video 1 (@video1) is the motion reference: copy its dance moves, body rhythm and "
                               "timing exactly; take only the movement from @video1 — not its appearance, colours, "
                               "people or background. @video1 is mute; Audio 1 is the only clock.")
            job["shotRef"] = {k: w.get(k) for k in ("srcFrame", "srcAt", "shotIndex", "shotStart", "shotEnd",
                                                     "coverage", "moves", "framing", "keyframeSha", "donorOk")}
        elif w.get("performanceSilentOverride"):
            # A no-voice window may not be told to sing (plan_coherence #14: with no audio
            # the model invents a vocal and mouths it). The breakdown describes what the
            # footage shows, and the original singer IS singing there — drop those blocks.
            blocks = [b.strip() for b in w["performanceSilentOverride"]
                      if b.strip() and not re.search(r"\b(sing|sings|singing|sung|rap|raps|rapping|mouth(s|ing)?|lip-?sync)\b",
                                                     b, re.I)]
            if blocks:
                job["shotRef"] = {k: w.get(k) for k in ("srcFrame", "srcAt", "shotIndex", "shotStart", "shotEnd",
                                                         "coverage", "framing", "keyframeSha")}
                job["shotRef"]["blocks"] = blocks
                # No-voice windows keep the composed movement line: a timecoded block list
                # is appended as the choreography, under the register's own sentence.
                prompt = prompt.rstrip() + " The choreography of this shot, in order: " + " ".join(blocks) + " "
        job["prompt"] = prompt


_STYLE_CACHE: dict = {}


def apply_shots(jobs: list, shots_path: str) -> None:
    """Give each window its OWN shot: the authored size/place replaces the standing sung
    framing sentence, and an approved frame becomes that window's identity reference.

    compose_prompts composes ONE prompt per world, so every window in a chapter carries
    the same locked medium close-up and only make_plan's medium/tight swap differs. Film
    #3 was stopped after three clips for that ("the same scene all the time"). A shot file
    is how a chapter becomes a sequence of shots: the take stays locked (lip-sync needs the
    mouth readable), the SETUP changes. A window with no entry is left exactly as composed.
    """
    from compose_prompts import SUNG_FRAMING_HEAD, SUNG_FRAMING_TIGHT_HEAD
    doc = json.load(open(shots_path, encoding="utf-8"))
    shots = doc.get("shots") or {}
    applied = 0
    for job in jobs:
        sh = shots.get(job["id"])
        if not sh:
            continue
        size, place = str(sh.get("size") or "").strip(), str(sh.get("place") or "").strip()
        if size:
            head = f"The camera holds a locked {size.rstrip('.')}"
            if place:
                head += f", {place.rstrip('.')}"
            head += ","
            # A shot that was already applied is REVISED, not skipped: the head this
            # function wrote last time is recorded on the job, so a corrected shots.json
            # can be re-applied without a full re-plan. Without this, revising one window's
            # shot (film #3's w06, rewritten after the free lane refused a portrait-like
            # frame four times) silently did nothing and the old prompt kept rendering.
            for standing in (job.get("shotHead"), SUNG_FRAMING_HEAD, SUNG_FRAMING_TIGHT_HEAD):
                if standing and standing in job.get("prompt", ""):
                    job["prompt"] = job["prompt"].replace(standing, head, 1)
                    job["shot"] = size
                    job["shotHead"] = head
                    applied += 1
                    break
        frame = str(sh.get("frame") or "").strip()
        if frame and os.path.isfile(frame):
            job["identityRef"] = os.path.abspath(frame)   # the approved frame IS the lock
            job["shotFrame"] = os.path.abspath(frame)
    print(f"apply_shots: {applied} window(s) took their authored shot from "
          f"{os.path.basename(shots_path)}", file=sys.stderr)


def resolve_voice_source(source: str, voice_wav: str, build: str, hook_wav: str) -> str:
    """The audio the voice slices are cut from.

    `mix` (default) is hook.wav — the whole track, bed and all. `stem` is the Demucs
    vocal stem the `stem` stage writes to build/stems/vocals.wav: the same timeline as
    hook.wav (it is separated FROM hook.wav) with nothing under the voice, which is the
    "single clock" the model can follow. A missing stem is a hard stop, never a quiet
    fall-back to the mix — the pack said stem, and a film cut half from each would sync
    two different ways."""
    if source == "stem":
        path = voice_wav or os.path.join(build, "stems", "vocals.wav")
        if not os.path.isfile(path) or os.path.getsize(path) == 0:
            die(f"--voice-source stem but no vocal stem at {path} — run the `stem` stage "
                "(singer_diarize.py --separate-only) or set VOICE_SOURCE=mix")
        return path
    if voice_wav:
        if not os.path.isfile(voice_wav):
            die(f"--voice-wav not found: {voice_wav}")
        return voice_wav
    return hook_wav


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True, help="projects/<slug> directory")
    ap.add_argument("--styles", default="", help="style register (required unless --redo-from)")
    ap.add_argument("--shots", default="",
                    help="build/shots.json: an AUTHORED shot per window — {shots: {wNN: "
                         "{size, place, action, frame?}}}. Its `size`+`place` replace the "
                         "standing sung framing sentence for that window, and an approved "
                         "`frame` becomes that window's identityRef. A world composes one "
                         "prompt for every window in it (compose_prompts), so without this "
                         "a chapter is the same shot N times — the operator stopped film #3 "
                         "for exactly that (2026-09-03).")
    ap.add_argument("--drawn", default="")
    ap.add_argument("--hook", default="", help="hook.json; defaults to <project>/build/hook.json")
    ap.add_argument("--identity-ref", default="", help="the FACE still (required unless --redo-from)")
    ap.add_argument("--identity-ref-2", default="",
                    help="the second performer's FACE still (PORTRAIT_2); required when a "
                         "style is for performer b or both")
    # RENDER SLACK around each sung window (seconds, default 0 = byte-identical plans).
    # The clip is rendered from `head` BEFORE the window to `tail` AFTER it, with
    # trimStartSec/tailSec recording the slack, so `slide` can correct an early or late
    # take from REAL frames instead of a held one (sync_shift.slack_plan), and the head
    # is a count-in before the first sung word. Most of 2026-08-22's rejected takes
    # were constant offsets (+400, +525, -1225 ms) that 40 ms of slack could not absorb.
    ap.add_argument("--slack-head", type=float, default=0.0)
    ap.add_argument("--slack-tail", type=float, default=0.0)
    # WHOLE LINES ONLY. A window opens ON its first line's first word and closes where
    # the next window's first word begins, so a slice never carries a partial line at
    # either end (operator, 2026-08-23: "you are not slicing the audio correctly, hence
    # this big mess"). The render rounds UP to whole seconds (+ --slack-tail); the
    # remainder is tail slack and is silenced past the last word this take sings.
    # Needs the brief (second planning pass). A window that already has its clip keeps
    # its geometry; the window after it starts where that clip ends.
    ap.add_argument("--exact-onsets", action="store_true")
    ap.add_argument("--windows", default="",
                    help="line_windows.py output: explicit whole-second windows that "
                         "start on sung lines. Replaces the fixed --clip-seconds tiling; "
                         "only the last window is slid back onto the song's end.")
    ap.add_argument("--vocal-brief", default="",
                    help="vocal_brief.py output: per-window words/silences. Each window's "
                         "prompt then directs the mouth line by line, and a window with no "
                         "words is sent WITHOUT a voice (shot-led).")
    ap.add_argument("--no-timestamps", action="store_true",
                    help="ONE CLOCK: the per-window direction quotes every line in order "
                         "and every lips-closed rule but names no seconds — the audio "
                         "reference is the only timing system (PROMPT_TIMESTAMPS=0 in "
                         "the pack). Default keeps the timestamped script.")
    ap.add_argument("--no-word-verify", action="store_true",
                    help="lyric is not English: the English-forced word check at landing "
                         "cannot judge it, so only timing correlation decides")
    ap.add_argument("--shot-refs", default="",
                    help="shot-refs.json (shot_refs.py): per-window keyframe as @IMG_1, a moves sentence, a motion donor")
    ap.add_argument("--motion-donor", action="store_true",
                    help="with --shot-refs: attach each window's donor clip as the motion reference (@video1)")
    ap.add_argument("--pronouns", default="he",
                    help="pipe-separated per performer (he|she|they) — used only to word "
                         "the per-window vocal direction")
    ap.add_argument("--performer-names", default="",
                    help="pipe-separated names of performers a|b (PERFORMER_NAMES). Required when "
                         "the lyric sheet tags voices by letter (- A / - B): the vocal direction "
                         "says whose mouth moves by name")
    ap.add_argument("--redo-from", default="",
                    help="a check_sync.py --json-out report. Emits a re-render plan for "
                         "the windows that are unusable (wrong bar, or too short to fill "
                         "their window) and NOTHING else — an offset is a cut-point fix, "
                         "not a re-render. Writes the plan; never submits.")
    ap.add_argument("--from-plan", default="", help="source plan for --redo-from (default build/plan.json)")
    ap.add_argument("--redo-ids", default="",
                    help="comma-separated window ids to re-render regardless of sync "
                         "(w00,w03) — for defects you SAW, which check_sync cannot measure")
    ap.add_argument("--refresh-prompts", default="",
                    help="prompts.json to re-read, so the redo uses corrected prompts "
                         "instead of faithfully reproducing the defect")
    ap.add_argument("--prompts", default="", help="prompts.json; defaults to <project>/build")
    ap.add_argument("--clip-seconds", type=float, default=8.0)
    ap.add_argument("--voice-source", choices=("mix", "stem"), default="mix",
                    help="what the voice slices are cut from: `mix` = hook.wav (the whole "
                         "track, today's default) or `stem` = the Demucs vocal stem, a clean "
                         "clock with no bed under it (VOICE_SOURCE in the pack)")
    ap.add_argument("--voice-wav", default="",
                    help="the audio file the slices are cut from; default hook.wav for "
                         "`mix`, build/stems/vocals.wav for `stem`")
    ap.add_argument("--aspect", default="9:16")
    ap.add_argument("--resolution", default="720p")
    ap.add_argument("--route", default="seedance-direct",
                    help="seedance-direct through the "
                    "vendored Higgsfield engine is the free lane")
    ap.add_argument("--sections", default="")
    ap.add_argument("--out", default="")
    ap.add_argument("--workspace-root", default=os.environ.get("VCLAW_WORKSPACE", ""))
    ap.add_argument("--ffmpeg", default=os.environ.get("FFMPEG_BIN", "ffmpeg"))
    args = ap.parse_args()

    build = os.path.join(args.project, "build")
    hook_path = args.hook or os.path.join(build, "hook.json")
    prompts_path = args.prompts or os.path.join(build, "prompts.json")

    extra_ids = tuple(x.strip() for x in args.redo_ids.split(",") if x.strip())
    if args.redo_from or extra_ids:
        if args.redo_from and not os.path.isfile(args.redo_from):
            die(f"not found: {args.redo_from}")
        src = args.from_plan or os.path.join(build, "plan.json")
        if not os.path.isfile(src):
            die(f"source plan not found: {src} (pass --from-plan)")
        build_redo(args.project, args.redo_from, src,
                   args.out or os.path.join(build, "plan-redo.json"),
                   os.path.join(build, "hook.wav"), args.ffmpeg,
                   extra_ids, args.refresh_prompts)
        return

    if not args.identity_ref:
        die("--identity-ref is required")
    if not args.styles:
        die("--styles is required")
    for p in (hook_path, prompts_path, args.identity_ref, args.identity_ref_2):
        if p and not os.path.isfile(p):
            die(f"not found: {p}")

    hook = json.load(open(hook_path, encoding="utf-8"))
    try:   # apply_shot_refs needs each style's performanceSung to find the sentence it replaces
        _STYLE_CACHE.update({st["id"]: st for st in json.load(open(args.styles, encoding="utf-8")).get("styles", [])})
    except (OSError, ValueError, KeyError, TypeError):
        pass
    hook_wav = hook.get("hookWav") or os.path.join(build, "hook.wav")
    if not os.path.isfile(hook_wav):
        die(f"hook.wav not found: {hook_wav} — run the hook stage first")
    voice_src = resolve_voice_source(args.voice_source, args.voice_wav, build, hook_wav)
    total = float(hook["durationSec"])
    if args.clip_seconds != int(args.clip_seconds):
        die(f"--clip-seconds must be a whole number of seconds, got {args.clip_seconds:g}. "
            f"{VALID_NOTE}")
    # Every window on this lane carries a voice reference, which is what makes it
    # lip-synced at all — so the synced cap is the one that applies.
    _max_clip = max_clip_for(args.route, synced=True)
    if not (MIN_CLIP <= args.clip_seconds <= _max_clip):
        die(f"--clip-seconds {args.clip_seconds:g} is outside {MIN_CLIP}-{_max_clip}s for route {args.route!r}. "
            f"{VALID_NOTE}")

    prompt_rows = json.load(open(prompts_path, encoding="utf-8"))["prompts"]
    prompts = {r["id"]: r["prompt"] for r in prompt_rows}
    # compose_prompts writes a second prompt per style — the same world locked for sync —
    # that apply_vocal_brief puts on the windows that carry a voice. An older prompts.json
    # has none, and then every window keeps the motion prompt exactly as before.
    prompts_sung = {r["id"]: r["promptSung"] for r in prompt_rows if r.get("promptSung")}
    prompts_silent = {r["id"]: r["promptNoVoice"] for r in prompt_rows if r.get("promptNoVoice")}
    prompts_other = {r["id"]: r["promptOtherVoice"] for r in prompt_rows if r.get("promptOtherVoice")}
    if not prompts:
        die("prompts.json has no prompts — run compose_prompts.py first")
    # Whose still each style binds. compose_prompts writes `performer` only when the
    # register uses it; a row without it is performer a, today's film.
    performer_of = {r["id"]: r.get("performer", "a") for r in prompt_rows}
    declared = {r["id"] for r in prompt_rows if "performer" in r}
    for sid, who in performer_of.items():
        if who in ("b", "both") and not args.identity_ref_2:
            die(f"style '{sid}' is for performer {who} but no --identity-ref-2 (PORTRAIT_2) "
                "was given")

    drawn_path = args.drawn or os.path.join(build, "styles-drawn.json")
    order = [s["id"] for s in json.load(open(drawn_path, encoding="utf-8"))["styles"]] \
        if os.path.isfile(drawn_path) else list(prompts)

    sections = json.load(open(args.sections, encoding="utf-8")) if args.sections else []
    if isinstance(sections, dict):
        sections = sections.get("sections", [])
    for s in sections:
        if s["styleId"] not in prompts:
            die(f"sections names style '{s['styleId']}', which is not in prompts.json")

    def style_at(mid: float, i: int) -> tuple[str, str]:
        for s in sections:
            if float(s["start"]) <= mid < float(s["end"]):
                return s["styleId"], s.get("label", "")
        return order[i % len(order)], ""

    def direction_at(mid: float) -> str:
        """A section may carry `direction`: prose for THESE windows only (e.g. "for the
        first three seconds he is still in verse energy"), appended after the vocal
        sentence. A style block is per scene; this is per moment."""
        for s in sections:
            if float(s["start"]) <= mid < float(s["end"]) and s.get("direction"):
                return " Direction for this window: " + s["direction"].strip().rstrip(".") + "."
        return ""

    w, h = (720, 1280) if args.aspect == "9:16" else (1280, 720)
    voice_dir = os.path.join(build, "voice")
    os.makedirs(voice_dir, exist_ok=True)

    clip = float(args.clip_seconds)
    jobs, t, i = [], 0.0, 0
    explicit = []
    if args.windows:
        if not os.path.isfile(args.windows):
            die(f"--windows not found: {args.windows}")
        explicit = json.load(open(args.windows, encoding="utf-8")).get("windows", [])
        if not explicit:
            die(f"--windows has no windows: {args.windows}")
    if explicit and args.exact_onsets and args.vocal_brief and os.path.isfile(args.vocal_brief):
        explicit = exact_onsets(explicit, json.load(open(args.vocal_brief, encoding="utf-8")),
                                build, float(args.slack_tail), _max_clip)
    for ew in explicit:
        # WINDOWS THAT START ON SUNG LINES (line_windows.py), on WHOLE seconds: the clip
        # IS the window (trimStartSec 0) on every window but the last, which ends on the
        # fractional song end and is slid back, its head skipped by the assembly.
        start, dur, trim = float(ew["startSec"]), float(ew["seconds"]), float(ew["trimStartSec"])
        tail = float(ew.get("tailSec") or 0.0) if ew.get("exact") else 0.0
        # A WINDOW THAT ALREADY HAS ITS CLIP KEEPS ITS GEOMETRY. Slack changes the
        # render length and the slice, and the driver re-verifies a clip on disk
        # against its slice — a 10 s take judged against a 12 s slice is parked and
        # re-rendered, which would throw away exactly the clips reuse just found.
        landed = os.path.isfile(os.path.join(build, "queue", "explore", "clips", f"w{i:02d}.mp4"))
        if (args.slack_head or args.slack_tail) and ew.get("kind", "phrase") != "intro" and not landed and not ew.get("exact"):
            # Slack stays inside the valid clip lengths: whole seconds, never past the
            # cap (tail gives way first, then head), never before the song's start, and
            # no tail on the window that ends the song (the slice would run past it).
            is_last = ew is explicit[-1]
            head = min(float(args.slack_head), start + trim)
            tail = 0.0 if is_last else float(args.slack_tail)
            head, tail = float(int(head)), float(int(tail))
            while dur + head + tail > _max_clip and tail > 0:
                tail -= 1
            while dur + head + tail > _max_clip and head > 0:
                head -= 1
            start, trim, dur = start - head, trim + head, dur + head + tail
        if dur != int(dur) or not (MIN_CLIP <= dur <= _max_clip):
            die(f"window w{i:02d}: {dur:g}s is not a valid clip length for {args.route!r}. {VALID_NOTE}")
        covered = round(dur - trim - tail, 3)
        sid, label = style_at(start + trim + covered / 2, i)
        voice = os.path.join(voice_dir, f"w{i:02d}.mp4")
        build_voice(voice_src, max(0.0, start), dur, voice, args.ffmpeg, w, h, source=args.voice_source)
        job = {"id": f"w{i:02d}", "window": i, "styleId": sid, "section": label,
               "startSec": start, "seconds": dur, "trimStartSec": trim, "synced": True,
               "tailSec": tail,
               "sungSec": ew.get("sungSec"),                 # the singing inside the clip (plan_coherence #12)
               # a landed clip whose sung geometry moved: named, never silently frozen
               **({"geometryStale": ew["geometryStale"]} if ew.get("geometryStale") else {}),
               # a lone short line carries the deliberate stretch margin; without this on
               # the JOB, plan_coherence #12 sees only the padding and refuses the plan
               "shortLineMargin": bool(ew.get("shortLineMargin")),
               "kind": ew.get("kind", "phrase"),
               "headSpill": float(ew.get("headSpill", 0.0)),
               "prompt": cite(prompts[sid], dur) + direction_at(start + trim + covered / 2),
               "identityRef": os.path.abspath(args.identity_ref),
               "voiceRef": os.path.abspath(voice),
               "voiceSource": args.voice_source}
        if sid in prompts_sung:
            job["promptSung"] = cite(prompts_sung[sid], dur) + direction_at(start + trim + covered / 2)
        if sid in prompts_silent:
            job["promptNoVoice"] = cite(prompts_silent[sid], dur) + direction_at(start + trim + covered / 2)
        if sid in prompts_other:
            job["promptOtherVoice"] = cite(prompts_other[sid], dur) + direction_at(start + trim + covered / 2)
        who = performer_of[sid]
        if who == "b":
            job["identityRef"] = os.path.abspath(args.identity_ref_2)
        elif who == "both":
            job["identityRef2"] = os.path.abspath(args.identity_ref_2)
        if sid in declared:
            job["performer"] = who
        jobs.append(job)
        t = start + dur - tail
        i += 1
    while not explicit and t < total - 0.05:
        remaining = total - t
        # The LAST window is the whole problem. A remainder is almost never a valid
        # duration, and asking for one anyway is what produced a 5 s clip for a
        # 7.56 s window. So render a full valid clip and SLIDE ITS START BACK so it
        # still ends exactly on the song's end; it then overlaps its predecessor by
        # `trim`, which the assembly skips off the front. Erring long is safe --
        # a picture shorter than its audio is not.
        trim = 0.0
        start = t
        if remaining < clip and total >= clip:
            trim = round(clip - remaining, 3)
            start = round(total - clip, 3)
        # total < clip is the degenerate case (a song shorter than one shot): there
        # is nothing to slide back into, so render one full clip from 0 and let the
        # assembly stop at the song's end.
        dur = clip
        covered = round(dur - trim, 3)
        sid, label = style_at(t + covered / 2, i)
        voice = os.path.join(voice_dir, f"w{i:02d}.mp4")
        build_voice(voice_src, start, dur, voice, args.ffmpeg, w, h, source=args.voice_source)
        job = {"id": f"w{i:02d}", "window": i, "styleId": sid, "section": label,
               "startSec": start, "seconds": dur,
               # How much of this clip the assembly skips off the FRONT. 0 on
               # every window but a slid-back final one.
               "trimStartSec": trim,
               "synced": True,
               "prompt": cite(prompts[sid], dur) + direction_at(t + covered / 2),
               "identityRef": os.path.abspath(args.identity_ref),
               "voiceRef": os.path.abspath(voice),
               "voiceSource": args.voice_source}
        if sid in prompts_sung:
            job["promptSung"] = cite(prompts_sung[sid], dur) + direction_at(t + covered / 2)
        if sid in prompts_silent:
            job["promptNoVoice"] = cite(prompts_silent[sid], dur) + direction_at(t + covered / 2)
        if sid in prompts_other:
            job["promptOtherVoice"] = cite(prompts_other[sid], dur) + direction_at(t + covered / 2)
        # Performer b's Image 1 IS the second portrait; `both` carries it as Image 2.
        # Refs ride in order image, image, audio so @IMG_2 -> <<<image_2>>>.
        who = performer_of[sid]
        if who == "b":
            job["identityRef"] = os.path.abspath(args.identity_ref_2)
        elif who == "both":
            job["identityRef2"] = os.path.abspath(args.identity_ref_2)
        if sid in declared:
            job["performer"] = who
        jobs.append(job)
        t += covered
        i += 1
    if not jobs:
        die("no windows produced — is hook.durationSec zero?")
    if args.vocal_brief:
        apply_vocal_brief(jobs, args.vocal_brief, args.pronouns, performer_of, declared,
                          performer_names=args.performer_names,
                          hook_wav=voice_src, ffmpeg=args.ffmpeg, voice_source=args.voice_source,
                          timestamps=not args.no_timestamps)
    if args.shot_refs:
        if not args.vocal_brief:
            die("--shot-refs needs --vocal-brief: only a brief says which windows sing")
        apply_shot_refs(jobs, args.shot_refs, os.path.abspath(args.identity_ref), args.pronouns,
                        motion_donor=args.motion_donor,
                        portrait2=os.path.abspath(args.identity_ref_2) if args.identity_ref_2 else "",
                        names=args.performer_names)
    # An authored shot list (SHOTS_FILE) sits BESIDE shot-refs, not under it: a film with
    # no reference video still gets its per-window setup. shot-refs runs first because it
    # rewrites the identity sentence; apply_shots only touches the framing head and the ref.
    if args.shots:
        apply_shots(jobs, args.shots)
    # Without a brief nothing knows which windows sing, so every window keeps the motion
    # prompt (today's behaviour); a sung prompt is only ever chosen by apply_vocal_brief.
    for job in jobs:
        job.pop("promptSung", None)
        job.pop("promptNoVoice", None)
        job.pop("promptOtherVoice", None)

    plan = {"schemaVersion": 1, "lane": "explore", "route": args.route,
            "constants": plan_constants(_max_clip, clip),
            "inputs": {name: {"path": path, "sha256": raplib.sha256_file(path)}
                       for name, path in (("brief", args.vocal_brief or ""), ("windows", args.windows or ""),
                                          ("hook", hook_path), ("shotRefs", args.shot_refs or "")) if path},
            # The film's length, for the gates that ask whether the plan reaches its end
            # (plan_coherence #3, select_cut's outro section): the hook is an input of
            # the plan, so a re-picked hook also fails #17 rather than silently misfitting.
            "hookSeconds": round(total, 3),
            "aspect": args.aspect,           # REQUIRED: the default elsewhere is 16:9
            "resolution": args.resolution, "seconds": args.clip_seconds,
            "projectDir": os.path.abspath(args.project),
            "queueDir": os.path.join(build, "queue", "explore"),
            "identityRef": os.path.abspath(args.identity_ref),
            # What every voice slice was cut from — the gates that correlate a slice
            # against its source (plan_coherence #11, the contract's slice badge) read it
            # here rather than assuming hook.wav.
            "voiceSource": args.voice_source, "voiceWav": os.path.abspath(voice_src),
            "jobs": jobs}
    if args.identity_ref_2:
        plan["identityRef2"] = os.path.abspath(args.identity_ref_2)
    if args.workspace_root:
        plan["workspaceRoot"] = args.workspace_root
    if args.no_word_verify:
        plan["verifyWords"] = False
    if args.pronouns:
        plan["pronouns"] = args.pronouns      # he|she per performer — coherence #15 reads it

    out = args.out or os.path.join(build, "plan.json")
    with open(out, "w", encoding="utf-8") as fh:
        json.dump(plan, fh, indent=2)
        fh.write("\n")

    per: dict[str, int] = {}
    for j in jobs:
        per[j["styleId"]] = per.get(j["styleId"], 0) + 1
    # What follows the last word is named, not lost: GAP_TO_BROLL_S or more is an outro
    # B-roll section (select_cut opens it), less was absorbed into the last render.
    # (the clip's zero sits at startSec; trimStartSec is skipped off its FRONT, so the
    # covered picture still ends at startSec + seconds - tailSec — select_cut's dur)
    film_end = max((float(j.get("startSec") or 0) + float(j.get("seconds") or 0)
                    - float(j.get("tailSec") or 0) for j in jobs), default=0.0)
    outro = round(total - film_end, 2)
    print(f"make_plan: {len(jobs)} window(s) covering {t:.2f}s of {total:.2f}s "
          f"@ {args.clip_seconds:g}s"
          + (f" (+{outro:.2f}s after the last word: an outro B-roll section)" if outro >= GAP_TO_BROLL_S else "")
          + f" -> {out}", file=sys.stderr)
    for k, v in sorted(per.items(), key=lambda kv: -kv[1]):
        print(f"  {v:2d}  {k}", file=sys.stderr)
    if not sections:
        print("  (styles dealt round-robin — pass --sections to place them)", file=sys.stderr)


if __name__ == "__main__":
    main()
