#!/usr/bin/env python3
"""make_broll_plan.py — author build/broll-plan.json from the vocal map's gaps.

THE HOLE THIS FILLS. The pipeline has always CONSUMED B-roll — `render-all` renders a
broll-plan.json when one exists, `cover` cuts its clips into the mouthing stretches —
but nothing ever PRODUCED the plan. `BROLL_PER_STYLE` was a knob wired to nothing, and
the runner's own comment admitted it: "every film that had any got it by hand." On the
film that produced this script, the cutaways were hand-written at 19:37, hours AFTER
delivery, when the operator saw a man mouthing over thirteen seconds of instrumental.

POLICY: GAPS ONLY (operator decision). The demand comes from the vocal map's word-derived
`silentStretches`; a song that sings all the way through gets no B-roll and this script
says so and exits 0. No variety pool, no per-style quota.

ONE JOB PER DISTINCT GAP-OWNING STYLE. A gap inside w01 gets a cutaway in w01's own
world, so the cut reads as deliberate rather than stock; three gaps in black-sand
windows share one black-sand cutaway (`cover` reads from the clip's own start and
wraps, so one clip covers several holes in different windows).

CLIP LENGTH SERVES TWO CONSUMERS AT ONCE:
  * cover_mouthing needs the cutaway to outlast the longest hole it fills;
  * plan_coherence's pool check (check #5) fails preflight unless at least one clip
    reaches longest_window + 1.2s — and a pool that exists but is all-undersized is
    exactly the shape that check was written against.
So: seconds = min(route unsynced cap, max(longest_hole, longest_window) + 1.2),
whole-second. At 14s windows on seedance-direct that is 16s against a 20s cap.

THE PLAN SHAPE is exactly what explore_queue.load_plan validates: schemaVersion 1, the
route/aspect/resolution the render plan already carries, queueDir build/broll (the
`cover` stage hardcodes build/broll/clips), and jobs of id+prompt+seconds with NO
identityRef, NO voiceRef, NO synced — the clean people-free shape that skips every
reference check. `render-all` then renders both plans in ONE work list on the one slot.

Usage:
  make_broll_plan.py --plan build/plan.json --vocal-map build/vocal-map.json \
                     --styles-drawn build/styles-drawn.json --styles <register.json> \
                     --out build/broll-plan.json [--min-cover 1.0] [--json]

Exit 0 written or legitimately nothing to do · 2 unreadable input.
"""
from __future__ import annotations

import argparse
import json
import math
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from compose_prompts import compose_broll  # noqa: E402
from make_plan import max_clip_for  # noqa: E402
import raplib  # noqa: E402


def gap_styles(plan: dict, stretches: list, min_cover: float) -> tuple[list, float]:
    """(ordered distinct styleIds owning a coverable gap, longest hole in seconds).

    A stretch is charged to every window it overlaps by at least min_cover — the same
    floor cover_mouthing applies, so this plans exactly what cover will later cut.
    """
    owners: list[str] = []
    longest = 0.0
    jobs = plan.get("jobs", [])
    for g in stretches:
        gs, ge = float(g["start"]), float(g["end"])
        hit = False
        for j in jobs:
            ws = float(j.get("startSec") or 0)
            we = ws + float(j.get("seconds") or 0)
            lo, hi = max(gs, ws), min(ge, we)
            if hi - lo >= min_cover:
                hit = True
                longest = max(longest, hi - lo)
                sid = j.get("styleId") or "default"
                if sid not in owners:
                    owners.append(sid)
        if not hit and ge - gs >= min_cover and jobs:
            # A STRETCH NO WINDOW TOUCHES IS STILL A SECTION. Sung-length renders stop at
            # the last word, so the outro after it overlaps nothing — and this planned no
            # cutaway for it while select_cut opened the section anyway (the duet fixture,
            # 2026-09-02). Charged to the nearest window's world, so the cut into it reads
            # as that world's own cutaway rather than a stock shot from elsewhere.
            def _dist(j: dict) -> float:
                ws = float(j.get("startSec") or 0)
                return max(0.0, ws - ge, gs - (ws + float(j.get("seconds") or 0)))
            near = min(jobs, key=_dist)
            longest = max(longest, ge - gs)
            sid = near.get("styleId") or "default"
            if sid not in owners:
                owners.append(sid)
    return owners, longest


def build(plan: dict, vocal_map: dict, styles_by_id: dict, project_dir: str,
          min_cover: float, tail: str = "", every_style: bool = False) -> dict | None:
    stretches = vocal_map.get("silentStretches") or []
    owners, longest_hole = gap_styles(plan, stretches, min_cover)
    # THE CUT'S OWN SECTIONS SIZE THE POOL. Sung-length windows leave every instrumental
    # between lines (and the outro) as a section that takes a cutaway slice; a world
    # with more hole-seconds than one clip holds needs a second clip. The holes come
    # from the plan's geometry (raplib.plan_holes — the rule select_cut tiles by), so
    # what is planned here is exactly what the cut will ask for; the vocal map's
    # stretches still add the worlds whose windows `cover` may need to cut into.
    cap = max_clip_for(plan.get("route", ""), synced=False)
    holes = raplib.plan_holes(plan, cap=cap)        # split so every piece fits one clip
    demand: dict[str, float] = {}
    hole_owners: list[str] = []
    for h in holes:
        sid = h.get("styleId") or "default"
        demand[sid] = demand.get(sid, 0.0) + float(h["seconds"]) + 0.2
        longest_hole = max(longest_hole, float(h["seconds"]))
        if sid not in hole_owners:
            hole_owners.append(sid)
    owners = hole_owners + [sid for sid in owners if sid not in hole_owners]
    if every_style:
        # ONE CUTAWAY PER WORLD, not just per gap. The gaps-only policy gave a film
        # three cutaways for eight looks, so every sync cover (drift, wrong bar, a
        # held frame) recycled the same tunnel/lounge/convertible shot — the operator
        # saw the repeat ("add more B-roll, you are repeating a lot", 2026-08-29).
        # A cutaway from the window's OWN world reads as a deliberate cut; the cover
        # stage picks by style when the pool has one.
        seen = list(dict.fromkeys(owners))
        for j in plan["jobs"]:
            sid = j.get("styleId")
            if sid and sid not in seen:
                seen.append(sid)
        owners = seen
    gap_owners = set(gap_styles(plan, stretches, min_cover)[0]) | set(hole_owners)
    if not owners:
        return None

    longest_window = max(float(j.get("seconds") or 0) for j in plan["jobs"])
    seconds = float(min(cap, math.ceil(max(longest_hole, longest_window) + 1.2)))

    jobs = []
    # one clip per world, plus one for every further clip-length of that world's holes
    per_world = [(sid, max(1, math.ceil(demand.get(sid, 0.0) / max(seconds - 0.2, 1.0)))) for sid in owners]
    for i, (sid, _n) in enumerate((sid, k) for sid, n in per_world for k in range(n)):
        style = styles_by_id.get(sid)
        if style is None:
            # The plan names a style the register does not carry. That is the same
            # disagreement plan_coherence exists to refuse: two artifacts that must
            # match, silently drifted (a pack swapped STYLES_FILE after planning).
            # Composing a cutaway in an arbitrary other world would hide it.
            print(f"make_broll_plan: window style {sid!r} is not in the register — "
                  f"the plan and STYLES_FILE disagree. Re-run the plan stage, or fix "
                  f"the register.", file=sys.stderr)
            raise SystemExit(2)
        job = {
            "id": f"b{i:02d}",
            "window": 100 + i,          # clear of every real window index
            "startSec": 0.0,
            "seconds": seconds,
            "styleId": style["id"],
            "section": "instrumental",
            "prompt": compose_broll(style, seconds, tail),
        }
        if sid not in gap_owners:
            # DEFERRED. A per-world cutaway is only worth ~30 min of the single slot
            # when a cover in that world is actually needed. Five were rendered up
            # front on the nineties film and two hours later three were used. It rides
            # in the SAME approved contract (no second approval) but lane_render skips
            # it until the NEEDS report names it (--only bNN).
            job["deferred"] = True
        jobs.append(job)

    return {
        "schemaVersion": plan.get("schemaVersion", 1),
        "lane": plan.get("lane", "explore"),
        "route": plan["route"],
        "aspect": plan["aspect"],
        "resolution": plan.get("resolution", "720p"),
        "seconds": seconds,
        "projectDir": plan.get("projectDir", project_dir),
        "queueDir": os.path.join(project_dir, "build", "broll"),
        "jobs": jobs,
    }


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--vocal-map", required=True)
    ap.add_argument("--styles-drawn", required=True)
    ap.add_argument("--styles", required=True, help="the styles register (STYLES_FILE)")
    ap.add_argument("--out", required=True)
    ap.add_argument("--min-cover", type=float, default=1.0,
                    help="mirrors cover_mouthing: shorter gaps are not cutaways")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--every-style", action="store_true",
                    help="plan one cutaway per style in the film (not only per silent "
                         "gap) so sync covers can draw from the window's own world")
    args = ap.parse_args()

    for path in (args.plan, args.vocal_map, args.styles):
        if not os.path.isfile(path):
            print(f"make_broll_plan: missing {path}", file=sys.stderr)
            raise SystemExit(2)

    plan = json.load(open(args.plan, encoding="utf-8"))
    vocal_map = json.load(open(args.vocal_map, encoding="utf-8"))
    register = json.load(open(args.styles, encoding="utf-8"))
    grammar = int(register.get("grammarVersion", 1) or 1)
    styles_by_id = {s["id"]: ({**s, "_grammar": grammar} if grammar >= 2 else s)
                    for s in register.get("styles", [])}
    if not styles_by_id:
        print(f"make_broll_plan: {args.styles} has no styles", file=sys.stderr)
        raise SystemExit(2)
    project_dir = os.path.dirname(os.path.dirname(os.path.abspath(args.out)))

    # promptTail ("Multiple cuts.") is a PERFORMANCE device — internal cuts inside a
    # cutaway that gets sliced into holes read as glitches. B-roll is one move.
    broll = build(plan, vocal_map, styles_by_id, project_dir, args.min_cover, "", args.every_style)
    if broll is None:
        print("make_broll_plan: the song sings throughout — no B-roll needed "
              "(gaps-only policy; no coverable silent stretch in the vocal map)")
        return

    json.dump(broll, open(args.out, "w", encoding="utf-8"), indent=1)
    if args.json:
        print(json.dumps(broll, indent=2))
    else:
        holes = len(vocal_map.get("silentStretches") or [])
        print(f"make_broll_plan: {len(broll['jobs'])} cutaway(s) at "
              f"{broll['seconds']:g}s for {holes} silent stretch(es) and {len(raplib.plan_holes(plan, cap=max_clip_for(plan.get("route", ""), synced=False)))} gap section(s) -> {args.out}")
        for j in broll["jobs"]:
            print(f"   {j['id']}  [{j['styleId']}]  {j['prompt'][:88]}…")


if __name__ == "__main__":
    main()
