#!/usr/bin/env python3
"""shot_refs.py — per window, the reference video's OWN shot: a source frame, a styled
keyframe of the performer in that framing and pose, the muted footage as a motion donor,
and the moves sentence the breakdown measured — so a sung window renders as the shot
the original film had there instead of one locked close-up.

Why (Baby Nimbooda, 2026-09-03): the first take came back a static wide shot of a
speck singing at the wrong rhythm, and the operator's word was "follow the music video —
take screenshots of the video when she's singing and mimic those; replicate the dance
moves". The lane already lets a window carry its own identity image (`identityRef`) and
the free engine treats image 1 as the frame-zero composition anchor, so a keyframe per
window needs no engine change; the donor rides a new task field (`motionRef`).

Per SUNG window (a voice reference is attached):
  1. the DOMINANT shot — the breakdown shot covering most of the window's sung span
  2. `references/shots/wNN-src.jpg`   the sharpest frame in that shot's first 1.5 s
  3. `references/shots/wNN-keyframe.png`  Go Bananas: the registered character in that
     framing and pose, the film's world, 1280x720 — becomes the window's @IMG_1
  4. `references/shots/wNN-donor.mp4`  (--donor) the original footage over the window's
     exact span, muted, 1280x720 — the motion reference (@video1)
  5. `moves`  the shot's measured sentence (or --moves override) — the performance line
  6. `--gate`  upload the keyframe (and donor) through the free engine's own media gate
     and record the verdict; nothing is submitted.
Per NO-VOICE window: the shots' timecoded blocks as `performanceSilentOverride`.

Usage:
  shot_refs.py --project P --plan build/plan.json --brief build/vocal-brief.json
               --breakdown build/dance-breakdown.json --video <reference.mp4>
               --styles <register.json> --char-id 392 --out build/shot-refs.json
               [--html build/shot-refs.html] [--donor] [--gate] [--only w05]
               [--moves build/shot-moves.json] [--regen] [--dry-run]

Exit 0 written · 2 bad input · 3 no Go Bananas key · 5 a sung window has no moves sentence.
"""
from __future__ import annotations

import argparse
import hashlib
import html
import json
import os
import re
import subprocess
import sys
import tempfile
import time

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
FFMPEG = os.environ.get("FFMPEG_FULL") or os.environ.get("FFMPEG_BIN") or "ffmpeg"
GB_API = os.environ.get("GO_BANANAS_API_URL", "https://gobananasai.com/api").rstrip("/")
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")
KEYFRAME_MODEL = "openai-gpt-image-2"
DONOR_MIN_COVERAGE = 0.8      # one original shot must cover this much of the sung span
MOVES_MAX_WORDS = 25
SHARPNESS_WINDOW_S = 1.5
NEGATIVE = ("adult, grown woman, real person, photoreal skin, film still, text, watermark, "
            "lemon, fruit, held object, extra feet, extra legs, duplicated body parts, "
            "hand at face, finger at lips, hand covering mouth, bare midriff, bare chest, "
            "panel grid, split screen, extra limbs, extra fingers")
FRAMING_SUNG = "a medium shot, waist-up, her face large, fully lit and readable"
FRAMING_BY_KIND = {"wide": "a full-body shot, her whole figure from head to feet in frame",
                   "medium": "a medium-full shot, knees-up",
                   "close": "a close-up, shoulders-up"}


def say(msg: str) -> None:
    print(f"shot_refs: {msg}", file=sys.stderr)


def die(msg: str, code: int = 2) -> None:
    say(msg); raise SystemExit(code)


def sha256_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def env_key(name: str) -> str:
    """The environment, else the repo's .env.local/.env (a worktree has none; the main
    checkout three levels up does)."""
    if os.environ.get(name):
        return os.environ[name].strip().strip('"')
    roots = [REPO] + ([os.path.abspath(os.path.join(REPO, "..", "..", ".."))]
                      if "/.claude/worktrees/" in REPO else [])
    for p in [os.path.join(r, fn) for r in roots for fn in (".env.local", ".env")]:
        if os.path.isfile(p):
            for line in open(p, encoding="utf-8", errors="ignore"):
                m = re.match(rf'^\s*{name}\s*=\s*"?([^"\n]+)"?', line)
                if m:
                    return m.group(1).strip()
    return ""


# ---------------------------------------------------------------------------
# geometry
# ---------------------------------------------------------------------------
def sung_span(job: dict, brief_w: dict | None, pronoun_gender: str) -> tuple[float, float] | None:
    # a letter-tagged sheet (two boys): the job's performer letter is the voice it owns
    if brief_w and any(sp.get("who") in ("a", "b") for sp in brief_w.get("spans", [])):
        pronoun_gender = str(job.get("performer") or "a")
    """Absolute [a, b] of this face's own singing inside the window (whole spans only)."""
    spans = (brief_w or job.get("vocal") or {}).get("spans") or []
    own = [sp for sp in spans if not sp.get("partialHead") and not sp.get("partialTail")
           and sp.get("who") in (pronoun_gender, "both", "duet", "lead")]
    if not own:
        own = [sp for sp in spans if sp.get("who") in (pronoun_gender, "both", "duet", "lead")]
    if not own:
        return None
    base = float(job.get("startSec") or 0) + float(job.get("trimStartSec") or 0)
    a = min(base + float(sp["start"]) for sp in own)
    b = max(base + float(sp["end"]) for sp in own)
    return (a, b)


def dominant_shot(shots: list[dict], a: float, b: float) -> tuple[dict | None, float]:
    """(shot, coverage of [a,b]) for the shot overlapping [a,b] the most."""
    best, best_ov = None, 0.0
    for s in shots:
        ov = max(0.0, min(b, float(s["end"])) - max(a, float(s["start"])))
        if ov > best_ov:
            best, best_ov = s, ov
    return best, (best_ov / (b - a) if b > a else 0.0)


def rebase_blocks(shot: dict, win_a: float, win_b: float) -> list[str]:
    """The shot's '[a-bs: …]' blocks whose span meets [win_a, win_b], with a and b
    re-expressed as seconds from the WINDOW's start (clamped to it)."""
    out = []
    s0 = float(shot.get("start") or 0.0)
    for blk in shot.get("blocks") or []:
        m = re.match(r"\s*\[\s*(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\s*s?\s*\]?\s*:?\s*(.*?)\]?\s*$", blk, re.S)
        if not m:
            out.append(blk.strip()); continue
        a, b, text = s0 + float(m.group(1)), s0 + float(m.group(2)), m.group(3).strip().rstrip("]")
        if b <= win_a or a >= win_b:
            continue
        ra, rb = max(0.0, a - win_a), min(win_b, b) - win_a
        if rb - ra < 0.5:
            continue
        out.append(f"[{ra:.0f}-{rb:.0f}s: {text}]")
    return out


def shots_in(shots: list[dict], a: float, b: float) -> list[dict]:
    return [s for s in shots if float(s["end"]) > a and float(s["start"]) < b]


# ---------------------------------------------------------------------------
# frames, keyframes, donors
# ---------------------------------------------------------------------------
def sharpest_frame(video: str, start: float, out: str, end: float | None = None) -> float:
    """The sharpest of 12 frames spread across the WHOLE shot, saved at 1280x720. A frame
    at a fixed offset was a motion-blurred mid-lunge on the first probe and the keyframe
    model gave a static stand for it; the first 1.5 s of a shot is often its wind-up, so
    the pose the film remembers sits later — sample the shot, keep the sharp one."""
    from PIL import Image, ImageFilter, ImageStat
    d = tempfile.mkdtemp(prefix="shot-refs-")
    span = max(0.8, (end - start) if end else SHARPNESS_WINDOW_S)
    n = 12
    subprocess.run([FFMPEG, "-v", "error", "-y", "-ss", f"{start:.3f}", "-t", f"{span:.3f}",
                    "-i", video, "-vf", f"fps={n / span:.4f},scale=1280:720", "-frames:v", str(n),
                    os.path.join(d, "f-%02d.jpg")], check=True, capture_output=True)
    best, best_t, best_s = None, start, -1.0
    for i, fn in enumerate(sorted(os.listdir(d))):
        p = os.path.join(d, fn)
        im = Image.open(p).convert("L").filter(ImageFilter.FIND_EDGES)
        s = ImageStat.Stat(im).var[0]
        if s > best_s:
            best, best_s, best_t = p, s, start + i * span / n
    if best is None:
        die(f"no frames extracted at {start}s")
    Image.open(best).convert("RGB").save(out, quality=92)
    return round(best_t, 2)


def normalise_1280x720(src: str, dst: str) -> None:
    from PIL import Image
    im = Image.open(src).convert("RGB")
    w, h = im.size
    scale = max(1280 / w, 720 / h)
    im = im.resize((round(w * scale), round(h * scale)), Image.LANCZOS)
    x = (im.width - 1280) // 2; y = (im.height - 720) // 2
    im.crop((x, y, x + 1280, y + 720)).save(dst)


def _curl_json(args: list[str]) -> dict:
    """Go Bananas over curl: Cloudflare 403s Python's HTTP client on POST /images (the
    identical body via curl is 201 — repo memory, 2026-09-02); GETs pass either way."""
    r = subprocess.run(["curl", "-sS", "-A", UA] + args, capture_output=True, text=True, timeout=400)
    if r.returncode != 0:
        raise RuntimeError(f"curl failed: {r.stderr.strip()[:200]}")
    try:
        return json.loads(r.stdout)
    except ValueError:
        raise RuntimeError(f"non-JSON answer: {r.stdout[:200]}")


def gb_upload(path: str, key: str) -> int:
    """POST /images/upload (multipart) → the Go Bananas image id (what `reference_image_ids`
    takes; a URL is not accepted there)."""
    d = _curl_json(["-H", f"X-API-Key: {key}", "-X", "POST", f"{GB_API}/images/upload", "-F", f"file=@{path}"])
    iid = d.get("image_id") or (d.get("data") or {}).get("image_id")
    if not iid:
        raise RuntimeError(f"upload returned no image_id: {json.dumps(d)[:200]}")
    return int(iid)


_POSITIONS = [
    (r"\b(kneel\w*|on (?:her|their) knees)\b", "KNEELING on the floor"),
    (r"\b(seated|sits?|sitting)\b", "SEATED on the floor"),
    (r"\b(squat\w*|crouch\w*)\b", "SQUATTING low"),
    (r"\b(lying|lies)\b", "LYING on the floor"),
]


def body_position(shot: dict) -> str:
    """The body position the breakdown measured for the shot ("KNEELING on the floor"), or "".

    Why (w06 dance proof, 2026-09-04): the render follows the KEYFRAME's pose over the prose —
    the breakdown said "kneeling on the floor", the keyframe showed her standing, and the take
    stood. The position has to be in the picture, so it goes into the keyframe prompt.
    """
    text = " ".join([shot.get("movesSentence") or ""] + list(shot.get("blocks") or []))
    for pat, phrase in _POSITIONS:
        if re.search(pat, text, re.I):
            return phrase
    return ""


def keyframe_prompt(style: dict, framing: str, moves: str, sung: bool, identity_notes: str,
                    pronoun: str = "she", performer: str = "a", identity_notes_2: str = "",
                    pronoun_2: str = "he") -> str:
    """The Go Bananas keyframe prompt. `performer` a/b/both picks whose shot it is (the
    style's `performer`); the words follow the pronoun(s). A she/solo call is the text the
    first film was drawn with, byte for byte — the keyframe cache keys on it."""
    world = (style or {}).get("set") or "the film's set"
    wardrobe = (style or {}).get("wardrobe") or ""
    both = performer == "both"
    pr = pronoun_2 if performer == "b" else pronoun
    notes = identity_notes_2 if performer == "b" else identity_notes
    if both:
        wardrobe2 = (style or {}).get("wardrobe2") or wardrobe
        adult, who_ref = "The two adults in the reference are REPLACED by the two toddler characters from the character references, one each — ", \
            "keep each face exactly as its character"
        wear = (f", the first in {wardrobe}, the second in {wardrobe2}" if wardrobe else "")
        pose = ("Their bodies are caught MID-DANCE, copying the two people in the reference exactly: the same arm "
                "positions, the same torso lean and turn, the same weight on the same foot"
                f"{(' — ' + moves.rstrip('.')) if moves else ''}. Not a standing pose: a dance pose, frozen at its peak. "
                "All their hands are away from their faces, palms below the chin. ")
        mouth = "Their mouths are open mid-song with joyful smiles. " if sung else "Joyful open smiles, lips together. "
        notes_txt = " ".join(x for x in (f"Character 1 notes: {identity_notes}" if identity_notes else "",
                                        f"Character 2 notes: {identity_notes_2}" if identity_notes_2 else "") if x)
        notes_txt = (notes_txt + " ") if notes_txt else ""
    else:
        she = pr == "she"
        Poss, poss, obj, adult_n, person = (("Her", "her", "her", "woman", "woman") if she else
                                            ("His", "his", "him", "man", "man"))
        adult = f"The adult {adult_n} in the reference is REPLACED by the toddler character from the character reference — "
        who_ref = f"keep {poss} face exactly as that character"
        wear = (", wearing " + wardrobe) if wardrobe else ""
        pose = (f"{Poss} body is caught MID-DANCE, copying the {person} in the reference exactly: the same arm positions, "
                "the same torso lean and turn, the same weight on the same foot"
                f"{', the skirt swinging with the move' if she else ''}"
                f"{(' — ' + moves.rstrip('.')) if moves else ''}. Not a standing pose: a dance pose, frozen at its peak. "
                f"Both of {poss} hands are away from {poss} face, palms below the chin. ")
# NO PROP FROM THE REFERENCE (operator, 2026-09-05: "she doesn't need a lemon in her hand"):
# reference_mode=add copies what the woman in the source frame holds. The rule lives in
# NEGATIVE (not in the cached prompt text) so approved keyframes are not all redrawn; a
# window that still shows one gets "her hands empty" in its --moves override.
        mouth = f"{Poss} mouth is open mid-song with a joyful smile. " if sung else "A joyful open smile, lips together. "
        notes_txt = ("Character notes: " + notes + " ") if notes else ""
    return (
        "Recreate this exact shot as ONE full-frame still in a warm luminous 3D-animated Pixar-film look: "
        f"the same camera angle and the same moment as the reference, framed as {framing}. "
        f"{adult}{who_ref}{wear}. "
        f"{pose}{mouth}"
        f"The setting is {world}. "
        f"{notes_txt}"
        "Soft rounded toddler proportions, big expressive eyes. No adults anywhere in frame, no real person, "
        "no film still, no text, no panel grid."
    )


def gb_keyframe(prompt: str, char_id, ref_image_id: int, key: str, out_png: str) -> dict:
    """`char_id`: one Go Bananas character id, or a list of them (a two-performer shot)."""
    ids = list(char_id) if isinstance(char_id, (list, tuple)) else [char_id]
    body = {"prompt": prompt, "character_ids": ids, "reference_image_ids": [ref_image_id],
            "reference_mode": "add", "model_id": KEYFRAME_MODEL, "aspect_ratio": "16:9",
            "enhance_prompt": False, "negative_prompt": NEGATIVE}
    with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
        json.dump(body, f); req_path = f.name
    try:
        d = _curl_json(["-H", f"X-API-Key: {key}", "-H", "Content-Type: application/json",
                        "-X", "POST", f"{GB_API}/images", "--data", f"@{req_path}"])
    finally:
        os.unlink(req_path)
    im = ((d.get("data") or {}).get("images") or [None])[0]
    if not im or not im.get("full_url"):
        raise RuntimeError(f"no image in the answer: {json.dumps(d)[:300]}")
    raw = out_png + ".raw.png"
    subprocess.run(["curl", "-sS", "-A", UA, "-o", raw, im["full_url"]], check=True, timeout=300)
    normalise_1280x720(raw, out_png)
    os.remove(raw)
    return {"imageId": im.get("d1_record_id") or im.get("id"), "url": im["full_url"],
            "model": im.get("model_id") or KEYFRAME_MODEL, "prompt": prompt}


def cut_donor(video: str, start: float, seconds: float, out: str) -> None:
    subprocess.run([FFMPEG, "-v", "error", "-y", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", video,
                    "-an", "-vf", "scale=1280:720,fps=25", "-c:v", "libx264", "-crf", "20",
                    "-pix_fmt", "yuv420p", "-movflags", "+faststart", out], check=True, capture_output=True)


def prep_own_donor(src: str, seconds: float, out: str, keep_audio: bool = False) -> None:
    """An OWNED clip (one of this film's own landed renders) as the window's motion donor:
    muted, 1280x720, trimmed to the window. The original film's footage is refused by the
    engine's IP check at submit (proof 2, 2026-09-04); a clip we rendered ourselves is ours to
    upload, and it carries the dance the operator already approved — so a sung window can
    copy that dance from @video1 while it lip-syncs the voice ("sing and dance at the same
    time", operator 2026-09-04 15:20)."""
    # keep_audio: the operator's 2026-09-04 15:30 test — "not the original mp4, just the mp4 of
    # the audio": the window's own voice slice (its mp4, audio kept) rides as @video1 so the
    # engine hears the vocal on the VIDEO channel too; the audio channel stays as it is.
    subprocess.run([FFMPEG, "-v", "error", "-y", "-i", src, "-t", f"{seconds:.3f}"]
                   + ([] if keep_audio else ["-an"])
                   + ["-vf", "scale=1280:720,fps=25", "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p"]
                   + (["-c:a", "aac", "-b:a", "192k"] if keep_audio else [])
                   + ["-movflags", "+faststart", out], check=True, capture_output=True)


def probe(path: str) -> dict:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=codec_type,width,height:format=duration",
                        "-of", "json", path], capture_output=True, text=True)
    try:
        d = json.loads(r.stdout)
    except ValueError:
        return {}
    v = next((s for s in d.get("streams", []) if s.get("codec_type") == "video"), {})
    return {"seconds": float(d.get("format", {}).get("duration") or 0), "width": v.get("width"),
            "height": v.get("height"), "audio": any(s.get("codec_type") == "audio" for s in d.get("streams", []))}


# ---------------------------------------------------------------------------
# the free engine's media gate
# ---------------------------------------------------------------------------
def gate_upload(path: str, kind: str) -> dict:
    """Upload through engines/seedance-direct's own session and record the verdict.
    Needs the engine venv (torch-free, but CloakBrowser) and the single-slot profile —
    run it only when the lane is idle. Nothing is submitted."""
    import importlib.util
    ap = os.path.join(REPO, "engines", "seedance-direct", "adapter.py")
    spec = importlib.util.spec_from_file_location("seedance_direct_adapter", ap)
    mod = importlib.util.module_from_spec(spec)
    try:
        spec.loader.exec_module(mod)
        sess = mod.make_session()
        fn = sess.upload_video if kind == "video" else sess.upload_image
        res = fn(path)
    except Exception as exc:                                   # noqa: BLE001
        return {"ok": False, "reason": f"gate did not run: {str(exc)[:200]}", "ran": False}
    media, reason = (res if isinstance(res, tuple) else (res, None))
    ok = bool(media and (media.get("id") if isinstance(media, dict) else media))
    status = media.get("status") if isinstance(media, dict) else None
    return {"ok": ok, "status": status, "reason": reason, "ran": True, "at": time.strftime("%Y-%m-%dT%H:%M:%S")}


# ---------------------------------------------------------------------------
def moves_ok(sentence: str) -> list[str]:
    problems = []
    n = len(sentence.split())
    if n > MOVES_MAX_WORDS:
        problems.append(f"{n} words (max {MOVES_MAX_WORDS})")
    if re.search(r"\b\d+(\.\d+)?\s?s(ec(ond)?s?)?\b|\[\s*\d", sentence):
        problems.append("carries seconds — a second clock beside the audio")
    # a MOVE of the camera is a second direction; "back to the camera" is the dancer's
    if re.search(r"\bthe camera (pans|zooms|tracks|moves|pushes|pulls|tilts|orbits|dollies|cranes|follows)|"
                 r"\bcamera (pan|zoom|move|movement|track|orbit)|\bdolly|\bzoom(s|ing)? (in|out)|\bpan(s|ning) (left|right|across)|"
                 r"\btracking shot|\bcrane (up|down)", sentence, re.I):
        problems.append("carries a camera move")
    try:
        from compose_prompts import slow_vocal_direction
        refused, _ = slow_vocal_direction({"performance": sentence})
        if refused:
            problems.append(f"slow-vocal manner: {', '.join(refused)}")
    except Exception:                                          # noqa: BLE001
        pass
    return problems


def write_html(path: str, doc: dict) -> None:
    from lane_page import page as shell
    rows = []
    for wid, w in doc["windows"].items():
        src = f'<img src="file://{html.escape(w["srcFrame"])}">' if w.get("srcFrame") else ""
        kf = f'<img src="file://{html.escape(w["keyframe"])}">' if w.get("keyframe") else '<span class="b bad">no keyframe</span>'
        donor = (f'<video muted controls preload="metadata" src="file://{html.escape(w["donor"])}"></video>'
                 if w.get("donor") else "")
        g = w.get("gate") or {}
        chips = ""
        for k in ("keyframe", "donor"):
            if g.get(k):
                cls = "ok" if g[k].get("ok") else "bad"
                chips += f' <span class="b {cls}">{k} gate: {"pass" if g[k].get("ok") else html.escape(str(g[k].get("reason") or g[k].get("status") or "refused"))}</span>'
        if w.get("problems"):
            chips += "".join(f' <span class="b bad">{html.escape(p)}</span>' for p in w["problems"])
        moves = html.escape(w.get("moves") or "")
        silent = "<br>".join(html.escape(b) for b in (w.get("performanceSilentOverride") or []))
        rows.append(f"""<tr><td><b>{wid}</b><br>{w['startSec']:.2f}–{w['endSec']:.2f}s<br>{'SUNG' if w.get('sung') else 'no voice'}<br>
shot {w.get('shotIndex')} · {w.get('shotStart')}–{w.get('shotEnd')}s · {int(100*(w.get('coverage') or 0))}% · {'donor ok' if w.get('donorOk') else 'no donor'}</td>
<td>{src}<figcaption>source · {w.get('srcAt')}s</figcaption></td><td>{kf}<figcaption>keyframe · {w.get('framing')}</figcaption></td>
<td>{donor}</td><td><p><b>{moves}</b></p><p class="muted">{silent}</p>{chips}</td></tr>""")
    body = f"""<p>Per window: the original film's own shot (source frame), the styled keyframe that becomes the window's
first image, the muted footage that carries its moves, and the measured moves sentence that becomes its performance line.
Red chips are refusals; a window with one does not render.</p>
<table><tr><th>window</th><th>source frame</th><th>keyframe</th><th>motion donor</th><th>moves</th></tr>{''.join(rows)}</table>"""
    css = ("table{width:100%;border-collapse:collapse}td,th{vertical-align:top;padding:8px;border-top:1px solid var(--line,#333)}"
           "img,video{max-width:360px;height:auto}figcaption{font-size:12px;opacity:.7}.muted{opacity:.75;font-size:13px}"
           ".b{display:inline-block;padding:2px 8px;border-radius:12px;font-size:12px;margin:2px;background:#233}"
           ".b.ok{background:#1d4a2a;color:#9aff9a}.b.bad{background:#4a1d1d;color:#ff9a9a}")
    open(path, "w", encoding="utf-8").write(shell("Shot references", f"{len(doc['windows'])} windows · from {os.path.basename(doc['video'])}",
                                                  body, extra_css=css))


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--project", required=True)
    ap.add_argument("--plan", required=True)
    ap.add_argument("--brief", default="")
    ap.add_argument("--breakdown", required=True, help="dance-breakdown.json")
    ap.add_argument("--video", required=True, help="the reference video the breakdown was made from")
    ap.add_argument("--styles", required=True)
    ap.add_argument("--char-id", required=True,
                    help="Go Bananas character id — '397', or '397|399' for performers a|b (a `both` style draws both)")
    ap.add_argument("--identity-notes", default=os.environ.get("IDENTITY_NOTES", ""))
    ap.add_argument("--identity-notes-2", default=os.environ.get("IDENTITY_NOTES_2", ""), help="performer b's descriptor")
    ap.add_argument("--pronoun", default=os.environ.get("PERFORMER_PRONOUNS", "she").split("|")[0])
    ap.add_argument("--pronoun-2", default=(os.environ.get("PERFORMER_PRONOUNS", "she").split("|") + ["he"])[1],
                    help="performer b's pronoun")
    ap.add_argument("--out", required=True)
    ap.add_argument("--html", default="")
    ap.add_argument("--moves", default="", help="json {wNN: sentence} overrides")
    ap.add_argument("--only", default="")
    ap.add_argument("--donor", action="store_true")
    ap.add_argument("--own-donor", default="", help="wNN=/path/to/owned.mp4[,wNN=...] — an owned clip as that window's motion donor")
    ap.add_argument("--own-donor-audio", action="store_true", help="keep the own donor's audio (the voice slice as @video1)")
    ap.add_argument("--gate", action="store_true")
    ap.add_argument("--regen", action="store_true", help="regenerate keyframes even if present")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

    own_donors = {}
    for part in [p.strip() for p in args.own_donor.split(",") if p.strip()]:
        wid_, _, path_ = part.partition("=")
        if not path_ or not os.path.isfile(path_):
            die(f"--own-donor {part}: the clip is not on disk", 2)
        own_donors[wid_.strip()] = os.path.abspath(path_)
    plan = json.load(open(args.plan, encoding="utf-8"))
    bd = json.load(open(args.breakdown, encoding="utf-8"))
    shots = [s for s in bd.get("shots", []) if not s.get("error")]
    styles = {s["id"]: s for s in json.load(open(args.styles, encoding="utf-8")).get("styles", [])}
    brief_w = {}
    if args.brief and os.path.isfile(args.brief):
        brief_w = {w["id"]: w for w in json.load(open(args.brief, encoding="utf-8")).get("windows", [])}
    overrides = json.load(open(args.moves, encoding="utf-8")) if args.moves else {}
    prior = {}
    if os.path.isfile(args.out):
        try:
            prior = json.load(open(args.out, encoding="utf-8")).get("windows", {})
        except (OSError, ValueError):
            prior = {}
    only = {x.strip() for x in args.only.split(",") if x.strip()}
    gender = "female" if args.pronoun == "she" else "male" if args.pronoun == "he" else "lead"
    CHAR_IDS = [int(x) for x in re.split(r"[|, ]+", str(args.char_id)) if x.strip()]
    if not CHAR_IDS:
        die("--char-id: no character id given")
    shots_dir = os.path.join(args.project, "references", "shots")
    os.makedirs(shots_dir, exist_ok=True)
    key = "" if args.dry_run else env_key("GO_BANANAS_API_KEY")
    if not args.dry_run and not key:
        die("no GO_BANANAS_API_KEY (env or the repo .env.local)", 3)

    windows: dict = {}
    refusals = 0
    for job in sorted(plan["jobs"], key=lambda j: float(j.get("startSec") or 0)):
        wid = job["id"]
        if not wid.startswith("w") or (only and wid not in only):
            if wid in prior and not only:
                pass
            elif wid in prior:
                windows[wid] = prior[wid]
            continue
        base = float(job.get("startSec") or 0) + float(job.get("trimStartSec") or 0)
        secs = float(job.get("seconds") or 0)
        end = base + secs
        sung = bool(job.get("voiceRef"))
        rec = {"startSec": round(base, 3), "endSec": round(end, 3), "seconds": secs, "sung": sung,
               "styleId": job.get("styleId"), "problems": []}
        if sung:
            span = sung_span(job, brief_w.get(wid), gender) or (base, end)
            shot, cov = dominant_shot(shots, *span)
        else:
            shot, cov = dominant_shot(shots, base, end)
        if not shot:
            rec["problems"].append("no breakdown shot overlaps this window")
            windows[wid] = rec; refusals += 1; continue
        rec.update({"shotIndex": shot["index"], "shotStart": shot["start"], "shotEnd": shot["end"],
                    "coverage": round(cov, 3), "shotFraming": shot.get("framing"),
                    "subjectVisible": bool(shot.get("subjectVisible")), "handsNearFace": bool(shot.get("handsNearFace"))})
        # A donor is one original shot (≥80 % of the sung span) that shows the body — a wide
        # or medium shot. `subjectVisible` (head-to-feet for most of the clip) is recorded
        # but not required: the 49-59 s shot has her rising from a kneel among a seated
        # troupe, head-to-feet only part of the time, and it is the film's clearest dance.
        rec["donorOk"] = bool(sung and cov >= DONOR_MIN_COVERAGE and (shot.get("framing") or "medium") != "close")
        # the moves line
        moves = overrides.get(wid) or (shot.get("movesSentence") if sung else "")
        if sung:
            if not moves:
                rec["problems"].append("no moves sentence (breakdown empty for this shot; give --moves)")
            else:
                rec["moves"] = moves.strip().rstrip(".")
                rec["problems"] += moves_ok(rec["moves"])
        else:
            # A dance window carries its DOMINANT shot's blocks only, re-timed to the window
            # (the blocks' seconds count from the shot's start; a neighbouring shot's leap
            # that overlaps by 0.9 s is not this window's choreography). Blocks that end
            # before the window opens or start after it closes are dropped.
            rec["performanceSilentOverride"] = rebase_blocks(shot, base, end)
        rec["framing"] = FRAMING_SUNG if sung else FRAMING_BY_KIND.get(shot.get("framing") or "medium", FRAMING_BY_KIND["medium"])
        if args.dry_run:
            windows[wid] = rec
            say(f"{wid} {'SUNG' if sung else 'silent'} {base:6.2f}-{end:6.2f} shot {shot['index']} "
                f"{shot['start']}-{shot['end']} cov {cov:.0%} donor={rec['donorOk']} — {rec.get('moves', '')[:70]}")
            continue
        # source frame + keyframe for EVERY window with a shot: a sung line opens on it and so
        # does a dance shot (the chant windows are the film's dancing now)
        if True:
            src = os.path.join(shots_dir, f"{wid}-src.jpg")
            kf = os.path.join(shots_dir, f"{wid}-keyframe.png")
            old = prior.get(wid) or {}
            if not os.path.isfile(src) or args.regen:
                rec["srcAt"] = sharpest_frame(args.video, float(shot["start"]), src, float(shot["end"]))
            else:
                rec["srcAt"] = old.get("srcAt")
            rec["srcFrame"], rec["srcSha"] = src, sha256_file(src)[:12]
            style = styles.get(job.get("styleId") or "", {})
            pose_text = rec.get("moves") or (shot.get("movesSentence") or "")
            position = body_position(shot)
            if position:
                pose_text = f"{position}, {pose_text[0].lower() + pose_text[1:]}" if pose_text else position
            perf = str(style.get("performer") or job.get("performer") or "a")
            prompt = keyframe_prompt(style, rec["framing"], pose_text, sung, args.identity_notes,
                                     pronoun=args.pronoun, performer=perf,
                                     identity_notes_2=args.identity_notes_2, pronoun_2=args.pronoun_2)
            char_ids = {"a": [CHAR_IDS[0]], "b": [CHAR_IDS[-1]], "both": CHAR_IDS}.get(perf, [CHAR_IDS[0]])
            if perf in ("b", "both") and len(CHAR_IDS) < 2:
                die(f"{wid}: style '{job.get('styleId')}' is for performer {perf} but --char-id names one character")
            # CACHE BY CONTENT: the keyframe is kept only while its source frame AND its prompt
            # are the ones it was drawn from — a style/notes edit (the lemon leaving her hand,
            # 2026-09-04) must redraw it, or the contract shows a keyframe the prompt contradicts.
            if (os.path.isfile(kf) and not args.regen and old.get("srcSha") == rec["srcSha"]
                    and old.get("keyframe") == kf and old.get("keyframePrompt") == prompt):
                rec.update({k: old.get(k) for k in ("keyframe", "keyframeSha", "keyframeImageId", "keyframePrompt")})
                say(f"{wid}: keyframe kept ({os.path.basename(kf)})")
            else:
                say(f"{wid}: uploading source frame + generating keyframe ({KEYFRAME_MODEL})…")
                try:
                    iid = gb_upload(src, key)
                    info = gb_keyframe(prompt, char_ids, iid, key, kf)
                    rec.update({"keyframe": kf, "keyframeSha": sha256_file(kf)[:12], "keyframeImageId": info["imageId"],
                                "keyframePrompt": prompt, "srcImageId": iid})
                except Exception as exc:                               # noqa: BLE001
                    rec["problems"].append(f"keyframe failed: {str(exc)[:160]}")
            if wid in own_donors:
                donor = os.path.join(shots_dir, f"{wid}-donor.mp4")
                src_pr = probe(own_donors[wid])
                if (src_pr.get("seconds") or 0) < secs - 0.25:
                    rec["problems"].append(f"own donor is {src_pr.get('seconds', 0):.2f}s, shorter than the {secs:.2f}s window")
                prep_own_donor(own_donors[wid], secs, donor, keep_audio=args.own_donor_audio)
                pr = probe(donor)
                rec.update({"donor": donor, "donorOwn": own_donors[wid], "donorOk": True, "donorAudio": bool(args.own_donor_audio),
                            "donorSeconds": round(pr.get("seconds") or 0, 3), "donorSha": sha256_file(donor)[:12]})
                if pr.get("audio") and not args.own_donor_audio:
                    rec["problems"].append("donor carries an audio stream")
                if (pr.get("width"), pr.get("height")) != (1280, 720):
                    rec["problems"].append(f"donor is {pr.get('width')}x{pr.get('height')}, not 1280x720")
            elif args.donor and rec["donorOk"]:
                donor = os.path.join(shots_dir, f"{wid}-donor.mp4")
                if not os.path.isfile(donor) or args.regen or abs((probe(donor).get("seconds") or 0) - secs) > 0.25:
                    cut_donor(args.video, base, secs, donor)
                pr = probe(donor)
                rec.update({"donor": donor, "donorSeconds": round(pr.get("seconds") or 0, 3), "donorSha": sha256_file(donor)[:12]})
                if pr.get("audio"):
                    rec["problems"].append("donor carries an audio stream")
                if (pr.get("width"), pr.get("height")) != (1280, 720):
                    rec["problems"].append(f"donor is {pr.get('width')}x{pr.get('height')}, not 1280x720")
            if args.gate:
                rec["gate"] = {}
                if rec.get("keyframe"):
                    rec["gate"]["keyframe"] = gate_upload(rec["keyframe"], "image")
                    if not rec["gate"]["keyframe"].get("ok"):
                        rec["problems"].append(f"keyframe refused by the media gate: {rec['gate']['keyframe'].get('reason')}")
                if rec.get("donor"):
                    rec["gate"]["donor"] = gate_upload(rec["donor"], "video")
                    if not rec["gate"]["donor"].get("ok"):
                        rec["donorOk"] = False
                        rec["problems"].append(f"donor refused by the media gate: {rec['gate']['donor'].get('reason')}")
            elif old.get("gate"):
                rec["gate"] = old["gate"]      # a verdict from an earlier --gate pass stands until re-gated
        if rec["problems"]:
            refusals += 1
        windows[wid] = rec
    doc = {"schemaVersion": 1, "video": os.path.abspath(args.video), "breakdown": os.path.abspath(args.breakdown),
           "breakdownSha": sha256_file(args.breakdown)[:12], "planHash": plan.get("planHash"),
           "charId": CHAR_IDS[0], "charIds": CHAR_IDS, "keyframeModel": KEYFRAME_MODEL, "windows": windows,
           "generatedAt": time.strftime("%Y-%m-%dT%H:%M:%S")}
    if not args.dry_run:
        json.dump(doc, open(args.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
        if args.html:
            write_html(args.html, doc)
        say(f"wrote {args.out} ({len(windows)} windows, {refusals} with problems)")
    if refusals and not args.dry_run:
        for wid, w in windows.items():
            for p in w.get("problems") or []:
                say(f"  {wid}: {p}")
        raise SystemExit(5)


if __name__ == "__main__":
    main()
