#!/usr/bin/env python3
"""broll_refs.py — a keyframe for every cutaway, in the film's own look.

Why (Baby Nimbooda, 2026-09-05 01:55): the cutaways rendered from TEXT alone came back as a
different film — a dark stage with navy skirts, then babies in tutus on a bare floor. Every
performance window had carried a keyframe (@IMG_1) all day and stayed on style; the cutaways
had none. On a style-locked film nothing renders from text alone (memory:
every-render-carries-a-reference-image).

Per B-roll job: a composition source (a frame of the original's troupe shot, or one of the
film's own landed keyframes when the original has no such shot in the segment) + a STYLE
anchor (one of the film's own keyframes for that world) → Go Bananas `POST /images` with both
as `reference_image_ids` (`reference_mode: add`, no character — the lead stays out of frame)
→ 1280x720 → `references/shots/bNN-keyframe.png` → the job's `identityRef`, cited in the
prompt as the first frame of the shot. Writes the plan back in place.

usage: broll_refs.py --project P --broll-plan build/broll-plan.json --breakdown build/dance-breakdown.json
                     --video original.mp4 --style-refs "sun-disc-dais=w00,courtyard-troupe=w07,..."
                     --shots "sun-disc-dais=8,courtyard-troupe=16,overhead-kaleidoscope=self,..." [--regen]
"""
import argparse
import re
import json
import os
import subprocess
import sys
import tempfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from shot_refs import (GB_API, KEYFRAME_MODEL, NEGATIVE, UA, _curl_json, env_key, gb_upload,  # noqa: E402
                       normalise_1280x720, sha256_file, sharpest_frame)


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


def gb_troupe_keyframe(prompt: str, ref_ids: list[int], key: str, out_png: str, negative: str = NEGATIVE) -> dict:
    body = {"prompt": prompt, "reference_image_ids": ref_ids, "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 = 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}"])
    finally:
        os.unlink(req)
    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"), "prompt": prompt}


def clause(subject: str = "the troupe") -> str:
    """The @IMG_1 sentence a cutaway prompt opens with. `subject` is a short noun phrase
    for what the frame shows (the style's brollSubject head, else the troupe)."""
    return (f"Image 1 (@IMG_1) is the first frame of this shot: {subject}, in exactly this framing, "
            "costumes, palette and set — start from it and keep its look throughout. ")


CLAUSE = clause()


_EMPTY_RE = re.compile(r"\b(no one|nobody|no people|no-one|empty)\b", re.I)


def broll_empty(style: dict) -> bool:
    """True when the style's brollSubject declares an EMPTY scene ("no one aboard",
    "nobody", "no people"). Then the keyframe prompt says so twice and the negative bans
    people: drawn from a composition source that shows the leads, the model otherwise
    keeps a couple of children in other clothes (Baby Yeh Dosti b00/b03, 2026-09-06)."""
    return bool(_EMPTY_RE.search(str(style.get("brollSubject") or "")))


PEOPLE_NEGATIVE = ("people, person, child, children, kid, kids, boy, boys, girl, girls, figure, figures, "
                   "face, faces, hands, rider, passenger, crowd")


def subject_head(style: dict) -> str:
    """The first clause of a style's brollSubject ("the toy sidecar bike on a dirt road, …"
    -> "the toy sidecar bike on a dirt road"), or "" when the style has none."""
    s = str(style.get("brollSubject") or "").strip()
    return s.split(",")[0].strip() if s else ""


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--broll-plan", required=True)
    ap.add_argument("--breakdown", required=True)
    ap.add_argument("--video", required=True)
    ap.add_argument("--styles", required=True, help="styles json (for each world's set text)")
    ap.add_argument("--style-refs", required=True, help="styleId=wNN[,…] — the film's own keyframe that anchors the look")
    ap.add_argument("--shots", required=True, help="styleId=<breakdown shot index>|self[,…] — the composition source")
    ap.add_argument("--regen", action="store_true")
    a = ap.parse_args()

    P = os.path.abspath(a.project)
    shots_dir = os.path.join(P, "references", "shots")
    os.makedirs(shots_dir, exist_ok=True)
    plan = json.load(open(a.broll_plan, encoding="utf-8"))
    bd = {s["index"]: s for s in json.load(open(a.breakdown, encoding="utf-8")).get("shots", [])}
    styles = {s["id"]: s for s in json.load(open(a.styles, encoding="utf-8")).get("styles", [])}
    style_refs = dict(p.split("=", 1) for p in a.style_refs.split(",") if p)
    shot_src = dict(p.split("=", 1) for p in a.shots.split(",") if p)
    key = env_key("GO_BANANAS_API_KEY")
    if not key:
        say("no GO_BANANAS_API_KEY"); raise SystemExit(3)

    for job in plan.get("jobs", []):
        sid, jid = job.get("styleId"), job["id"]
        style_kf = os.path.join(shots_dir, f"{style_refs.get(sid, '')}-keyframe.png")
        if not os.path.isfile(style_kf):
            say(f"{jid}: no style keyframe for world {sid} ({style_kf}) — skipped"); continue
        kf = os.path.join(shots_dir, f"{jid}-keyframe.png")
        if os.path.isfile(kf) and not a.regen:
            say(f"{jid}: keyframe kept")
        else:
            src_spec = shot_src.get(sid, "self")
            if src_spec == "self":
                src = style_kf
            else:
                shot = bd[int(src_spec)]
                src = os.path.join(shots_dir, f"{jid}-src.jpg")
                sharpest_frame(a.video, float(shot["start"]), src, float(shot["end"]))
            world = (styles.get(sid) or {}).get("set") or "the film's set"
            # WHAT THE CUTAWAY SHOWS comes from the style's brollSubject (compose_prompts uses
            # the same field for the cutaway prompt); the troupe wording is the default the
            # first film was drawn with.
            subject = str((styles.get(sid) or {}).get("brollSubject") or "").strip()
            empty = broll_empty(styles.get(sid) or {})
            people = ((f"The subject is {subject}; the lead performers are NOT in this shot"
                       + (" — NO PEOPLE AT ALL: nobody in frame, no child, no figure, no face, an empty scene of things and landscape only."
                          if empty else ".")) if subject else
                      "The people are the troupe of eight toddler dancers in candy-pink, marigold-yellow and lilac "
                      "lehengas, caught MID-DANCE with skirts flaring; the lead dancer in turquoise is NOT in this shot.")
            prompt = (f"Recreate the shot in the first reference as ONE full-frame still, in EXACTLY the look of the "
                      f"second reference: the same warm luminous 3D-animated Pixar-film palette, lighting, toddler "
                      f"proportions and costumes. {people} The setting is {world}. No text, no watermark.")
            say(f"{jid}: uploading {os.path.basename(src)} + {os.path.basename(style_kf)} → keyframe ({KEYFRAME_MODEL})…")
            ids = [gb_upload(src, key), gb_upload(style_kf, key)]
            info = gb_troupe_keyframe(prompt, ids, key, kf,
                                      negative=(NEGATIVE + ", " + PEOPLE_NEGATIVE) if empty else NEGATIVE)
            job["keyframePrompt"] = info["prompt"]
        job["identityRef"] = kf
        job["keyframeSha"] = sha256_file(kf)[:12]
        if not job["prompt"].startswith("Image 1 (@IMG_1)"):
            head = subject_head(styles.get(sid) or {})
            job["prompt"] = (clause(head) if head else CLAUSE) + job["prompt"]
    json.dump(plan, open(a.broll_plan, "w", encoding="utf-8"), indent=2, ensure_ascii=False)
    say(f"wrote {a.broll_plan} ({sum(1 for j in plan.get('jobs', []) if j.get('identityRef'))} cutaway(s) with a keyframe)")


if __name__ == "__main__":
    main()
