#!/usr/bin/env python3
"""check_shot_table.py — the six-check gate the whole engine hangs off.

The source method states six self-checks as prose and asks the agent to run
them honestly on itself. An agent grading its own table passes it. This runs
them as code, exits non-zero on any failure, prints the failing ROWS, and only
stamps `selfCheck.passed` into the artifact when all six hold. Storyboarding
and every downstream stage read that stamp, so a table that has not passed
cannot reach a render.

The six, straight from the method:

  1. hook-density       every shot carries a hook; pivots are distributed; the
                        opening and closing shots carry a strong one.
  2. shot-duration      no shot longer than the ceiling (default 15s).
  3. cast-per-shot      no more than N acting characters in one shot.
  4. anchor-inheritance within a scene, landmarks and lighting either match the
                        previous shot or carry an explicit continuity note.
  5. beat-coverage      the per-second beats tile the shot with no gap and no
                        overlap, and every beat carries all five elements.
  6. continuity-chain   the handoff column reads as an unbroken chain, a flip is
                        marked as a deliberate hard cut, and a character who
                        left the frame is still accounted for.

Usage:
  check_shot_table.py --table <artifacts/shot-table.json>
                      [--stamp] [--json-out <path>]
                      [--max-shot-seconds 15] [--max-cast 3]

Exit codes: 0 all six pass · 2 the table could not be read · 3 a check failed.
"""
from __future__ import annotations

import argparse
import datetime as _dt
import hashlib
import json
import os
import sys
from typing import Any

# A hook that can open or close a film. `setup` and `expression-beat` cannot:
# they are connective tissue, and a short that opens on one has no hook.
STRONG_HOOKS = {"visual-joke", "reversal", "reveal", "suspense", "tender", "climax"}
# A hook that turns the story rather than continuing it. The method wants one
# of these in every three consecutive shots, which is what stops a short
# becoming a sequence of pleasant unrelated moments.
PIVOT_HOOKS = {"reveal", "reversal", "callback"}

# The five elements every beat must carry. `audio` is satisfied by the literal
# "silent" — an intended silence is a decision, an empty field is an omission.
BEAT_ELEMENTS = ("action", "camera", "spatial", "audio", "handoff")

# Tolerance for beat arithmetic. Beats are authored in seconds and sub-second
# markers are allowed, so exact float equality would fail on 2.0-2.5 boundaries.
EPS = 1e-6


def shots_digest(shots: list[dict]) -> str:
    """Fingerprint of the rows the stamp is vouching for.

    Without it the stamp only says "these shots passed ONCE". Edit a row after
    stamping and apply_shot_table still composes, because it checks the flag and
    not the content — the same staleness class already solved for rendered
    outputs with prompt hashes.
    """
    payload = json.dumps(shots, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


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


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


def _shot_label(index: int, shot: dict) -> str:
    sid = _text(shot.get("id")) or f"#{index + 1}"
    title = _text(shot.get("title"))
    return f"{sid} ({title})" if title else sid


# ---------------------------------------------------------------------------
# 1. hook density
# ---------------------------------------------------------------------------
def check_hook_density(shots: list[dict]) -> list[str]:
    failures: list[str] = []
    for i, shot in enumerate(shots):
        if not _text(shot.get("hookType")):
            failures.append(f"{_shot_label(i, shot)}: no hookType — every shot must earn its place")

    if shots:
        first, last = shots[0], shots[-1]
        if _text(first.get("hookType")) not in STRONG_HOOKS:
            failures.append(
                f"{_shot_label(0, first)}: opening shot carries '{_text(first.get('hookType'))}' — "
                f"an opening needs one of {', '.join(sorted(STRONG_HOOKS))}"
            )
        if len(shots) > 1 and _text(last.get("hookType")) not in STRONG_HOOKS:
            failures.append(
                f"{_shot_label(len(shots) - 1, last)}: closing shot carries "
                f"'{_text(last.get('hookType'))}' — a closing needs one of "
                f"{', '.join(sorted(STRONG_HOOKS))}"
            )

    # One pivot in every three consecutive shots. Only meaningful once there
    # ARE three: a two-shot film cannot be said to sag in the middle.
    if len(shots) >= 3:
        for start in range(len(shots) - 2):
            window = shots[start:start + 3]
            if not any(_text(s.get("hookType")) in PIVOT_HOOKS for s in window):
                labels = ", ".join(_shot_label(start + n, s) for n, s in enumerate(window))
                failures.append(
                    f"shots {labels}: three consecutive shots with no "
                    f"{'/'.join(sorted(PIVOT_HOOKS))} — the story stops turning here"
                )
    return failures


# ---------------------------------------------------------------------------
# 2. shot duration
# ---------------------------------------------------------------------------
def check_shot_duration(shots: list[dict], ceiling: float, target: float = 0.0,
                        tolerance: float = 0.25) -> list[str]:
    failures: list[str] = []
    total = 0.0
    for i, shot in enumerate(shots):
        dur = shot.get("durationSeconds")
        if not isinstance(dur, (int, float)) or dur <= 0:
            failures.append(f"{_shot_label(i, shot)}: durationSeconds is {dur!r} — must be a positive number")
            continue
        total += float(dur)
        if dur > ceiling + EPS:
            failures.append(
                f"{_shot_label(i, shot)}: {dur}s exceeds the {ceiling}s ceiling — split the beat into two shots"
            )
    # The method settles the film's LENGTH up front, then the six checks only
    # ever looked at individual shots — so a 20-second brief could scaffold into
    # a 24-second film and nothing said a word (the storyboard carried no
    # durations, so every scene defaulted to 8s).
    if target > 0 and abs(total - target) > target * tolerance:
        failures.append(
            f"the film runs {round(total, 2)}s against a target of {target}s "
            f"(more than {int(tolerance * 100)}% out) — adjust the shot durations or the target"
        )
    return failures


# ---------------------------------------------------------------------------
# 3. cast per shot
# ---------------------------------------------------------------------------
def check_cast_per_shot(shots: list[dict], ceiling: int) -> list[str]:
    failures: list[str] = []
    for i, shot in enumerate(shots):
        cast = shot.get("characters") or []
        if len(cast) > ceiling:
            failures.append(
                f"{_shot_label(i, shot)}: {len(cast)} acting characters "
                f"({', '.join(str(c) for c in cast)}) exceeds the limit of {ceiling} — "
                f"identity drifts fastest in a crowded frame"
            )
    return failures


# ---------------------------------------------------------------------------
# 4. anchor inheritance
# ---------------------------------------------------------------------------
def _landmark_map(shot: dict) -> dict[str, str]:
    anchors = shot.get("anchors") or {}
    out: dict[str, str] = {}
    for lm in anchors.get("landmarks") or []:
        if isinstance(lm, dict) and _text(lm.get("name")):
            out[_text(lm["name"])] = _text(lm.get("position"))
    return out


def _lighting(shot: dict) -> dict[str, str]:
    anchors = shot.get("anchors") or {}
    lighting = anchors.get("lighting") or {}
    return {k: _text(v) for k, v in lighting.items() if _text(v)}


def check_anchor_inheritance(shots: list[dict]) -> list[str]:
    failures: list[str] = []
    # Compare a shot only against the previous shot IN THE SAME SCENE. A scene
    # revisited later legitimately re-establishes, and the shots between it and
    # its predecessor are somewhere else entirely.
    last_in_scene: dict[str, tuple[int, dict]] = {}
    for i, shot in enumerate(shots):
        scene = _text(shot.get("scene"))
        if not scene:
            # A blank binding used to `continue`, which meant a film whose rows
            # were all unbound passed this check having compared NOTHING — the
            # same inert-gate failure as a readiness check that verifies nothing
            # and reports ready. The scaffolder only auto-binds when the project
            # has exactly one setting, so a normal multi-location film arrives
            # here entirely blank.
            failures.append(
                f"{_shot_label(i, shot)}: no scene binding — bind it to an environment "
                f"plate by name, or this check silently compares nothing"
            )
            continue
        prev = last_in_scene.get(scene)
        last_in_scene[scene] = (i, shot)
        if prev is None:
            continue
        prev_i, prev_shot = prev

        note = _text((shot.get("anchors") or {}).get("continuityNote"))
        if note:
            continue  # a declared change is not drift

        prev_lm, this_lm = _landmark_map(prev_shot), _landmark_map(shot)
        shared = set(prev_lm) & set(this_lm)
        moved = [n for n in sorted(shared) if prev_lm[n] != this_lm[n]]
        if moved:
            detail = "; ".join(f"{n}: {prev_lm[n]} -> {this_lm[n]}" for n in moved)
            failures.append(
                f"{_shot_label(i, shot)}: landmark moved since {_shot_label(prev_i, prev_shot)} "
                f"in scene '{scene}' ({detail}) with no anchors.continuityNote explaining it"
            )

        prev_light, this_light = _lighting(prev_shot), _lighting(shot)
        if prev_light and this_light and prev_light != this_light:
            failures.append(
                f"{_shot_label(i, shot)}: lighting baseline changed since "
                f"{_shot_label(prev_i, prev_shot)} in scene '{scene}' "
                f"({prev_light} -> {this_light}) with no anchors.continuityNote"
            )
    return failures


# ---------------------------------------------------------------------------
# 5. beat coverage
# ---------------------------------------------------------------------------
def check_beat_coverage(shots: list[dict]) -> list[str]:
    failures: list[str] = []
    for i, shot in enumerate(shots):
        label = _shot_label(i, shot)
        beats = shot.get("beats") or []
        if not beats:
            failures.append(f"{label}: no beats — the shot has no per-second direction at all")
            continue

        ordered = []
        for n, beat in enumerate(beats):
            frm, to = beat.get("from"), beat.get("to")
            if not isinstance(frm, (int, float)) or not isinstance(to, (int, float)):
                failures.append(f"{label} beat {n + 1}: from/to must be numbers, got {frm!r}/{to!r}")
                continue
            if to <= frm:
                failures.append(f"{label} beat {n + 1}: {frm}-{to}s does not move forward")
                continue
            ordered.append((float(frm), float(to), n, beat))
        if not ordered:
            continue
        ordered.sort(key=lambda b: b[0])

        if abs(ordered[0][0]) > EPS:
            failures.append(f"{label}: beats start at {ordered[0][0]}s — the first frame is undirected")

        for (a_from, a_to, a_n, _), (b_from, b_to, b_n, _) in zip(ordered, ordered[1:]):
            if b_from - a_to > EPS:
                failures.append(
                    f"{label}: gap between beat {a_n + 1} (ends {a_to}s) and beat {b_n + 1} "
                    f"(starts {b_from}s) — {round(b_from - a_to, 3)}s of the shot is undirected"
                )
            elif a_to - b_from > EPS:
                failures.append(
                    f"{label}: beat {a_n + 1} ({a_from}-{a_to}s) overlaps beat {b_n + 1} "
                    f"({b_from}-{b_to}s) — two directions for the same moment"
                )

        dur = shot.get("durationSeconds")
        if isinstance(dur, (int, float)) and dur > 0:
            end = ordered[-1][1]
            if dur - end > EPS:
                failures.append(
                    f"{label}: beats end at {end}s but the shot runs {dur}s — "
                    f"the last {round(dur - end, 3)}s is undirected"
                )
            elif end - dur > EPS:
                failures.append(
                    f"{label}: beats run to {end}s, past the shot duration of {dur}s"
                )

        for _, _, n, beat in ordered:
            missing = [e for e in BEAT_ELEMENTS if not _text(beat.get(e))]
            if missing:
                failures.append(
                    f"{label} beat {n + 1} ({beat.get('from')}-{beat.get('to')}s): "
                    f"missing {', '.join(missing)} — all five elements are required "
                    f"(an intended silence is the literal 'silent', not an empty field)"
                )
            # The mouthing rule, kept deliberately narrow so it fires only on a
            # real omission: a beat that explicitly carries speech must record
            # whether the mouth is open. A clip whose mouth moves is only usable
            # on the words it was rendered against, so this is what makes a
            # mismatch reviewable instead of a surprise at assembly.
            audio = _text(beat.get("audio")).lower()
            speaks = audio.startswith(("dialogue:", "narration:")) or " says " in audio
            if speaks and beat.get("mouth") not in ("open", "closed"):
                failures.append(
                    f"{label} beat {n + 1}: audio carries speech ({beat.get('audio')!r}) "
                    f"but mouth is not recorded as open or closed"
                )
    return failures


# ---------------------------------------------------------------------------
# 6. continuity chain
# ---------------------------------------------------------------------------
def check_continuity_chain(shots: list[dict]) -> list[str]:
    failures: list[str] = []
    for i, shot in enumerate(shots):
        label = _shot_label(i, shot)
        cont = shot.get("continuity") or {}
        hard_cut = bool(cont.get("hardCut"))

        if i > 0 and not _text(cont.get("from")) and not hard_cut:
            failures.append(
                f"{label}: no continuity.from — the chain breaks here. Either say how it "
                f"continues {_shot_label(i - 1, shots[i - 1])}, or set hardCut with a reason"
            )
        if hard_cut and not _text(cont.get("hardCutReason")):
            failures.append(
                f"{label}: hardCut is set but hardCutReason is empty — a deliberate flip "
                f"has to say what it is (a time skip, a location jump)"
            )
        if i < len(shots) - 1 and not _text(cont.get("to")):
            failures.append(
                f"{label}: no continuity.to — nothing is set up for "
                f"{_shot_label(i + 1, shots[i + 1])}"
            )

        # A character who ACTS in this shot is IN this shot. Listing them only in
        # `exited` — or describing them anonymously ("a single tan paw") — leaves
        # them out of `characters`, so nothing puts them in the keyframe, and on
        # an image-to-video route the keyframe IS the identity lock. Measured
        # twice on one film: a registered dog rendered as a different breed when
        # he was only in the prompt, and the closing reversal never rendered at
        # all because his paw was described but he was not listed.
        listed = {str(c) for c in (shot.get("characters") or [])}
        exited = {
            _text(e.get("name"))
            for e in ((shot.get("anchors") or {}).get("exited") or [])
            if isinstance(e, dict)
        }
        beat_text = " ".join(
            _text(beat.get(field)).lower()
            for beat in (shot.get("beats") or [])
            for field in ("action", "spatial")
        )
        for name in sorted(exited - listed):
            if name and name.lower() in beat_text:
                failures.append(
                    f"{label}: {name} is listed as EXITED but acts in the beats — a character "
                    f"who acts is present. Add them to `characters` so they reach the keyframe, "
                    f"or the render will simply omit them"
                )

        # A character on screen in the previous shot and absent from this one
        # must be accounted for, once. After two consecutive shots off stage
        # they are simply gone and tracking them is noise.
        if i > 0:
            prev_cast = {str(c) for c in (shots[i - 1].get("characters") or [])}
            this_cast = {str(c) for c in (shot.get("characters") or [])}
            gone = prev_cast - this_cast
            if gone:
                tracked = {
                    _text(e.get("name"))
                    for e in ((shot.get("anchors") or {}).get("exited") or [])
                    if isinstance(e, dict)
                }
                untracked = sorted(gone - tracked)
                if untracked:
                    failures.append(
                        f"{label}: {', '.join(untracked)} left the frame since "
                        f"{_shot_label(i - 1, shots[i - 1])} but is not in anchors.exited — "
                        f"an untracked exit is how a character reappears on the wrong side"
                    )
    return failures


# ---------------------------------------------------------------------------
def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--table", required=True, help="path to shot-table.json")
    ap.add_argument("--stamp", action="store_true",
                    help="write selfCheck into the table when all six pass")
    ap.add_argument("--json-out", default="", help="write the check report as JSON")
    ap.add_argument("--max-shot-seconds", type=float, default=15.0)
    ap.add_argument("--max-cast", type=int, default=3)
    ap.add_argument("--target-seconds", type=float, default=0.0,
                    help="the film's intended length; 0 disables the total-duration check")
    args = ap.parse_args()

    if not os.path.isfile(args.table):
        die(f"shot table not found: {args.table}")
    try:
        table = json.load(open(args.table, encoding="utf-8"))
    except json.JSONDecodeError as exc:
        die(f"{args.table} is not valid JSON: {exc}")

    shots = table.get("shots")
    if not isinstance(shots, list) or not shots:
        die(f"{args.table} has no shots")

    results = [
        ("hook-density", check_hook_density(shots)),
        ("shot-duration", check_shot_duration(shots, args.max_shot_seconds, args.target_seconds)),
        ("cast-per-shot", check_cast_per_shot(shots, args.max_cast)),
        ("anchor-inheritance", check_anchor_inheritance(shots)),
        ("beat-coverage", check_beat_coverage(shots)),
        ("continuity-chain", check_continuity_chain(shots)),
    ]
    checks = [{"id": cid, "passed": not fails, "failures": fails} for cid, fails in results]
    passed = all(c["passed"] for c in checks)

    if args.json_out:
        os.makedirs(os.path.dirname(os.path.abspath(args.json_out)), exist_ok=True)
        with open(args.json_out, "w", encoding="utf-8") as fh:
            json.dump({"passed": passed, "checks": checks}, fh, indent=2)
            fh.write("\n")

    for check in checks:
        mark = "ok  " if check["passed"] else "FAIL"
        print(f"  [{mark}] {check['id']}", file=sys.stderr)
        for failure in check["failures"]:
            print(f"         - {failure}", file=sys.stderr)

    if not passed:
        total = sum(len(c["failures"]) for c in checks)
        print(
            f"\ncheck_shot_table: {total} failure(s) across "
            f"{sum(1 for c in checks if not c['passed'])} check(s). "
            f"Fix the rows above and re-run — storyboarding stays blocked until all six pass.",
            file=sys.stderr,
        )
        raise SystemExit(3)

    if args.stamp:
        table["selfCheck"] = {
            "passed": True,
            "checkedAt": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
            "shotsHash": shots_digest(shots),
            "checks": [{"id": c["id"], "passed": True} for c in checks],
        }
        tmp = f"{args.table}.tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(table, fh, indent=2)
            fh.write("\n")
        os.replace(tmp, args.table)
        print(f"check_shot_table: all six passed; stamped {args.table}", file=sys.stderr)
    else:
        print("check_shot_table: all six passed", file=sys.stderr)


if __name__ == "__main__":
    main()
