#!/usr/bin/env python3
"""make_shot_table.py — scaffold the shot table from artifacts that already exist.

This deliberately does NOT write the creative content. It reads the storyboard
(the scene list and durations) and the story bible (cast, settings, continuity
notes) and lays out the ROWS: shot ids, durations, scene and cast bindings, an
inherited anchor block, and one empty beat per second sized to the shot.

The beats come out blank on purpose. `check_shot_table.py` refuses a beat that
is missing any of its five elements, so the empty scaffold is what forces the
per-second direction to be authored rather than skipped — the tool enforcing the
method instead of a document asking for it. Filling them in is the agent's job,
and it is the one genuinely creative step in the chain.

Re-running is safe: any shot whose beats are already authored is left untouched,
so this can be used to extend a table after the storyboard grows.

Usage:
  make_shot_table.py --project <projects/slug> [--out <path>]
                     [--style-lock pixar] [--max-shot-seconds 15]
"""
from __future__ import annotations

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

BEAT_TEMPLATE = {
    "action": "",
    "camera": "",
    "spatial": "",
    "audio": "",
    "handoff": "",
}


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


def load(path: str, what: str, required: bool = True) -> dict:
    if not os.path.isfile(path):
        if required:
            die(f"{what} not found at {path}")
        return {}
    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 scaffold_beats(duration: float) -> list[dict]:
    """One beat per whole second, plus a short tail beat for any remainder.

    The remainder beat matters: a 4.5s shot scaffolded as four beats would leave
    half a second undirected, and the gate would refuse it with a message about
    the author's arithmetic rather than about the film.
    """
    beats: list[dict] = []
    whole = int(duration)
    for i in range(whole):
        beats.append({"from": i, "to": i + 1, **BEAT_TEMPLATE})
    if duration - whole > 1e-6:
        beats.append({"from": whole, "to": round(duration, 3), **BEAT_TEMPLATE})
    if not beats:  # a sub-one-second shot is still one beat
        beats.append({"from": 0, "to": round(duration, 3), **BEAT_TEMPLATE})
    return beats


def authored(shot: dict) -> bool:
    """True when someone has already written the per-second direction."""
    return any(
        any(str(beat.get(k, "")).strip() for k in BEAT_TEMPLATE)
        for beat in shot.get("beats") or []
    )


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True, help="path to projects/<slug>")
    ap.add_argument("--out", default="", help="defaults to <project>/artifacts/shot-table.json")
    ap.add_argument("--style-lock", default="pixar",
                    help="style id from src/video/style-register.ts (default: the stylized-3D register)")
    ap.add_argument("--max-shot-seconds", type=float, default=15.0)
    args = ap.parse_args()

    project = os.path.abspath(args.project)
    if not os.path.isdir(project):
        die(f"project directory not found: {project}")
    artifacts = os.path.join(project, "artifacts")
    out_path = args.out or os.path.join(artifacts, "shot-table.json")

    storyboard = load(os.path.join(artifacts, "storyboard.json"), "storyboard")
    bible = load(os.path.join(artifacts, "story-bible.json"), "story bible", required=False)
    scenes = storyboard.get("scenes") or []
    if not scenes:
        die("the storyboard has no scenes — run `vclaw video storyboard` first")

    bible_scenes = {
        s.get("sceneIndex"): s for s in (bible.get("scenes") or []) if isinstance(s, dict)
    }
    settings = [s.get("name") for s in (bible.get("settings") or []) if isinstance(s, dict)]
    default_scene = settings[0] if len(settings) == 1 else ""

    existing = {}
    if os.path.isfile(out_path):
        prior = load(out_path, "existing shot table", required=False)
        existing = {s.get("id"): s for s in prior.get("shots") or [] if isinstance(s, dict)}

    shots: list[dict] = []
    over_ceiling: list[str] = []
    for n, scene in enumerate(scenes):
        shot_id = f"S{n + 1:02d}"
        duration = scene.get("durationSeconds")
        if not isinstance(duration, (int, float)) or duration <= 0:
            duration = 8.0
        if duration > args.max_shot_seconds:
            over_ceiling.append(f"{shot_id} ({duration}s)")

        prior = existing.get(shot_id)
        if prior and authored(prior):
            shots.append(prior)  # never overwrite authored direction
            continue

        bible_scene = bible_scenes.get(scene.get("sceneIndex", n)) or {}
        cast = scene.get("characters") or bible_scene.get("charactersPresent") or []
        notes = bible_scene.get("continuityNotes") or []

        shot: dict = {
            "id": shot_id,
            "title": (scene.get("description") or "").strip()[:60],
            "durationSeconds": duration,
            "hookType": "",
            "scene": default_scene,
            "characters": list(cast),
            "continuity": {
                "from": (notes[0] if notes and n > 0 else ""),
                "to": "",
            },
            "anchors": {
                "landmarks": [],
                "characterPositions": [{"name": c, "position": ""} for c in cast],
                "exited": [],
                "lighting": {},
            },
            "beats": scaffold_beats(float(duration)),
        }
        if prior:
            # Keep whatever WAS filled in on a previous pass, beats aside.
            for key in ("hookType", "scene", "characters", "continuity", "anchors", "title"):
                if prior.get(key):
                    shot[key] = prior[key]
        shots.append(shot)

    table = {
        "schemaVersion": 1,
        "projectSlug": storyboard.get("projectSlug") or os.path.basename(project),
        "generatedAt": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "title": bible.get("title") or "",
        "styleLockId": args.style_lock,
        "aspectRatio": bible.get("aspectRatio") or "",
        "totalDurationSeconds": round(sum(float(s["durationSeconds"]) for s in shots), 3),
        "dialogueMode": "none",
        "shots": shots,
    }
    # A previously stamped self-check is deliberately NOT carried over: the table
    # has just been rebuilt, so the old pass says nothing about the new rows.

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

    blank = [s["id"] for s in shots if not authored(s)]
    print(f"make_shot_table: {len(shots)} shot(s), "
          f"{table['totalDurationSeconds']}s total -> {out_path}", file=sys.stderr)
    if over_ceiling:
        print(f"  note: {', '.join(over_ceiling)} exceed the {args.max_shot_seconds}s ceiling "
              f"and the gate will refuse them — split those scenes.", file=sys.stderr)
    if blank:
        print(f"  {len(blank)} shot(s) need per-second direction authored: {', '.join(blank)}",
              file=sys.stderr)
        print("  Each beat needs all five: action, camera, spatial, audio, handoff.",
              file=sys.stderr)
    print(json.dumps({"table": out_path, "shots": len(shots), "needAuthoring": blank}))


if __name__ == "__main__":
    main()
