#!/usr/bin/env python3
"""apply_shot_table.py — compose the table DOWN into the storyboard.

The per-second table is a planning and QC instrument, not something a provider
obeys second by second. No route honours one-second-granularity choreography.
So the table is not sent: it is composed down into the shape the routes actually
respond to — one prose block per shot carrying the beats in order, the spatial
anchors, the performance register and the negative — and written into the
storyboard artifact that videoclaw already renders from.

That integration point is deliberate. `execution-runtime.ts` resolves a scene's
prompt as **packet -> `scenePrompt.animationPrompt` -> description**, so writing
there means `filmmaking-prompts`, `show-preflight`, `execute`, `pool` and
`batch-submit` all keep working unchanged. Composing straight to a provider
would have built a second prompt path none of them could see.

**But note the head of that chain: a READY filmmaking-prompts packet WINS.** A
packet becomes execution-ready once its promptText is non-empty and every
reference resolves — which happens the moment a storyboard grid is attached. At
that point everything composed here is silently discarded at submit. So this
script refuses when a ready packet exists for a scene it composed, rather than
letting the operator approve one prompt and ship another.

Honest limitation while you are here: `prompt-lint` lints the PACKETS, not this
prose. It is a real gate on the packet path and says nothing about this one.

It also REFUSES an unstamped table, and a stamp whose shots have since changed.
The six checks are not advisory.

Usage:
  apply_shot_table.py --project <projects/slug>
                      [--performance elastic-broad] [--dry-run]
                      [--allow-packet-override]
"""
from __future__ import annotations

import argparse
import datetime as _dt
import hashlib
import json
import os
import sys

SKILL_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGISTER = os.path.join(SKILL_DIR, "references", "performance-register.json")

# A LAST-RESORT guess at the acting register, used only when the shot does not
# name one. Treat it with suspicion: a hook type is a STORY function and a
# performance register is a BODY MECHANIC, and the two do not follow from each
# other. Measured on a real film — a `reveal` of an OBJECT (a girl spotting a
# biscuit on a shelf) and a `reversal` delivered by a dog's paw both drew
# `reveal-turn`, so both prompts told the model to build a turn of the head that
# neither shot contains. Set `performanceId` per shot whenever the body matters.
HOOK_PERFORMANCE = {
    "reveal": "reveal-turn",
    "reversal": "reveal-turn",
    "chase": "frantic-chase",
    "visual-joke": "impact-recoil",
    "tender": "grounded-warm",
    "callback": "grounded-warm",
    "suspense": "held-still",
    "expression-beat": "held-still",
    "setup": "grounded-warm",
    "climax": "elastic-broad",
}


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


def load(path: str, what: str) -> dict:
    if not os.path.isfile(path):
        die(f"{what} not found at {path}")
    try:
        return json.load(open(path, encoding="utf-8"))
    except json.JSONDecodeError as exc:
        die(f"{what} at {path} is not valid JSON: {exc}")
    return {}


def _text(v) -> str:
    return v.strip() if isinstance(v, str) else ""


def shots_digest(shots: list) -> str:
    """Must match check_shot_table.shots_digest byte for byte."""
    return hashlib.sha256(
        json.dumps(shots, sort_keys=True, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def ready_packet_scenes(artifacts_dir: str, scene_indices: list) -> set:
    """Scene indices with an EXECUTION-READY packet, which outranks our prose.

    Mirrors `isExecutionReadyPromptPacket` in execution-runtime.ts: non-empty
    promptText, and every reference both `ready` and carrying a path. A packet
    that is merely present does not win — one whose grid reference is still
    pending loses to animationPrompt, which is why this must check readiness
    rather than existence.
    """
    path = os.path.join(artifacts_dir, "filmmaking-prompts.json")
    if not os.path.isfile(path):
        return set()
    try:
        artifact = json.load(open(path, encoding="utf-8"))
    except json.JSONDecodeError:
        return set()
    wanted = set(scene_indices)
    ready = set()
    for packet in artifact.get("seedancePackets") or []:
        if packet.get("sceneIndex") not in wanted:
            continue
        if not _text(packet.get("promptText")):
            continue
        refs = packet.get("references") or []
        if any(r.get("status") != "ready" or not _text(r.get("path")) for r in refs):
            continue
        ready.add(packet["sceneIndex"])
    return ready


def compose(shot: dict, register: dict, forced: str = "") -> str:
    """One shot row -> the prose block a route actually responds to."""
    perf_id = forced or _text(shot.get("performanceId")) or HOOK_PERFORMANCE.get(
        _text(shot.get("hookType")), "elastic-broad"
    )
    perf = next((p for p in register["performance"] if p["id"] == perf_id), None)
    if perf is None:
        die(f"unknown performance register '{perf_id}' on shot {shot.get('id')}")

    parts: list[str] = []
    anchors = shot.get("anchors") or {}

    # 1. Where we are, and who is in it — the identity and staging line.
    staging: list[str] = []
    positions = anchors.get("characterPositions") or []
    for pos in positions:
        name, where = _text(pos.get("name")), _text(pos.get("position"))
        if not name:
            continue
        clause = f"{name} at {where}" if where else name
        if _text(pos.get("facing")):
            clause += f", facing {_text(pos['facing'])}"
        if _text(pos.get("pose")):
            clause += f", {_text(pos['pose'])}"
        staging.append(clause)
    if staging:
        parts.append("Staging: " + "; ".join(staging) + ".")

    landmarks = [
        f"{_text(l.get('name'))} at {_text(l.get('position'))}"
        for l in anchors.get("landmarks") or []
        if _text(l.get("name")) and _text(l.get("position"))
    ]
    if landmarks:
        # These must hold their screen position across the scene; naming them in
        # the prompt is what makes the post-render drift audit meaningful.
        parts.append("Hold these fixed in frame: " + "; ".join(landmarks) + ".")

    lighting = anchors.get("lighting") or {}
    lit = [f"{k} {_text(v)}" for k, v in lighting.items() if _text(v)]
    if lit:
        parts.append("Lighting: " + ", ".join(lit) + ".")

    # 2. The beats, in order, as one continuous action paragraph. The timecodes
    #    are dropped here: they are the checkable contract, not an instruction a
    #    model can follow, and leaving them in reads as on-screen text to some
    #    routes.
    actions, cameras, audio = [], [], []
    for beat in shot.get("beats") or []:
        act = _text(beat.get("action")).rstrip(".")
        # Collapse a repeated action the same way the camera line already does.
        # A held pose is legitimately written on several consecutive beats, but
        # "she pulls, then she pulls, then she pulls" is noise in a prompt and
        # reads to a model as an instruction to loop the move.
        if act and (not actions or actions[-1] != act):
            actions.append(act)
        cam = _text(beat.get("camera"))
        if cam and (not cameras or cameras[-1] != cam):
            cameras.append(cam)
        cue = _text(beat.get("audio"))
        if cue and cue.lower() != "silent" and cue not in audio:
            audio.append(cue)
    if actions:
        parts.append("Action, in order: " + ", then ".join(actions) + ".")
    if cameras:
        parts.append("Camera: " + ", then ".join(cameras) + ".")

    # 3. The performance register — the acting layer the style register does not
    #    carry.
    parts.append(f"Performance: {perf['acting']}.")
    parts.append(f"Timing: {perf['timing']}.")
    parts.append(f"Expression: {perf['expression']}.")

    # 4. Audio, diegetic only.
    if audio:
        parts.append("Audio: " + "; ".join(audio) + ".")

    # 5. The negative, then the tail. The tail goes LAST on every video prompt —
    #    it is what makes the model cut within the shot instead of holding one
    #    static take.
    negative = ", ".join(filter(None, [register["negativeBaseline"], _text(perf.get("negative"))]))
    parts.append(f"AVOID: {negative}.")
    parts.append(register["promptTail"])
    return "\n".join(parts)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--performance", default="",
                    help="force one performance register on every shot (default: chosen per hook type)")
    ap.add_argument("--dry-run", action="store_true", help="print the composed prompts, write nothing")
    ap.add_argument("--allow-packet-override", action="store_true",
                    help="proceed even though a ready filmmaking-prompts packet will win at submit")
    args = ap.parse_args()

    project = os.path.abspath(args.project)
    artifacts = os.path.join(project, "artifacts")
    table_path = os.path.join(artifacts, "shot-table.json")
    storyboard_path = os.path.join(artifacts, "storyboard.json")

    table = load(table_path, "shot table")
    register = load(REGISTER, "performance register")

    stamp = table.get("selfCheck") or {}
    if not stamp.get("passed"):
        die(
            "the shot table has not passed its self-check.\n"
            "    Run: check_shot_table.py --table "
            f"{table_path} --stamp\n"
            "    The six checks are the gate between a broken continuity chain and a set of\n"
            "    clips rendered against it. Nothing composes until they pass."
        )
    # A stamp says the rows passed ONCE. Edit a row afterwards and the flag still
    # reads true, so the checks would be silently skipped for the edit.
    recorded = stamp.get("shotsHash")
    if recorded and recorded != shots_digest(table.get("shots") or []):
        die(
            "the shot table has changed since it passed its self-check.\n"
            "    Run: check_shot_table.py --table "
            f"{table_path} --stamp\n"
            "    The stamp vouches for the rows it saw, not for the file it sits in."
        )

    storyboard = load(storyboard_path, "storyboard")
    scenes = storyboard.get("scenes") or []
    shots = table.get("shots") or []
    if len(shots) != len(scenes):
        die(
            f"the table has {len(shots)} shot(s) but the storyboard has {len(scenes)} scene(s).\n"
            "    They must correspond one-to-one. Re-run make_shot_table.py after any\n"
            "    storyboard change, then re-author and re-check."
        )

    composed = [compose(shot, register, args.performance) for shot in shots]

    # THE OVERRIDE CHECK. execution-runtime resolves a scene's prompt as
    # packet -> animationPrompt -> description, so a ready packet discards
    # everything composed here at submit time — after the operator approved it.
    scene_indices = [scene.get("sceneIndex", n) for n, scene in enumerate(scenes)]
    overridden = ready_packet_scenes(artifacts, scene_indices)
    if overridden:
        rows = ", ".join(
            f"{shots[n].get('id')} (scene {index})"
            for n, index in enumerate(scene_indices)
            if index in overridden
        )
        message = (
            f"a READY filmmaking-prompts packet exists for: {rows}\n"
            "    execution-runtime resolves prompt as packet -> animationPrompt -> description,\n"
            "    so the packet WINS and everything composed here is discarded at submit —\n"
            "    after you approved it. The preview would not be the contract.\n"
            "    Either build the packets with `--phase storyboard` (which gates the video\n"
            "    packets to [] and leaves this prose as the prompt), or pass\n"
            "    --allow-packet-override to ship the PACKET text knowingly."
        )
        if not args.allow_packet_override:
            die(message)
        print(f"apply_shot_table: WARNING — {message}", file=sys.stderr)

    if args.dry_run:
        for shot, text in zip(shots, composed):
            print(f"\n===== {shot.get('id')} — {shot.get('title', '')} =====")
            if overridden:
                print("!! a ready packet overrides this at submit; this is NOT what would be sent")
            print(text)
        return

    # Hashes drive the stale-output gate. `updatedAt` only moves when the prompt
    # itself changes, so an unrelated re-run never invalidates a good render.
    hashes_path = os.path.join(project, "build", "prompt-hashes.json")
    prior = {}
    if os.path.isfile(hashes_path):
        try:
            prior = json.load(open(hashes_path, encoding="utf-8"))
        except json.JSONDecodeError:
            prior = {}
    now = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    hashes: dict[str, dict] = {}
    changed: list[str] = []

    silent_film = _text(table.get("dialogueMode")) in ("", "none")
    for n, (scene, shot, text) in enumerate(zip(scenes, shots, composed)):
        prompt = scene.setdefault("scenePrompt", {})
        prompt["animationPrompt"] = text
        # A film with no dialogue must SAY so on each scene. assemble's lip-sync
        # word-ceiling falls back to the scene DESCRIPTION when a scene carries
        # no dialogue, and `silent` is its designed opt-out (there is a control
        # test asserting the fallback, so it is intentional, not a bug). Without
        # this the finished short warned "33 words — OVER LIMIT. Veo will cut
        # off speech mid-sentence" about prose nobody ever speaks — and a
        # warning that fires on well-formed input teaches you to ignore the log.
        if silent_film:
            scene["silent"] = True
        # Carry the CAST down onto the scene.
        #
        # This one missing assignment is why "The Sun Mango" rendered with no
        # locked identity on any shot. The chain: the shot table names the cast
        # per shot and check_shot_table.py validates it (cast-per-shot), then
        # this composer dropped it, so storyboard scenes carried no
        # `characters`. Downstream, buildExecutionPayload builds its Flow slot
        # plan from `scene.characters` — empty cast, empty slot plan, no
        # `--character` flags — and flow-characters.json sat on disk with both
        # characters correctly registered and never once attached.
        #
        # Everything that should have caught it was reading the same empty
        # list: show-preflight passed on it, consistency-audit's per-character
        # checks passed on it, and the veo-useapi identity gate needs a
        # non-empty cast before it can refuse. A field nothing writes makes
        # every check that reads it unanimously, silently, agree.
        cast = [c for c in (shot.get("characters") or []) if isinstance(c, str) and c.strip()]
        if cast:
            scene["characters"] = cast
        digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
        key = str(scene.get("sceneIndex", n))
        was = prior.get(key) or {}
        if was.get("hash") == digest:
            hashes[key] = was
        else:
            hashes[key] = {"hash": digest, "updatedAt": now, "shotId": shot.get("id")}
            changed.append(str(shot.get("id")))

    tmp = f"{storyboard_path}.tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(storyboard, fh, indent=2)
        fh.write("\n")
    os.replace(tmp, storyboard_path)

    os.makedirs(os.path.dirname(hashes_path), exist_ok=True)
    with open(hashes_path, "w", encoding="utf-8") as fh:
        json.dump(hashes, fh, indent=2)
        fh.write("\n")

    print(f"apply_shot_table: composed {len(composed)} shot(s) into {storyboard_path}", file=sys.stderr)
    if changed:
        print(f"  {len(changed)} prompt(s) changed: {', '.join(changed)}", file=sys.stderr)
        print("  Run check_stale_outputs.py before re-rendering — a changed prompt beside an", file=sys.stderr)
        print("  old clip makes the resumable driver skip the scene and verify the wrong one.", file=sys.stderr)
    print(json.dumps({"storyboard": storyboard_path, "shots": len(composed), "changed": changed}))


if __name__ == "__main__":
    main()
