#!/usr/bin/env python3
"""compose_prompts.py — build the video prompt for each drawn style, and emit the
pre-spend review HTML.

THE PROMPT STRUCTURE IS LOAD-BEARING. A style block is not a prompt; it has to be
assembled into one that tells the model six separate things, and dropping any of
them changes the output:

  1. what kind of film this is            "A character rap MV <in the set>."
  2. what the image reference is FOR      the FACE ONLY — "preserve the same facial
                                          identity and face shape from the portrait
                                          WHILE CHANGING THE OUTFIT to <wardrobe>"
  2b. WHO is in the portrait              the --subject visual descriptor, written
                                          into the same sentence as the reference.
                                          The reference alone does not lock a face
                                          on these models; the prose does half the
                                          work, and make_plan's @IMG_1 citation is
                                          ADDED to this prose, never substituted.
  3. what the audio reference is FOR      "the rhythm and vocal performance
                                          reference ... rapping directly to camera,
                                          the final video including sound"
  4. the performance                      how he moves, on the beat
  5. the camera + look                    camera, palette, "stylized internal cuts"
  6. the negatives                        no subtitles / no on-screen text /
                                          no identity drift, jitter, bent limbs,
                                          hand close-ups

Point 2 is the one that is easy to get wrong and ruins the film: the portrait is an
IDENTITY reference, not a costume reference. Lock the wardrobe into the character
and every style renders in the same clothes, which turns a rap MV into a person
standing in different rooms wearing the same top.

Point 5's "stylized internal cuts" makes the model cut WITHIN the 8-second shot
instead of holding one static take.

Usage:
  compose_prompts.py --styles <styles.json> --drawn <styles-drawn.json>
                     --out-dir <build/> [--keyframe-dir <references/>]
                     [--duration 8] [--aspect 9:16] [--subject "a man"]
                     [--subject-2 "<second performer>"] [--pronouns "he|she"]
                     [--performer-names "A|B"] [--lyric-language English]
Writes <out-dir>/prompts.json and <out-dir>/storyboard.html.

TWO PERFORMERS. A style block may carry `"performer": "a" | "b" | "both"` (default
`a`). The performer is a property of the SCENE: windows get their style from
--sections, so the style decides whose face is in the shot. `a` is PORTRAIT +
--subject, `b` is PORTRAIT_2 + --subject-2, `both` cites Image 1 AND Image 2.
Pronouns are never inferred: --pronouns states one per performer, and a block for
`b` or `both` without a second subject is refused rather than rendered wrong.
"""
from __future__ import annotations

import argparse
import html
import json
import os
import re
import sys

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

# Applied to every prompt. The first two clauses are the house rule (nothing we
# render ever carries type); the rest are the failure modes these models actually
# exhibit and that a per-style negative would not think to name.
#
# The tail from "no extra fingers" onward was added 2026-08-06 after a 25-window
# film came back with three dead clips — an empty cityscape, a bare salt flat, and
# a rooftop where the performer was an ant. The camera lines had asked for a
# "drone-style rise pulling back over the whole city" and the model obliged. The
# lesson, borrowed from a K-pop MV prompt the operator found: BAN THE FAILURE MODE
# rather than wish for the good version. "Wild camera" is a wish; "no static hold,
# no empty establishing wide" is a constraint.
GLOBAL_NEGATIVE = ("no subtitles, no on-screen text, avoid identity drift, jitter, "
                   "bent limbs, and hand close-ups, no extra fingers, no sixth finger, "
                   "no duplicate or cloned faces, no slow motion, no freeze frames, "
                   "no static locked-off hold, no empty establishing wide with no "
                   "performer in it, no shot where the performer is a distant speck, "
                   "no flat-on symmetrical framing")

# DEFAULT-ON, unlike most additive options in this repo. A rap MV always wants its
# performer readable, so a style that does not say so is wrong rather than merely
# unopinionated — and the byte-identical-output convention exists to avoid surprise
# regressions, whereas here the surprise IS the fix. A style block can replace this
# sentence wholesale with its own `shot` field when a specific window wants
# something else.
SHOT_DISCIPLINE = (
    "Shot discipline: cover the take across a RANGE of shot sizes — open "
    "wide or full-body so the location reads, spend most of the take in "
    "medium and waist-up framing, and use a tight shot sparingly and "
    "briefly. The performer is never smaller than a third of the frame "
    "height, and never tighter than head-and-shoulders — {poss} {face} must not "
    "fill the frame. The camera keeps moving for the whole take and never "
    "settles into a held wide. "
)

# Applied whenever a block is NOT solo. Lifted from the same reference: naming the
# body parts is what stops "dancing" rendering as people waving their arms on the
# spot, which is exactly what the first pass of one stage came back as.
PERFORMANCE_RULE = ("Everyone dances with their whole body — footwork, level changes, "
                    "hips, spins, torso and legs — not arms waving on the spot.")

# Opt-in via the register's `maskedEnsemble`. An ensemble has no reference image, so
# its members differ shot to shot; identical masks remove the thing that can drift
# and look deliberate rather than accidental. The protagonist stays unmasked, which
# also makes him the only face the eye can land on.
MASKED_ENSEMBLE = ("Every dancer wears an identical plain white full-face mask that "
                   "completely hides their features; the protagonist is the only "
                   "unmasked face in the film.")
MASKED_NEGATIVE = ("no unmasked dancer, no mask resembling the protagonist's face, "
                   "no second unmasked person")

# The second performance register. Until now every block was "dance hard", which is
# wrong for a cold, still, fashion-film beat — and there was no way to ask for one.
# `performanceMode: "still"` selects this. Its negative matters as much as its text:
# without banning big choreography explicitly the model reverts to dancing.
# THE REGISTER ITSELF DIRECTED THE SLOW VOCAL. This rule used to read "hold a still
# posture ... turn the head slowly ... rap short clipped phrases", injected into every
# `performanceMode: still` block — so rewording the block's own sentence changed nothing
# (mirror-corridor, 2026-08-22: on time at 0-2 s, +1.3 s late by 8-10 s). The body stays
# still; the VOCAL is locked to the track, said in the same sentence.
STILLNESS_RULE = ("Small movement, heavy atmosphere: {subj} stand{s} planted and look{s} "
                  "straight down the lens, a sharp head-turn on the beat, adjust{s} a chain "
                  "or a ring, and the vocal is crisp and locked tight to the beat, every "
                  "clipped phrase landing exactly on the drum. Cold, confident, provocative.")
STILLNESS_NEGATIVE = ("no big choreography, no uniform group choreography, no sweet or "
                      "cute expression, no soft romantic focus, no gentle slow push-in")

# The third register. Neither dancing nor coldly still: the camera merely passes
# someone living in their own space. Taken from a prompt whose direction is
# explicitly anti-performance — "she is not performing", no dance-type, idol-type
# or strong-emotion acting, the mouth only faintly humming, never addressing the
# lens. Without this, "not dancing" could only be expressed as "cold and
# provocative", which is a different film.
# "at their own pace ... only lightly shaping the words" told a SUNG window to drift and
# under-mouth; the manner stays unhurried, the singing is locked to the track.
AMBIENT_RULE = ("{Subj} {be} not performing for the camera — it simply passes through {poss} "
                "space while {subj} move{s} self-contained and unhurried in manner, the "
                "singing locked exactly to the track, {poss} {mouth} shaping every sung word "
                "precisely and softly.")
AMBIENT_NEGATIVE = ("no big choreography, no uniform group choreography, no idol-style "
                    "posing, no direct address to the lens, no exaggerated expression")

# CORE DIRECTIVE, verbatim in spirit from the strongest reference in the library.
# Camera and performance were two independent paragraphs that we hoped would
# cohere; this makes them ONE system, and it is structurally the fix for the
# distant-performer failure — someone chasing the lens cannot end up small in it.
# The deliberate LAG is the craft detail: perfect tracking reads as robotic.
CAMERA_COUPLING = ("The camera leads and the performer follows: {poss} eyes stay locked on "
                   "the lens, {poss} body rotates on-axis to stay squared to it, and {poss} "
                   "footwork chases its movement — pressing forward when it retreats, "
                   "pivoting when it orbits, counter-lunging back when it pushes in, "
                   "always half a step behind so {subj} read{s} as pursuing the camera rather "
                   "than matching it.")

# SUNG WINDOWS ARE FRAMED FOR SYNC, NOT FOR MOTION. Every published Seedance lip-sync
# guide says the same thing for a line that must land on the track: a locked medium
# close-up, front-on, no head turn, at most a slow minimal push-in; drift, orbits and a
# performer chasing the lens are where sync goes to die. Our sung prompts asked for the
# opposite (a lateral drift, rising from a sofa to a mic, the camera coupling) and
# Smooth Like That's w11 sang the right words at the wrong rhythm three times
# (2026-08-29). The style's motion register is not lost: it stays on the instrumental
# (no-voice) windows and on the B-roll, where nothing has to sync.
# TWO SUNG WINDOWS IN ONE WORLD, BACK TO BACK, MUST NOT SHARE A FRAME. w08 and w09 were
# the same courtyard, the same pair, the same locked medium close-up — the cut between
# them read as a skip in the same shot (Baby Ram & Sita v7, 2026-09-02). make_plan
# swaps the head of the second one's framing for SUNG_FRAMING_TIGHT_HEAD, and the third
# goes back: a cut between two sizes reads as a cut.
SUNG_FRAMING_HEAD = "The camera holds a locked medium close-up, chest-up,"
SUNG_FRAMING_TIGHT_HEAD = ("The camera holds a locked close-up, shoulders-up — tighter than the shot before it, "
                           "so the cut into this take reads as a deliberate change of size —")
SUNG_FRAMING = ("The camera holds a locked medium close-up, chest-up, {subj} squared to the lens for "
                "the whole take, with at most a slow minimal push-in — no lateral drift, no orbit, "
                "no reframing, no head turn; {poss} face stays fully lit and legible.")
SUNG_PERFORMANCE = ("stay{s} planted and sing{s} straight down the lens, {poss} {mouth} shaping "
                    "every sung word precisely on the track, with small expressive gestures only")
SUNG_NEGATIVE = ("no head turn, no whip-pan, no camera orbit, no walking, no rising or sitting "
                 "mid-take")
# The two clauses of GLOBAL_NEGATIVE that a locked sung shot must be allowed to break.
SUNG_LIFT = ("no static locked-off hold", "no flat-on symmetrical framing")
# SUNG_LOCK=0 (pack) UNLOCKS the sung framing: the style's own camera sentence stays on a
# sung window and only the two bans that protect the mouth remain. For a film that follows
# a real music video shot for shot (Baby Nimbooda, 2026-09-03: "we can't have a static
# shot on one scene and then just singing the song") the locked close-up IS the defect;
# the moves come from a measured per-window sentence and a motion donor, and the take's
# own voice plays with its mouth (vocal-swap), so the sync argument for the lock is
# weaker than the film's. Unset = today's prompts, byte for byte.
SUNG_LOCK = os.environ.get("SUNG_LOCK", "1") != "0"
SUNG_NEGATIVE_LOOSE = "no whip-pan, no camera orbit"


def sung_performance_sentence(style: dict, pr: dict) -> str:
    """The exact performance sentence a sung prompt carries (make_plan replaces it by
    exact match with a per-window moves sentence)."""
    performance = (style.get("performanceSung") or SUNG_PERFORMANCE.format(**pr)).rstrip(".")
    return f"{pr['Subj']} {performance}."

# The pronoun sets the templates above are filled from. `he` is today's text exactly;
# nothing is inferred from a descriptor — the pack states PERFORMER_PRONOUNS. `they`
# is the set for a `both` block (two people in the shot).
PRONOUNS = {
    "he":   {"subj": "he", "Subj": "He", "obj": "him", "poss": "his", "be": "is", "s": "s", "mouth": "mouth", "face": "face"},
    "she":  {"subj": "she", "Subj": "She", "obj": "her", "poss": "her", "be": "is", "s": "s", "mouth": "mouth", "face": "face"},
    "they": {"subj": "they", "Subj": "They", "obj": "them", "poss": "their", "be": "are", "s": "", "mouth": "mouths", "face": "faces"},
}
PERFORMERS = ("a", "b", "both")

# THE NO-VOICE REGISTER IS COMPOSED, NEVER REWRITTEN. A window with nothing for this
# face to sing (an instrumental, or a line the OTHER performer sings) used to take the
# motion prompt and regex the singing verbs out of the style's prose — then
# plan_coherence #14 re-read the result with its own spelling of the verbs, and every
# new register phrasing was a refused plan (2026-08-28, 08-31, three stops). Now the
# silent window's prompt is built from a template that never emits a performance verb:
# the declaration in the audio slot, and a movement line in the performance slot. A
# register may author `performanceSilent` (world-specific action, no singing verb);
# otherwise the mode's own movement line. #14 stays as the authoring-error net.
NO_VOICE_SILENT = ("There is no singing in this shot: {subj} {do} not sing, speak or mouth words — lips "
                   "closed for the whole take; the music is added afterwards. ")
NO_VOICE_OTHER = ("The voice on the track here belongs to the other performer, not {obj}: {subj} {do} not "
                  "sing, speak or mouth words — lips closed — and simply perform{s} the scene's action, "
                  "moving to the beat; the music is added afterwards. ")
NO_VOICE_MOVEMENT = {
    "dance": "move{s} with the beat, lips closed, eyes on the lens",
    "still": "hold{s} a still posture, lips closed, eyes on the lens, the smallest shift of weight",
    "ambient": "{be} in the scene, lips closed, not performing to the lens",
}


# A SENTENCE ABOUT SLOWNESS PRODUCES A VOCAL BEHIND THE BEAT. violet-haze: "raps to
# camera, slow and heavy-lidded" — 0 of 16 draws on the bar (2026-08-18). mirror-corridor:
# "holds a still posture ... turns her head slowly" — two draws in a row started on time
# and drifted +0.6 s then +1.3 s late by the end, against a take of the SAME slice under a
# crisp block that held -100 ms throughout (2026-08-22). The model renders what the
# performance sentence is about; the direction leaks from the mood into the tempo.
#
# Two grades, from the evidence. REFUSED: the slowness is attached to the SINGING
# ("the slow duet lines", "raps ... slow and heavy-lidded", a drawl) or the body is
# directed STILL ("holds a still posture" — the 0/2 block). WARNED: a slow gait or a
# single slow gesture — desert-highway "raps to camera walking the white line, unhurried"
# was the style where EVERY window landed (2026-08-18), and lyari-alley-hook's "one slow
# coat-sweep" held -100 ms throughout. Camera and set are never checked: a slow track
# through still air is where the languor belongs.
_SLOW_MANNER = re.compile(
    r"(?i)\b(slow(ly)? (duet |sung |rapped |spoken )?(lines?|verse|hook|vocal|delivery|phrases?|words?)"
    r"|(sings?|singing|raps?|rapping|delivers?|mouths?) (it |them |the \w+ |every \w+ |each \w+ )?(slow(ly)?|lazily|languidly|drowsily|in a drawl)\b"
    r"|(sings?|singing|raps?|rapping)( \w+){0,6},? slow and heavy-lidded"
    r"|slow(ly)?,? and heavy-lidded|heavy-lidded"
    r"|still posture|holds? (perfectly |very )?still|stands? (perfectly |very )?still|frozen in place"
    r"|drawl(s|ing)?|half-time delivery|behind the beat)\b")
_SLOW_ANY = re.compile(r"(?i)\b(slow(ly|er)?|unhurried|languid(ly)?|lazy|lazily|leisurely|sluggish|in no hurry)\b")


def slow_vocal_direction(style: dict) -> tuple[list[str], list[str]]:
    """(refused, warned): tempo phrases in this block's PERFORMANCE sentence."""
    perf = style.get("performance", "")
    refused = sorted({m.group(0).lower() for m in _SLOW_MANNER.finditer(perf)})
    covered = [m.span() for m in _SLOW_MANNER.finditer(perf)]
    warned = sorted({m.group(0).lower() for m in _SLOW_ANY.finditer(perf)
                     if not any(a <= m.start() < b for a, b in covered)})
    return refused, warned


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


MODES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                          "..", "references", "video-modes.json")


def load_modes() -> dict:
    """id -> mode. Missing registry is fatal only when a mode was actually asked for."""
    try:
        with open(MODES_PATH, encoding="utf-8") as fh:
            return {m["id"]: m for m in json.load(fh)["modes"]}
    except FileNotFoundError:
        return {}


def apply_mode(style: dict, mode: dict) -> dict:
    """Fill a style's UNSET grammar fields from the mode; never overwrite.

    Precedence is style > mode > built-in default, in that order and never any
    other. A mode is a starting point — the moment it can overrule a block the
    author wrote deliberately, the registry stops being safe to adopt.

    `cameraGrammar` APPENDS rather than replaces: the style's camera line is the
    film's own choreography and the mode's is a rule about how to shoot it. Losing
    the former to gain the latter would trade one problem for another.
    """
    p = mode.get("prompt", {})
    out = dict(style)
    for field in ("performanceMode", "shot", "details", "shotFormula"):
        if not out.get(field) and p.get(field):
            out[field] = p[field]
    # `lift` accumulates rather than being overridden: a style lifting one clause
    # and a mode lifting another should end up with both lifted, not one.
    if p.get("lift"):
        out["lift"] = list(out.get("lift", [])) + list(p["lift"])
    if p.get("cameraGrammar"):
        out["camera"] = f"{out['camera']}. {p['cameraGrammar'].rstrip('.')}"
    if p.get("negatives"):
        out["negative"] = f"{out['negative']}, {p['negatives']}"
    # `ensemble: none` is the mode asserting this grammar has no ensemble, which is
    # what `solo` means downstream. Keyed on PRESENCE, not truthiness: a block that
    # says `solo: false` has expressly asked for other people in frame, and letting
    # the mode delete them would be the silent failure this precedence rule exists
    # to stop — the render succeeds, it just is not the film that was approved.
    if "solo" not in style and p.get("ensemble") == "none":
        out["solo"] = True
    return out


def _clause_key(clause: str) -> str:
    return clause.strip().lower().removeprefix("no ").removeprefix("avoid ")


# The B-roll register CANNOT share GLOBAL_NEGATIVE: that constant bans "empty
# establishing wide with no performer in it" — which is the literal definition of a
# cutaway. One negative register per shot kind, because a ban that is load-bearing for
# a performance shot is a contradiction for scenery.
#
# "no people" is deliberately ABSENT from this Avoid list. prompt_negation.py's
# docstring records the trap: a noun surviving only inside an Avoid clause still trips
# the provider's moderation filter ("no children" was refused as a minor reference).
# The people-free lock lives in the BODY, positively phrased — see compose_broll.
BROLL_NEGATIVE = ("no on-screen text, no subtitles, no logos, no music, no voices, "
                  "no singing, no lyrics, no slow motion, no freeze frames, "
                  "no static locked-off hold, no jitter, no warped geometry")


def _negatives(style: dict, extra: str = "", lift: tuple = ()) -> str:
    """Style negative + the global tail, DEDUPED and order-preserving.

    Most style blocks already ban on-screen text and subtitles, so a naive
    concatenation repeats them inside one Avoid clause -- noise that dilutes the
    terms the model actually needs to weight.
    """
    # A negative that cannot be lifted is not a constraint, it is a ceiling.
    # GLOBAL_NEGATIVE was written from ONE failure (a film of distant, motionless
    # wides) and bans stillness, slow motion and soft focus in every film forever —
    # which forbids a meditative piece outright, and forbids the release an outro
    # needs. A mode may now lift specific clauses; nothing is lifted by accident.
    lifted = {_clause_key(c) for c in lift}
    seen, out = set(), []
    joined = ", ".join(p for p in (style["negative"], extra, GLOBAL_NEGATIVE) if p)
    for clause in (c.strip() for c in joined.split(",")):
        key = _clause_key(clause)
        if clause and key not in seen and key not in lifted:
            seen.add(key)
            out.append(clause)
    return ", ".join(out)


def _v2_negatives(neg: str) -> str:
    return ", ".join(c for c in (x.strip() for x in neg.split(",")) if c and c != "no slow motion")


def compose_broll(style: dict, seconds: float, tail: str = "") -> str:
    """A people-free cutaway in this style's WORLD — the shot `cover` cuts away to.

    Built from the style's place-bearing fields only: `set` (the world — the register's
    single location field), `palette` (colour and light), and the movement half of
    `camera`. The person-bearing fields (`wardrobe`, `performance`, `solo`) are
    deliberately not consulted: a cutaway that contains the performer is not a cutaway,
    and on this lane it would also be MOUTHING, which is the defect B-roll exists to fix.

    THE PEOPLE-FREE LOCK IS POSITIVE PROSE IN THE BODY, and its wording is load-bearing:
    this exact sentence passed moderation twice and returned two clean, empty-world
    clips on the film that produced this function. Do not migrate it into the Avoid
    list — a noun that survives only inside an Avoid clause still trips the moderation
    filter (prompt_negation.py records "no children" being refused as a minor
    reference), and this model renders what a sentence is ABOUT.
    """
    # SCRUB PERSON-CLAUSES FROM THE WORLD TEXT. `set` is free prose and packs write the
    # performer into it — the first real register run surfaced "he is the only person
    # anywhere in the scene" inside a location description, which would sit two
    # sentences from the people-free lock and contradict it. The model renders what a
    # sentence is ABOUT, so the person-clause goes, not gets argued with.
    person = ("he ", "she ", "his ", "her ", "him ", "person", "people", "figure",
              "performer", "man ", "woman ", "crowd", "subject")
    world = ", ".join(
        c for c in (c.strip() for c in style["set"].rstrip(".").split(","))
        if c and not any(p in f" {c.lower()} " for p in person))
    palette = style["palette"].strip().rstrip(".")
    mood = style.get("mood", "quiet, atmospheric")
    if int(style.get("_grammar", 1) or 1) >= 2:
        # v2: the person-scrub covers palette and mood too — "gold glinting at the
        # collar", "she does not need to move", "owning the lane" leaked into four
        # empty-scenery prompts through those two fields.
        person2 = person + ("someone", "collar", "aviator", "owning", "entry of", "lens",
                            "eyes", "face", "chest", "hand", "grin", "coat", "kurta")
        def _scrub(text: str) -> str:
            return ", ".join(c for c in (c.strip() for c in text.rstrip(".").split(","))
                             if c and not any(p in f" {c.lower()} " for p in person2))
        palette = _scrub(palette) or palette
        mood = _scrub(mood) or "quiet, atmospheric"
    # The movement half of the camera line, not the framing half: B-roll wants the
    # style's motion grammar (drift, dolly, glide) without its performer-facing framing.
    move = (style.get("brollCamera") or
            "a slow steady drift forward at waist height, one continuous unhurried move")
    ambience = style.get("brollAmbience") or "the natural ambient sound of the place"
    seen, avoid = set(), []
    joined = ", ".join(p for p in (style.get("negative", ""), BROLL_NEGATIVE) if p)
    for clause in (c.strip() for c in joined.split(",")):
        key = _clause_key(clause)
        if clause and key not in seen:
            seen.add(key)
            avoid.append(clause)
    # brollSubject (style, optional): a cutaway WITH people — the ensemble without the lead.
    # A dance film's instrumental gaps want the troupe, not an empty set (Baby Nimbooda v1,
    # 2026-09-04: three empty-plate cutaways, the film ended on 4 s of an empty corridor).
    # The lead stays out of frame so the cutaway never shows a mouth the record could contradict.
    subject_line = (style.get("brollSubject") or "").strip().rstrip(".")
    if subject_line:
        return (
            f"A cutaway of {subject_line}, {world}. "
            f"The lead dancer is NOT in this shot — nobody sings, nobody faces the lens to mouth words. "
            f"The camera uses {move}. "
            f"The palette is {palette}, {mood}. "
            f"{ambience.capitalize().rstrip('.')} only, no music, no voices. "
            f"Avoid: {', '.join(avoid)}.{(' ' + tail) if tail else ''}"
        )
    return (
        f"An empty scenery shot: {world}. "
        f"NO PEOPLE ANYWHERE IN FRAME, no figures, no silhouettes of people, no hands. "
        f"The camera uses {move}. "
        f"The palette is {palette}, {mood}. "
        f"{ambience.capitalize().rstrip('.')} only, no music, no voices. "
        f"Avoid: {', '.join(avoid)}.{(' ' + tail) if tail else ''}"
    )


def compose(style: dict, duration: float, subject: str, tail: str,
            masked_ensemble: bool = False, extras: dict | None = None,
            subject2: str = "", pronouns: dict | None = None,
            lyric_language: str = "English", sung: bool = False,
            no_voice: str = "", names: dict | None = None) -> str:
    """One prompt for this style. `sung=True` is the SAME world, wardrobe, identity and
    audio sentences (make_plan.cite() rewrites those by exact match, so they must not
    move) with the sync framing in place of the style's camera/performance motion:
    make_plan puts it on the windows that carry a voice. `no_voice="silent"|"other"` is
    the register for a window this face does not sing (NO_VOICE_*): the same world,
    wardrobe and identity sentences, the declaration in the audio slot, a movement line
    with no performance verb in the performance slot, the motion camera."""
    if no_voice not in ("", "silent", "other"):
        die(f"compose: no_voice must be '', 'silent' or 'other', got {no_voice!r}")
    # Whose shot this is. `pronouns` maps performer -> PRONOUNS set; absent = today.
    performer = style.get("performer", "a")
    if performer not in PERFORMERS:
        die(f"style '{style.get('id')}': performer must be one of {'/'.join(PERFORMERS)}, "
            f"got {performer!r}")
    if performer in ("b", "both") and not subject2.strip():
        die(f"style '{style.get('id')}' is for performer {performer} but the pack has no "
            "PORTRAIT_2/IDENTITY_NOTES_2")
    if performer == "both" and style.get("solo"):
        die(f"style '{style.get('id')}' is for both performers and says solo: true — "
            "a two-person shot cannot be solo")
    pr = (pronouns or {}).get(performer) or (PRONOUNS["they"] if performer == "both"
                                             else PRONOUNS["he"])
    solo = f" {pr['Subj']} {pr['be']} alone in frame." if style.get("solo") else ""
    # Per-window overrides. `shot` replaces the standing framing sentence when a
    # window genuinely wants something else; `beat` is the one-word identity that
    # forces a window to be ABOUT something; `details` is the detail-lock that makes
    # "close" concrete — naming eyes, rings, a chain is what actually pulls the lens
    # in, where "tight framing" alone does not.
    shot = style.get("shot") or SHOT_DISCIPLINE.format(**pr)
    if sung and SUNG_LOCK:
        shot = ""                          # the locked framing IS the shot discipline
    beat = f"The beat of this shot is {style['beat']}. " if style.get("beat") else ""
    details = (f" The camera holds close on {style['details']}."
               if style.get("details") else "")
    perf = style.get("performanceMode", "dance")
    # GRAMMAR v2 (register: "grammarVersion": 2). Three injections that were right for
    # a solo dance MV and wrong for everything else (review of the first couple film,
    # 2026-08-22): the whole-body ENSEMBLE rule went into a two-person walking window
    # and a stamping desert circle ("everyone dances… spins"); camera COUPLING
    # ("her footwork chases the lens") went into a STILL-register block next to "she
    # holds a still posture"; and "no slow motion" is a negated noun sitting beside
    # "slow drift". v2: the ensemble rule only where a block says `ensembleDance`,
    # coupling only for the dance register, and the ban becomes a positive
    # "real-time speed throughout". v1 (no flag) is byte-identical to before.
    v2 = int(style.get("_grammar", 1) or 1) >= 2
    if perf == "still":
        register = f" {STILLNESS_RULE.format(**pr)}"
    elif perf == "ambient":
        register = f" {AMBIENT_RULE.format(**pr)}"
    elif v2:
        register = f" {PERFORMANCE_RULE}" if style.get("ensembleDance") else ""
    else:
        register = "" if style.get("solo") else f" {PERFORMANCE_RULE}"
    # Coupling is wrong for the ambient register by definition: that mode's whole
    # direction is that he is NOT performing to the lens.
    if v2:
        coupling = f" {CAMERA_COUPLING.format(**pr)}" if perf == "dance" else ""
    else:
        coupling = f" {CAMERA_COUPLING.format(**pr)}" if perf != "ambient" else ""
    if sung:
        # Coupling ("footwork chases the lens") and the ensemble/stillness registers are
        # motion direction; a sung window has one job, the line on the track.
        coupling, register = "", ""
    if no_voice:
        # the stillness/ambient rules direct the singing ("singing locked exactly to the
        # track"); the no-voice movement line carries the register's manner instead
        register = ""
    mask = f" {MASKED_ENSEMBLE}" if masked_ensemble and not style.get("solo") else ""
    # Register-level continuity. Our windows never see each other, so carry-over is
    # impossible; a repeated motif is the one form of cohesion that survives being
    # rendered independently.
    ex = extras or {}
    motif = (f" One motif recurs throughout the film: {ex['motif']}."
             if ex.get("motif") else "")
    keep = (f" Whatever else changes, preserve: {ex['mustKeep']}."
            if ex.get("mustKeep") else "")
    formula = (f" Shot formula: {style['shotFormula']}." if style.get("shotFormula") else "")
    extra = ", ".join(p for p in (
        STILLNESS_NEGATIVE if perf == "still" else "",
        AMBIENT_NEGATIVE if perf == "ambient" else "",
        MASKED_NEGATIVE if (masked_ensemble and not style.get("solo")) else "",
        (SUNG_NEGATIVE if SUNG_LOCK else SUNG_NEGATIVE_LOOSE) if sung else "",
    ) if p)
    lift = tuple(style.get("lift", ())) + (SUNG_LIFT if sung else ())
    performance = style["performance"]
    camera_line = f"The camera uses {style['camera']}.{details}{coupling} {shot} "
    cuts = "with stylized internal cuts"
    if sung:
        performance = (style.get("performanceSung") or SUNG_PERFORMANCE.format(**pr)).rstrip(".")
        # SUNG_LOCK=0: the style's camera sentence stays (no coupling, no shot discipline —
        # those are motion direction for a dance window); the take is still one take.
        camera_line = (f"{SUNG_FRAMING.format(**pr)}{details} " if SUNG_LOCK
                       else f"The camera uses {style['camera']}.{details} ")
        cuts = "one continuous take"
    if no_voice:
        performance = (style.get("performanceSilent")
                       or NO_VOICE_MOVEMENT.get(perf, NO_VOICE_MOVEMENT["dance"]).format(**pr)).rstrip(".")
    # The prose descriptor is load-bearing, and it used to be dropped on the floor:
    # `subject` was accepted, threaded through, and never interpolated. Seedance
    # locks a face from the TEXT as much as from the reference still, and make_plan
    # ADDS its @IMG_1 citation to this sentence rather than replacing it — so with
    # no descriptor here, every free-lane prompt shipped a bare citation, which is
    # the logged cause of a hard shot (rotating, submerged, backlit) rendering a
    # different man. Keep the "Image 1 is the protagonist portrait" substring
    # intact: make_plan._cite() rewrites it by exact match.
    # Performer b's shot is Image 1 = PORTRAIT_2 with b's descriptor (make_plan binds
    # the right still); a `both` shot cites Image 1 AND Image 2, each sentence keeping
    # the exact substring make_plan.cite() rewrites.
    who = (subject2 if performer == "b" else subject).strip().rstrip(".")
    # THE NAME BESIDE THE FACE. With --performer-names the portrait sentence carries the
    # performer's name ("… — <descriptor> (Veeru) —"), so a letter-tagged sheet's direction
    # ("only Veeru's mouth shapes the words") points at a face the model can find. No
    # names = today's text, byte for byte.
    names = names or {}
    n1 = names.get("b" if performer == "b" else "a", "")
    descriptor = (f" — {who}" + (f" ({n1})" if n1 else "")) if who and who != "the subject" else ""
    if performer == "both":
        who2 = subject2.strip().rstrip(".") + (f" ({names['b']})" if names.get("b") else "")
        wardrobe2 = style.get("wardrobe2") or style["wardrobe"]
        identity = (
            f"Image 1 is the protagonist portrait{descriptor} — preserve the same facial identity "
            f"and face shape from the uploaded photo while changing the outfit to {style['wardrobe']}. "
            f"Image 2 is the second performer's portrait — {who2} — preserve that facial identity "
            f"and face shape as well, in {wardrobe2}. ")
        voice = (f"with both performers singing the lines to camera, their mouths clearly "
                 f"shaping the {lyric_language} lyrics")
    else:
        identity = (
            f"Image 1 is the protagonist portrait{descriptor} — preserve the same facial identity "
            f"and face shape from the uploaded photo while changing the outfit to {style['wardrobe']}. ")
        voice = (f"with the character rapping directly to camera, {pr['poss']} {pr['mouth']} "
                 f"clearly shaping the {lyric_language} lyrics")
    audio = (f"Audio 1 is the {duration:g}-second rap track — use it as the rhythm and vocal "
             f"performance reference, {voice}, and the final video including sound. ")
    if no_voice:
        words = {**pr, "do": "do" if pr["subj"] == "they" else "does"}
        audio = (NO_VOICE_OTHER if no_voice == "other" else NO_VOICE_SILENT).format(**words)
    return (
        f"A character rap MV set in {style['set']}. {beat}"
        f"{identity}"
        f"{audio}"
        # The templates carry NO subject: this is the one place the pronoun is prepended.
        # They used to start with {Subj} too, so every window read "He He moves…"
        # (film #3, 2026-09-07). A register-authored performance* is subject-less as well.
        f"{pr['Subj']} {performance}."
        f"{solo}{register}{mask}{formula} "
        f"{camera_line}"
        f"The palette is {style['palette']}, "
        f"{style['mood']}, {cuts}.{motif}{keep} "
        f"{'Real-time speed throughout. ' if v2 else ''}"
        f"Avoid: {(_v2_negatives if v2 else (lambda n: n))(_negatives(style, extra, lift))}. {tail}"
    )


def main() -> None:
    ap = argparse.ArgumentParser()
    # Not argparse-required: --list-modes is a standalone query and would otherwise
    # be unusable without naming a style register it does not read.
    ap.add_argument("--styles", default="")
    ap.add_argument("--drawn", default="")
    ap.add_argument("--out-dir", default="")
    ap.add_argument("--keyframe-dir", default="")
    ap.add_argument("--duration", type=float, default=8.0)
    ap.add_argument("--aspect", default="9:16")
    ap.add_argument("--subject", default="the subject")
    ap.add_argument("--subject-2", default="",
                    help="IDENTITY_NOTES_2 — the second performer's visual descriptor")
    ap.add_argument("--pronouns", default="he",
                    help="pipe-separated, one per performer: he|she|they (default he)")
    ap.add_argument("--performer-names", default="",
                    help="pipe-separated display names for the storyboard labels only")
    ap.add_argument("--lyric-language", default="English")
    # Storyboard ONLY — this lane sends the portrait(s) as the identity reference, never
    # a keyframe, so the card must show the portrait that will go with the prompt.
    ap.add_argument("--identity-ref", default="", help="performer a's portrait (storyboard card only)")
    ap.add_argument("--identity-ref-2", default="", help="performer b's portrait (storyboard card only)")
    ap.add_argument("--mode", default="", help="video-modes.json id; overrides the register's own")
    ap.add_argument("--list-modes", action="store_true", help="print the mode menu and exit")
    args = ap.parse_args()

    modes = load_modes()
    if args.list_modes:
        for m in modes.values():
            a = m.get("authoring", {})
            print(f"\n{m['id']}  —  {m['label']}")
            print(f"  {m['whenToUse']}")
            print(f"  ensemble : {m.get('prompt', {}).get('ensemble', '?')}"
                  f"   performance: {m.get('prompt', {}).get('performanceMode', 'dance')}")
            for k in ("wardrobe", "ensembleStyling", "worldHints", "palette"):
                if a.get(k):
                    print(f"  {k:15}: {a[k]}")
        raise SystemExit(0)

    for flag, val in (("--styles", args.styles), ("--out-dir", args.out_dir)):
        if not val:
            print(f"compose_prompts: {flag} is required", file=sys.stderr)
            raise SystemExit(2)

    if not args.subject.strip() or args.subject.strip() == "the subject":
        print("compose_prompts: WARNING — no --subject descriptor. The prompts will "
              "point at the portrait without describing the person in it, and these "
              "models lock a face from the prose as much as from the reference. Pass "
              "the pack's IDENTITY_NOTES.", file=sys.stderr)

    # Pronouns are stated, never inferred: a wrong pronoun is a silent wrong film.
    pron_ids = [p.strip() for p in args.pronouns.split("|") if p.strip()]
    for pid in pron_ids:
        if pid not in PRONOUNS:
            die(f"--pronouns: unknown '{pid}' (he|she|they)")
    if args.subject_2.strip() and len(pron_ids) < 2:
        die("--subject-2 given but --pronouns has no second entry — state both, e.g. "
            "PERFORMER_PRONOUNS=\"he|she\" in the pack")
    pronouns = {"a": PRONOUNS[pron_ids[0] if pron_ids else "he"],
                "b": PRONOUNS[pron_ids[1]] if len(pron_ids) > 1 else PRONOUNS["he"],
                "both": PRONOUNS["they"]}
    names = [n.strip() for n in args.performer_names.split("|")] if args.performer_names else []
    name_of = {"a": names[0] if names else "", "b": names[1] if len(names) > 1 else ""}
    name_of["both"] = " + ".join(n for n in (name_of["a"], name_of["b"]) if n)

    register = json.load(open(args.styles, encoding="utf-8"))
    tail = register.get("promptTail", "Multiple cuts.")
    # Register-level switch: one identical mask for the whole ensemble. Off by
    # default, because it is a strong look, not a neutral default.
    masked = bool(register.get("maskedEnsemble"))

    # --mode beats the register's own `mode`, so an operator can audition a grammar
    # against an existing film without editing its register.
    mode_id = args.mode or register.get("mode", "")
    mode = {}
    if mode_id:
        if mode_id not in modes:
            print(f"compose_prompts: unknown mode '{mode_id}'. Known: "
                  f"{', '.join(modes) or '(registry missing)'}", file=sys.stderr)
            raise SystemExit(2)
        mode = modes[mode_id]
        if mode.get("prompt", {}).get("ensemble") == "masked":
            masked = True
        print(f"compose_prompts: mode '{mode_id}' — {mode['label']}", file=sys.stderr)
    styles = register["styles"]
    if args.drawn and os.path.isfile(args.drawn):
        styles = json.load(open(args.drawn, encoding="utf-8"))["styles"]

    # Refuse, do not warn: this defect costs a whole window's draws (~30 min each)
    # and reads as the lottery until the per-2s offset profile is drawn.
    refused, warned = {}, {}
    for st in styles:
        r, w = slow_vocal_direction(st)
        if st.get("performanceSung"):
            # the sung sentence drives the mouth even harder than the motion one
            r2, w2 = slow_vocal_direction({**st, "performance": st["performanceSung"]})
            r, w = r + r2, w + w2
        if r:
            refused[st["id"]] = r
        if w:
            warned[st["id"]] = w
    for k, v in warned.items():
        print(f"compose_prompts: WARNING — {k}: a slow gesture in the performance sentence "
              f"({', '.join(v)}); a gesture has not dragged a vocal so far, a manner has", file=sys.stderr)
    if refused and os.environ.get("COMPOSE_ALLOW_SLOW_VOCAL") != "1":
        lines = "\n".join(f"  {k}: {', '.join(v)}" for k, v in refused.items())
        die("these style blocks direct a SLOW VOCAL in their `performance` sentence — the "
            "model sings behind the beat when the sentence is about slowness (violet-haze "
            "0/16, mirror-corridor 0/2):\n" + lines + "\n  Move the languor into `set` / "
            "`camera` (a slow track, still air) and make the performance 'crisp and locked "
            "tight to the beat, every word landing where the track puts it'. "
            "COMPOSE_ALLOW_SLOW_VOCAL=1 overrides.")
    elif refused:
        print(f"compose_prompts: COMPOSE_ALLOW_SLOW_VOCAL=1 — slow-vocal refusal overridden for "
              f"{', '.join(refused)}", file=sys.stderr)

    # Register-level, film-wide. `motif` is the only continuity available to us —
    # windows are rendered independently, so a repeated image is cohesion that
    # survives that. `mustKeep` is a positive lock; "must keep" and "must avoid"
    # are different instruments and one does not substitute for the other.
    extras = {"motif": register.get("motif", ""), "mustKeep": register.get("mustKeep", "")}

    # The `performer` key is written onto rows ONLY when the register uses the field
    # anywhere, so a single-subject register's prompts.json stays byte-identical.
    uses_performers = any("performer" in s for s in styles)

    os.makedirs(args.out_dir, exist_ok=True)
    rows = []
    grammar = int(register.get("grammarVersion", 1) or 1)
    for s in styles:
        s = apply_mode(s, mode) if mode else s
        if grammar >= 2:
            s = {**s, "_grammar": grammar}
        prompt = compose(s, args.duration, args.subject, tail, masked, extras,
                         args.subject_2, pronouns, args.lyric_language, names=name_of)
        prompt_sung = compose(s, args.duration, args.subject, tail, masked, extras,
                              args.subject_2, pronouns, args.lyric_language, sung=True, names=name_of)
        prompt_silent = compose(s, args.duration, args.subject, tail, masked, extras,
                                args.subject_2, pronouns, args.lyric_language, no_voice="silent", names=name_of)
        prompt_other = compose(s, args.duration, args.subject, tail, masked, extras,
                               args.subject_2, pronouns, args.lyric_language, no_voice="other", names=name_of)
        kf = ""
        if args.keyframe_dir:
            for n in (f"keyframe-{s['id']}-0-9x16.png", f"keyframe-{s['id']}-0.png"):
                p = os.path.join(args.keyframe_dir, n)
                if os.path.isfile(p):
                    kf = os.path.relpath(p, args.out_dir)
                    break
        row = {"id": s["id"], "label": s["label"], "prompt": prompt, "promptSung": prompt_sung,
               "promptNoVoice": prompt_silent, "promptOtherVoice": prompt_other,
               "keyframe": kf}
        if uses_performers:
            row["performer"] = s.get("performer", "a")
        rows.append(row)

    with open(os.path.join(args.out_dir, "prompts.json"), "w", encoding="utf-8") as fh:
        json.dump({"aspect": args.aspect, "durationSec": args.duration, "prompts": rows},
                  fh, indent=2)
        fh.write("\n")

    # The preview IS the contract: it shows the EXACT text that will be submitted,
    # beside the keyframe it will be submitted with. Review this before spending.
    def who_label(r: dict) -> str:
        if not name_of["a"] or "performer" not in r:
            return ""
        return (f' <span style="color:#8ab4f8;font-size:13px;margin-left:8px">'
                f'{html.escape(name_of.get(r["performer"], ""))}</span>')

    def card_media(r: dict) -> str:
        """The image(s) this prompt is sent with: a keyframe if one exists, else the
        performer's portrait(s) — the reference this lane actually submits."""
        if r["keyframe"]:
            return '<img src="' + html.escape(r["keyframe"]) + '" alt="keyframe">'
        perf = r.get("performer", "a")
        refs = [args.identity_ref] if perf == "a" else [args.identity_ref_2] if perf == "b" \
            else [args.identity_ref, args.identity_ref_2]
        imgs = "".join(f'<img src="file://{html.escape(os.path.abspath(x))}" alt="portrait">'
                       for x in refs if x)
        return imgs or '<div class="noimg">no portrait passed</div>'

    cards = "\n".join(
        f'''<section>
  <h2>{html.escape(r["label"])} <small>{html.escape(r["id"])}</small>{who_label(r)}</h2>
  <div class="row">
    {card_media(r)}
    <div><p><b>instrumental windows</b> — the style's motion</p><pre>{html.escape(r["prompt"])}</pre>
    <p><b>sung windows</b> — {"locked for sync" if SUNG_LOCK else "framing UNLOCKED (SUNG_LOCK=0): the style camera stays"} (same world, wardrobe and identity)</p><pre>{html.escape(r["promptSung"])}</pre>
    <p><b>no-voice windows</b> — composed, lips closed (the other-voice form swaps the first sentence)</p><pre>{html.escape(r["promptNoVoice"])}</pre></div>
  </div>
</section>''' for r in rows)

    doc = shell("rap-avatar-mv — storyboard: what will actually be submitted",
                f"{len(rows)} shot(s) · {html.escape(args.aspect)} · {args.duration:g}s · "
                f"the portrait supplies the FACE ONLY, the outfit changes per style · the voice slice per WINDOW is on "
                f"submit-contract.html · review before spending",
                cards,
                extra_css="section{border:1px solid var(--line);border-radius:10px;padding:18px;margin-bottom:20px;background:var(--panel)}"
                          "h2{font-size:16px;margin:0 0 12px;color:var(--ink)}h2 small{color:var(--ink3);font-weight:400;margin-left:8px}"
                          ".row{display:flex;gap:18px;align-items:flex-start}img{width:200px;border-radius:8px;flex:0 0 auto}"
                          ".noimg{width:200px;height:355px;border:1px dashed var(--line);border-radius:8px;flex:0 0 auto;"
                          "display:flex;align-items:center;justify-content:center;color:var(--ink3);font-size:13px}"
                          "pre{margin:0;font-size:13px;line-height:1.6;flex:1}")
    out = os.path.join(args.out_dir, "storyboard.html")
    with open(out, "w", encoding="utf-8") as fh:
        fh.write(doc)
    inject_nav(out)
    print(f"compose_prompts: {len(rows)} prompt(s) -> {out}", file=sys.stderr)


if __name__ == "__main__":
    main()
