#!/usr/bin/env bash
# 3d-animation-short — MASTER gated step-runner.
#
# Advances the whole short from a story idea to a finished film, PAUSING at every
# human gate (exit 10). Do the work the gate prints, then re-run the SAME
# command: re-run IS approval. Completed stages are recorded in build/3d-state
# and skipped. To re-roll a PAID artifact, DELETE it and re-run — nothing that
# already exists is ever re-bought.
#
# It sequences commands videoclaw already owns. The only logic here is the ORDER
# and the GATES; every artifact is produced by `vclaw video ...` or by this
# skill's four python scripts. Every command and flag below was checked against
# the dispatch table rather than written from memory — an earlier draft invented
# `execute --route`, `execute --scenes`, `show-preflight --route` and a
# `story-bible` subcommand, none of which exist.
#
# Usage:  make-3d-short.sh <pack> <slug> [--restart] [--from <stage>]

# shellcheck source=lib/common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/common.sh"

PACK="${1:-}"; SLUG="${2:-}"
[ -n "$PACK" ] && [ -n "$SLUG" ] || die "usage: make-3d-short.sh <pack> <slug> [--restart] [--from <stage>]"
shift 2

STAGES="scaffold brief scenes bible cast plates shot-table selfcheck contract keyframes assets render-one render-all assemble bgm polish qc preview"

RESTART=0; FROM=""
while [ $# -gt 0 ]; do
  case "$1" in
    --restart) RESTART=1 ;;
    --from) shift; FROM="${1:-}" ;;
    *) die "unknown flag: $1" ;;
  esac
  shift
done

load_env
load_preset "$PACK"
P="$(project_dir "$SLUG")"
load_video_env "$P" 2>/dev/null || true

mkdir -p "$P/build"
STATE="$P/build/3d-state"
# --restart must clear the HUMAN gates too, not just the stage ledger. They live
# in separate sentinel files, and leaving them behind makes "restart" walk the
# whole pipeline past every approval with no human present: the contract gate
# and the route-lock assertion are inside `[ ! -f contract-approved ]`, the
# shot-1 spend review is inside `[ ! -f shot1-submitted ]`, and the sign-off is
# inside `[ ! -f film-signed-off ]`. A restarted run skipped all three — and
# rendered nothing, because shot1-submitted also gates the render itself.
if [ "$RESTART" = "1" ]; then
  rm -f "$STATE" \
        "$P/build/contract-approved" \
        "$P/build/shot1-submitted" \
        "$P/build/film-signed-off"
fi
if [ -n "$FROM" ]; then
  case " $STAGES " in *" $FROM "*) ;; *) die "unknown stage '$FROM'. Stages: $STAGES" ;; esac
  if [ -f "$STATE" ]; then
    keep=""; hit=0
    for s in $STAGES; do
      [ "$s" = "$FROM" ] && hit=1
      [ "$hit" = "1" ] && continue
      grep -qx "$s" "$STATE" 2>/dev/null && keep="$keep$s"$'\n'
    done
    printf '%s' "$keep" > "$STATE"
  fi
fi

done_stage(){ grep -qx "$1" "$STATE" 2>/dev/null; }
mark(){ grep -qx "$1" "$STATE" 2>/dev/null || echo "$1" >> "$STATE"; }

# --- pack-derived settings --------------------------------------------------
ROUTE="${ROUTE:-veo-useapi}"
ASPECT="${ASPECT:-16:9}"
SHORT_DURATION="${SHORT_DURATION:-45}"
SHOT_MAX_SECONDS="${SHOT_MAX_SECONDS:-15}"
CAST_MAX_PER_SHOT="${CAST_MAX_PER_SHOT:-3}"
STYLE_LOCK="${STYLE_LOCK:-pixar}"
DIALOGUE_MODE="${DIALOGUE_MODE:-none}"
BGM_BACKEND="${BGM_BACKEND:-lyria3}"
POOL_CONCURRENCY="${POOL_CONCURRENCY:-2}"
TARGET_LUFS="${TARGET_LUFS:--14}"
TARGET_TP="${TARGET_TP:--1.5}"

TABLE="$P/artifacts/shot-table.json"

# ---- 1. scaffold -----------------------------------------------------------
if ! done_stage scaffold; then
  log "scaffold: $SLUG (route $ROUTE, aspect $ASPECT, ${SHORT_DURATION}s)"
  require_route
  # Test project.json, not the directory: build/ was created above, so a
  # directory test would always be true and init would never fire.
  [ -f "$P/project.json" ] || vclaw video init "$SLUG" --mode storyboard --root "$VCLAW_WORKSPACE" >/dev/null
  # The render route lives in the manifest as `routePreference`, not on a CLI
  # flag — there is no `--route` on execute or pool. The on-disk project is the
  # source of truth, so setting it here is the supported path, and it is what
  # makes "one film, one route" hold for every driver that reads the manifest.
  python3 - "$P/project.json" "$ROUTE" <<'PY'
import json, sys
path, route = sys.argv[1], sys.argv[2]
with open(path, encoding="utf-8") as fh:
    manifest = json.load(fh)
if manifest.get("routePreference", [None])[:1] != [route]:
    manifest["routePreference"] = [route]
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(manifest, fh, indent=2)
        fh.write("\n")
    print(f"  routePreference -> {route}", file=sys.stderr)
PY
  mark scaffold
fi

# ---- 2. brief (gate: the format decisions the method makes up front) --------
if ! done_stage brief; then
  if [ ! -f "$P/artifacts/brief.json" ]; then
    gate "write the brief, and fix the format up front" \
"The method settles aspect and duration BEFORE any story work, because both
change the shot count and every artifact downstream of it.

  vclaw video brief --project $SLUG --title '<title>' --intent '<one-line what-if>' \\
    --root \"\$VCLAW_WORKSPACE\"

Pack says: aspect $ASPECT, ${SHORT_DURATION}s total, dialogue '$DIALOGUE_MODE'.
  * Dialogue LANGUAGE is never assumed. Leave it unset unless the operator named one.
  * Prove a 3-shot, ~20s short first. It exercises every gate in this runner for a
    fraction of the credits."
  fi
  mark brief
fi

# ---- 3. scenes (gate: the shot spine) --------------------------------------
if ! done_stage scenes; then
  if [ ! -f "$P/artifacts/storyboard.json" ]; then
    gate "lay out the shots" \
"Turn the story spine into the scene list. Pass EVERY scene in ONE command —
--scene REPLACES the list rather than appending, so a second call drops the first:

  vclaw video storyboard --project $SLUG \\
    --scene '<shot 1>' --scene '<shot 2>' --scene '<shot 3>' \\
    --root \"\$VCLAW_WORKSPACE\"

Story gates before you commit to it:
  * The protagonist ACTS; they are not carried by events.
  * The crisis is worsened by the protagonist's own flaw.
  * No coincidence solves the problem.
  * The ending reuses an emotional anchor planted earlier.
  * Pressure comes from a real position, not a flat villain.
  * No shot longer than ${SHOT_MAX_SECONDS}s, no more than $CAST_MAX_PER_SHOT acting characters in one."
  fi
  mark scenes
fi

# ---- 4. bible (optional continuity derivation) -----------------------------
if ! done_stage bible; then
  # There is no `vclaw video story-bible` subcommand: the artifact is written as
  # a side effect. This is best-effort on purpose — make_shot_table.py treats the
  # bible as optional and falls back to the storyboard alone.
  if [ ! -f "$P/artifacts/story-bible.json" ]; then
    log "bible: deriving continuity (optional)"
    vclaw video director-preflight --project "$SLUG" --apply-content-fixes \
      --root "$VCLAW_WORKSPACE" >/dev/null 2>&1 || \
      warn "no story bible derived — the shot table will scaffold from the storyboard alone"
  fi
  mark bible
fi

# ---- 5. cast (cheap GB; gate: lock identity) -------------------------------
if ! done_stage cast; then
  if [ ! -f "$P/artifacts/reference-sheets.json" ] && [ ! -f "$P/characters/characters.json" ]; then
    gate "build the cast" \
"Generate a labelled reference sheet per character:

  vclaw video character-auto-create --project $SLUG --root \"\$VCLAW_WORKSPACE\"

  * Sheets carry readable labels; the RENDERED FILM never does.
  * Identity is locked by the ROUTE, not by the sheet alone:
      veo-useapi      -> register each one first
                         (vclaw video flow-register-characters --project $SLUG)
      seedance-direct -> register as Asset Library avatars
                         (vclaw video seedance-register-assets --project $SLUG)
      runway/dreamina -> the sheet plus a rich visual descriptor in the prompt
    See references/route-matrix.md.
  * Changing a locked design later invalidates the shot table, the composed
    prompts and every clip already rendered."
  fi
  mark cast
fi

# ---- 6. plates (cheap GB; environments ONLY) -------------------------------
if ! done_stage plates; then
  if [ ! -f "$P/artifacts/environment-assets.json" ]; then
    gate "lock the environments" \
"Generate one plate per location — NO people in them, which is what this command
already does and what the method requires (character action belongs in the shots):

  vclaw video environment-auto-create --project $SLUG --root \"\$VCLAW_WORKSPACE\"

Then note, per location, the FIXED LANDMARKS whose screen position must hold
across the scene (door frame, island, tree, mailbox). The anchor chain is built
from that list, and the drift audit after the render is only as good as it is."
  fi
  mark plates
fi

# ---- 7. shot-table (scaffold, then the one genuinely creative step) --------
if ! done_stage shot-table; then
  log "shot-table: scaffolding rows from the storyboard"
  python3 "$ANIM_SCRIPTS/make_shot_table.py" --project "$P" \
    --style-lock "$STYLE_LOCK" --max-shot-seconds "$SHOT_MAX_SECONDS" >/dev/null
  need="$(python3 -c "
import json
t=json.load(open('$TABLE'))
print(' '.join(s['id'] for s in t['shots'] if not any(
    any(str(b.get(k,'')).strip() for k in ('action','camera','spatial','audio','handoff'))
    for b in s.get('beats',[]))))
")"
  if [ -n "$need" ]; then
    gate "author the per-second direction" \
"$TABLE is scaffolded. These shots have no direction yet: $need

For EVERY beat, all five: action / camera / spatial / audio / handoff.
An intended silence is the literal 'silent', never an empty field.
Also per shot: hookType, scene, continuity.from and .to, and the anchor block
(landmarks with screen positions, character positions, lighting, and anyone who
has just left the frame).

This is the one step no tool can do for you, and it is where the film is
actually directed. See references/shot-table-spec.md."
  fi
  mark shot-table
fi

# ---- 8. selfcheck (THE gate — six checks, refuses to advance) --------------
if ! done_stage selfcheck; then
  log "selfcheck: the six checks"
  if ! python3 "$ANIM_SCRIPTS/check_shot_table.py" --table "$TABLE" --stamp \
        --max-shot-seconds "$SHOT_MAX_SECONDS" --max-cast "$CAST_MAX_PER_SHOT" \
        --target-seconds "$SHORT_DURATION" --json-out "$P/build/selfcheck.json"; then
    gate "fix the shot table" \
"The six checks refused the table (detail above, and in $P/build/selfcheck.json).
Fix the named rows and re-run. Nothing composes or renders until all six pass —
that is the whole point of the gate."
  fi
  mark selfcheck
fi

# ---- 9. contract (free): the preview IS the contract, BEFORE any spend -----
if ! done_stage contract; then
  log "contract: composing the table down into the storyboard"
  # Capture `changed` so an edited prompt REVOKES the approval below. Without
  # that, a re-run after a prompt change would sail past the contract gate on
  # the strength of an approval given to different text.
  compose_out="$(python3 "$ANIM_SCRIPTS/apply_shot_table.py" --project "$P")"
  if [ -n "$(printf '%s' "$compose_out" | python3 -c 'import json,sys; print(",".join(json.load(sys.stdin)["changed"]))')" ]; then
    rm -f "$P/build/contract-approved"
  fi
  # --write is not optional here. filmmaking-prompts PRINTS its artifact by
  # default and only PERSISTS it with --write, while prompt-lint reads the
  # persisted file — so without it the lint fails with "artifact not found" and
  # the runner blames the lint for a step that never happened. Found by running
  # this, not by reading it.
  # --phase storyboard on purpose. It keeps the storyboard/camera-language half
  # and the referenceMap, but gates the VIDEO packets to [] — and a ready video
  # packet OUTRANKS scenePrompt.animationPrompt in execution-runtime, which would
  # silently discard everything composed above, after the operator approved it.
  vclaw video filmmaking-prompts --project "$SLUG" --phase storyboard --write \
    --root "$VCLAW_WORKSPACE" >/dev/null || \
    gate "filmmaking-prompts failed" \
"It could not build the packets (error above). The composed storyboard prompts
are already written, so nothing is lost — fix what it named and re-run."
  vclaw video prompt-lint --project "$SLUG" --root "$VCLAW_WORKSPACE" || \
    gate "the prompt lint refused the packets" \
"Fix what it named, then re-run. Linting BEFORE spend is the cheapest review there is."
  # show-preflight is INERT without a show-bible — it returns ready:true having
  # checked nothing, which is worse than no gate at all. Derive one first, then
  # assert the gate actually engaged.
  [ -f "$P/artifacts/show-bible.json" ] || \
    vclaw video show-bible --project "$SLUG" --root "$VCLAW_WORKSPACE" >/dev/null || \
    warn "could not derive a show-bible"
  preflight="$P/build/show-preflight.json"
  vclaw video show-preflight --project "$SLUG" --root "$VCLAW_WORKSPACE" > "$preflight" || true
  python3 - "$preflight" "$ROUTE" <<'PY' || gate "the route is not ready for this cast" \
"show-preflight refused (detail above). It is route-aware and never fabricates a
registration — supply the missing piece, then re-run.
See references/route-matrix.md."
import json, sys
report = json.load(open(sys.argv[1], encoding="utf-8"))
if not report.get("bibleAdopted"):
    # Say so out loud. A readiness gate that passed because it checked nothing
    # reads identical to one that passed because everything was ready.
    print("  WARNING: show-preflight ran INERT (no show-bible adopted) — it verified", file=sys.stderr)
    print("           nothing about cast sheets, plates or voices for this route.", file=sys.stderr)
for blocker in report.get("blockers", []):
    print(f"  BLOCKER: {blocker}", file=sys.stderr)
sys.exit(0 if report.get("ready") else 1)
PY
  # The gate must be REACHABLE PAST. `gate` exits 10, so an unconditional call
  # here makes `mark contract` dead code and the stage can never complete —
  # the runner loops on it forever. The sentinel is what makes "re-run IS
  # approval" true for a gate that has no artifact of its own to test for, and
  # composing above deletes it whenever the prompts change.
  if [ ! -f "$P/build/contract-approved" ]; then
    touch "$P/build/contract-approved"
    assert_route_locked || gate "the film would render on the WRONG route" \
"The pack asks for '$ROUTE' and the plan resolves something else (detail above).
Usually a missing credential for $ROUTE, which makes the planner fall down its
preference list silently — the pack, project.json and every gate still say
$ROUTE while the clips go somewhere else, and one film rendered across two
providers has a visible style seam.

Fix the credential (or change ROUTE in the pack deliberately), then re-run."
  gate "approve the submit contract" \
"Read the EXACT prompts that will be submitted:

  python3 $ANIM_SCRIPTS/apply_shot_table.py --project $P --dry-run
  vclaw video portal --project $SLUG --root \"\$VCLAW_WORKSPACE\"
  open -a \"Google Chrome\" $P/build/preview-portal/review.html

Check each prompt against the shot it claims to be, and the references against
the cast it claims to lock. This is the last free moment before the film costs
something."
  fi
  mark contract
fi

# ---- 10. keyframes (cheap GB, one PER SHOT) --------------------------------
if ! done_stage keyframes; then
  # Count keyframes PER SHOT, not "is references/ non-empty". The loose test
  # passed on a project holding only character sheets and a location plate, and
  # execute then blocked on a missing asset-manifest — after the runner had
  # already told the operator the setup was ready.
  shot_count="$(python3 -c "import json;print(len(json.load(open('$TABLE'))['shots']))")"
  kf_count="$(ls "$P/references"/kf-*.* 2>/dev/null | wc -l | tr -d ' ')"
  if [ "$kf_count" -lt "$shot_count" ]; then
    gate "generate one keyframe per shot" \
"$kf_count of $shot_count keyframes present. This route is image-to-video: every
shot needs its own start frame, named $P/references/kf-s01.jpg (one per shot).

  * Nano Banana (gemini-flash-image) for stills — markedly cheaper than
    gpt-image-2 at the same job.
  * gpt-image-2 stays the rule for multi-panel GRIDS only.
  * Build each from the cast sheets AND the location plate so identity and the
    anchor chain both survive.
  * Every character the shot LISTS must be visible in its keyframe. On an
    image-to-video route the start frame is the identity lock; a character who
    is only in the prompt gets invented, however well they are registered.
  * Frame 0 is the feed thumbnail: never let it read as a blank or a freeze."
  fi
  # The keyframe's ASPECT becomes the film's aspect. An off-aspect still gets
  # fitted into the video frame with black bars baked into the picture — a
  # quarter of the frame lost, discovered only after the render. Image models do
  # not reliably honour an aspect request: asked for 16:9 at 2k, two of three
  # keyframes came back 1584x672 (2.35:1) and both shots shipped letterboxed.
  python3 - "$P/references" "$ASPECT" <<'PY' || gate "a keyframe is the wrong shape" \
"Regenerate the keyframes listed above at the project aspect, then re-run.
Fixing this after the render means paying for the shot twice."
import glob, os, sys
from PIL import Image
refs, aspect = sys.argv[1], sys.argv[2]
w, h = (float(x) for x in aspect.replace(":", "/").split("/"))
target = w / h
bad = []
for path in sorted(glob.glob(os.path.join(refs, "kf-*.*"))):
    try:
        iw, ih = Image.open(path).size
    except Exception as exc:                       # noqa: BLE001 - report, never crash the gate
        bad.append(f"{os.path.basename(path)}: unreadable ({exc})")
        continue
    ratio = iw / ih
    if abs(ratio - target) / target > 0.02:
        bars = round(abs(ih - iw / target) / 2)
        bad.append(f"{os.path.basename(path)}: {iw}x{ih} is {ratio:.3f}:1, "
                   f"wanted {aspect} ({target:.3f}:1) — about {bars}px of black bar per edge")
for line in bad:
    print(f"  {line}", file=sys.stderr)
raise SystemExit(1 if bad else 0)
PY
  mark keyframes
fi

# ---- 10b. assets (bind each keyframe to its scene) -------------------------
# execute needs an asset-manifest and will BLOCK without one. It exits 0 while
# doing so, which is how a missing stage looked like a successful render.
if ! done_stage assets; then
  if [ ! -f "$P/artifacts/asset-manifest.json" ]; then
    log "assets: binding keyframes to scenes"
    asset_args=()
    i=0
    for kf in "$P/references"/kf-*.*; do
      asset_args+=(--asset "image:$kf:$i")
      i=$((i + 1))
    done
    vclaw video assets --project "$SLUG" "${asset_args[@]}" --root "$VCLAW_WORKSPACE" >/dev/null || \
      die "could not build the asset manifest"
  fi
  mark assets
fi

# ---- 11. render ONE shot (gate) -------------------------------------------
if ! done_stage render-one; then
  python3 "$ANIM_SCRIPTS/check_stale_outputs.py" --project "$P" || \
    gate "clear the stale outputs first" \
"A clip older than the prompt describing it makes the resumable driver SKIP that
scene, and you then review the previous render believing it is the new one.
Clear them (command above), then re-run."
  # Guarded, and the guard is the SPEND control. An unconditional gate here
  # makes `mark render-one` dead code, so every re-run re-submits shot 1 and
  # buys it again — the most expensive shape of the same bug the contract stage
  # had. Re-rolling shot 1 is therefore deliberate: delete the sentinel.
  if [ ! -f "$P/build/shot1-submitted" ]; then
    assert_route_locked || die "refusing to render: the plan does not resolve '$ROUTE' (detail above)"
    log "render-one: submitting shot 1 on $ROUTE"
    touch "$P/build/shot1-submitted"
    vclaw video execute --project "$SLUG" --scene 0 --root "$VCLAW_WORKSPACE" || {
      rm -f "$P/build/shot1-submitted"
      die "the first render failed — do not batch the rest"
    }
    # execute EXITS 0 WHEN IT BLOCKS. It writes status:"blocked" with the reason
    # into the execution report and returns success, so trusting the exit code
    # told the operator to go and approve a shot that was never submitted — the
    # exact failure the gate below warns about, committed by the runner itself.
    assert_submitted || {
      rm -f "$P/build/shot1-submitted"
      die "shot 1 did not reach the provider (detail above). Nothing was spent."
    }
    gate "approve shot 1" \
"Verify the OUTCOME, not that the command ran:

  vclaw video execute-status --project $SLUG --root \"\$VCLAW_WORKSPACE\"

Then pull a frame and LOOK at it. Check identity, that the fixed landmarks
landed where the table said, and the lighting. Wrong? Fix the row, re-run the
selfcheck and the contract, clear the stale output, and re-render THIS shot
only. Never batch the rest on an unreviewed setup.

To buy shot 1 again on purpose: rm $P/build/shot1-submitted"
  fi
  mark render-one
fi

# ---- 12. render the rest ---------------------------------------------------
if ! done_stage render-all; then
  python3 "$ANIM_SCRIPTS/check_stale_outputs.py" --project "$P" || \
    gate "clear the stale outputs first" "See above; then re-run."
  assert_route_locked || die "refusing to batch: the plan does not resolve '$ROUTE' (detail above)"
  log "render-all: the remaining shots sequentially on $ROUTE"
  # pool only enqueues now. The direct driver adopts in-flight jobs and skips
  # selected scenes; no fallback-chain means the film keeps its exact route.
  vclaw video render-scenes --project "$SLUG" --method "$ROUTE" \
    --confirm-spend --root "$VCLAW_WORKSPACE" > "$P/build/render-scenes-report.json" \
    || die "the scene driver stopped — see execute-status"
  python3 "$ANIM_SCRIPTS/check_render_result.py" "$P/build/render-scenes-report.json" \
    || gate "some shots are not complete" "Read build/render-scenes-report.json and execute-status. Diagnose failures before retrying; re-running adopts pending jobs without duplicate submission."
  # And then the outcome itself. A driver can report success at the top level
  # while individual scenes were skipped or left in flight — which is exactly
  # how this stage once completed with two of three clips missing.
  assert_clips_present "$(python3 -c "import json;print(len(json.load(open('$TABLE'))['shots']))")" || \
    gate "not every shot has a clip yet" \
"The driver finished but some scenes have no clip on disk (named above). Usually
one of two things:

  * a job is still in flight — just re-run to keep polling; or
  * a scene is being SKIPPED because its selection still names a winning
    candidate whose clip was deleted. Clear it:

      python3 $ANIM_SCRIPTS/check_stale_outputs.py --project $P --delete

Then re-run."
  mark render-all
fi

# ---- 13. assemble (free: ordered concat, videoclaw already owns it) --------
if ! done_stage assemble; then
  # Reconcile plan against reality BEFORE stitching. assemble concatenates whole
  # clips, so a mismatch here becomes a film whose length contradicts its own
  # shot table, recorded nowhere.
  assert_planned_duration || \
    gate "the render length does not match the plan" \
"Routes render in their own increments and ignore the table's per-shot seconds
(detail above). assemble concatenates WHOLE clips, so stitching now ships a film
whose length contradicts its own shot table.

Pick one, deliberately:
  * accept the rendered lengths — update durationSeconds in
    $TABLE to what actually rendered, re-run the selfcheck, then re-run; or
  * cut to the plan — trim each outputs/scene-N.mp4 to its planned length
    (ffmpeg -i in.mp4 -t <seconds> -c copy out.mp4) and re-run.

Either is fine. Shipping a 20-second plan as a 24-second film is not."
  log "assemble: stitching in table order"
  vclaw video assemble --project "$SLUG" --from-clips --root "$VCLAW_WORKSPACE" || die "assemble failed"
  mark assemble
fi

# ---- 14. bgm (one continuous track, ducked under speech) ------------------
if ! done_stage bgm; then
  if [ ! -f "$P/artifacts/soundtrack.json" ]; then
    # soundtrack REQUIRES --prompt; without it the stage dies on a missing flag
    # after the film is already stitched. Derive one from the pack when the
    # operator has not written a better line, and say which was used.
    bgm_prompt="${BGM_PROMPT:-}"
    if [ -z "$bgm_prompt" ]; then
      bgm_prompt="A short warm orchestral cue for a gentle animated short set in ${WORLD_DESC:-a domestic interior}. Light strings and woodwind, unhurried, a small mischievous turn in the middle and a soft resolve at the end. Instrumental only, no vocals."
      log "bgm: no BGM_PROMPT in the pack — using a derived cue"
    fi
    log "bgm: $BGM_BACKEND (${SHORT_DURATION}s)"
    vclaw video soundtrack --project "$SLUG" --backends "$BGM_BACKEND" \
      --prompt "$bgm_prompt" --duration "$SHORT_DURATION" --instrumental \
      --confirm-spend --root "$VCLAW_WORKSPACE" || die "soundtrack failed"
    # Generating a candidate does NOT select it, and assemble only mixes the
    # SELECTED track — so without this the film ships silent under the picture
    # while artifacts/audio/ holds a perfectly good cue nobody wired in.
    vclaw video soundtrack --project "$SLUG" --select "$BGM_BACKEND" \
      --root "$VCLAW_WORKSPACE" >/dev/null || die "could not select the soundtrack"
    # And the master was stitched before the music existed: restitch or the
    # picture keeps the silent mix. Drop `assemble` from the stage ledger so the
    # next pass redoes it.
    #
    # This used to be `sed -i '' '/^assemble$/d'` guarded by `|| true` — BSD
    # syntax, so on GNU sed it failed SILENTLY and the film shipped with the
    # pre-music mix. grep -v is portable and the `|| true` here is honest: an
    # empty ledger is a legitimate result. (A companion `rm -f
    # build/3d-state.assemble-done` was removed: nothing in the repo ever wrote
    # that path.)
    if [ -f "$STATE" ]; then
      grep -vx 'assemble' "$STATE" > "$STATE.tmp" 2>/dev/null || true
      mv -f "$STATE.tmp" "$STATE" 2>/dev/null || rm -f "$STATE.tmp"
    fi
    gate "approve the track" \
"Play it against the cut. ONE continuous track for the whole film, never one per
shot. Not right? DELETE artifacts/soundtrack.json and re-run to buy another.
Then re-run assemble so the mix picks it up, ducked under speech and key effects."
  fi
  mark bgm
fi

# ---- 15. polish (free): normalise, poster, and DELIVER ---------------------
# The stage that was missing. assemble leaves the master in outputs/, which is
# the WORKING area — so the film never reached final/videos/, the preview page
# showed the three raw scene clips and no finished film at all, and
# verify-final had nothing to check. A film nobody can find is not delivered.
if ! done_stage polish; then
  master="$P/outputs/final.mp4"
  [ -f "$master" ] || die "no assembled master at $master"
  mkdir -p "$P/final/videos" "$P/final/images" "$P/final/audio"
  delivered="$P/final/videos/$SLUG.mp4"
  if [ ! -f "$delivered" ]; then
    log "polish: normalising to ${TARGET_LUFS} LUFS and delivering"
    # Two-pass loudnorm using MEASURED values, then a limiter AFTER the gain
    # with level=disabled — so it limits instead of re-normalising and undoing
    # itself. A loudness-only pass happily ships files that clip.
    meas="$(ffmpeg -hide_banner -i "$master" \
      -af "loudnorm=I=${TARGET_LUFS}:TP=${TARGET_TP}:LRA=11:print_format=json" \
      -f null /dev/null 2>&1 | python3 "$ANIM_SCRIPTS/read_loudness.py")"
    IFS=: read -r m_i m_tp m_lra m_thresh m_off <<<"$meas"
    [ -n "$m_i" ] || die "could not measure the master's loudness"
    ffmpeg -hide_banner -v error -i "$master" \
      -af "loudnorm=I=${TARGET_LUFS}:TP=${TARGET_TP}:LRA=11:measured_I=$m_i:measured_TP=$m_tp:measured_LRA=$m_lra:measured_thresh=$m_thresh:offset=$m_off:linear=true,alimiter=limit=0.87:level=disabled,aresample=48000" \
      -c:v copy -c:a aac -b:a 192k -movflags +faststart "$delivered" -y \
      || die "the loudness pass failed"
  fi
  # A poster from a COMPOSED frame, not frame 0 by reflex — frame 0 is the feed
  # thumbnail, and an opening wide is rarely the best still of a film.
  poster="$P/final/images/$SLUG-poster.jpg"
  if [ ! -f "$poster" ]; then
    mid="$(ffprobe -v error -show_entries format=duration -of default=nk=1:nw=1 "$delivered" \
      | python3 -c 'import sys; print(round(float(sys.stdin.read().strip() or 0) / 2, 2))')"
    ffmpeg -v error -ss "$mid" -i "$delivered" -frames:v 1 -q:v 2 "$poster" -y \
      || warn "no poster extracted"
  fi
  # The portal surfaces only final/{videos,images,audio}, so the score has to be
  # delivered too or the preview page has no player.
  if [ -f "$P/artifacts/soundtrack.json" ] && [ -z "$(ls -A "$P/final/audio" 2>/dev/null)" ]; then
    src="$(python3 "$ANIM_SCRIPTS/read_soundtrack.py" "$P")"
    [ -n "$src" ] && [ -f "$src" ] && cp "$src" "$P/final/audio/$SLUG-score.mp3"
  fi
  # --silent PLAYS the file rather than trusting DIALOGUE_MODE, because nothing
  # between the pack and the provider enforces it. --expect-seconds is the only
  # place the finished film is ever measured against the pack's target.
  silent_flag=""
  [ "$DIALOGUE_MODE" = "none" ] && silent_flag="--silent"
  python3 "$ANIM_SCRIPTS/check_delivery.py" --master "$delivered" --poster "$poster" \
    $silent_flag --expect-seconds "$SHORT_DURATION" \
    || gate "the delivered master is not clean" \
"Fix what is named above, delete $P/final/videos/$SLUG.mp4, and re-run."
  log "polish: delivered $delivered"
  mark polish
fi

# ---- 16. qc (gate: sign off the film) --------------------------------------
if ! done_stage qc; then
  log "qc: probing the master"
  vclaw video qc --project "$SLUG" --root "$VCLAW_WORKSPACE" || warn "qc reported findings — read them"
  vclaw video consistency-audit --project "$SLUG" --root "$VCLAW_WORKSPACE" >/dev/null 2>&1 || \
    warn "consistency-audit did not run (needs a vision key) — review identity by eye instead"
  if [ ! -f "$P/build/film-signed-off" ]; then
    touch "$P/build/film-signed-off"
    gate "sign off the film" \
"Check, in this order:
  * Identity holds across every shot — this is what drifts first.
  * The fixed landmarks landed where the anchor chain said they would.
  * No storyboard artefact survived into the picture: no panel borders, no
    labels, no arrows, no timing marks, no burnt-in text.
  * Audio present, speech intelligible, music sitting under it.
  * Frame 0 is a composed frame, not a blank.
Re-run to accept and build the preview."
  fi
  mark qc
fi

# ---- 17. preview -----------------------------------------------------------
if ! done_stage preview; then
  log "preview: the delivery surface"
  vclaw video portal --project "$SLUG" --surface preview --root "$VCLAW_WORKSPACE" >/dev/null || \
    warn "portal failed — the film is still in final/"
  mark preview
fi

log "done: $SLUG"
log "  film:  $P/final/"
log "  table: $TABLE"
