#!/usr/bin/env python3
"""author_cuts.py — write cut-<style>.json for every drawn style: each window takes ITS OWN take.

The `select` gate asks a human to author the cut from library.html. On a film where
every window rendered its own take and the assembly is one film walking through its
worlds (--sections), the cut is not a choice: window N takes the clip rendered for
window N. This writes that assignment for every style the film draws, from the
library index (whose clip ids are the ones select_cut resolves), so an unattended run
can pass the gate honestly. A window with no take of its own is left out and named,
so select_cut refuses it rather than guessing.

Usage:
  author_cuts.py --plan build/plan.json --library build/library-index.json \
                 --styles-drawn build/styles-drawn.json --build build [--note "..."]
"""
from __future__ import annotations

import argparse
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))


def window_index_by_start(plan_path: str, plan: dict, fps: int = 24) -> dict:
    """plan job id -> select_cut window index, matched by where the take lands in the song.

    select_cut numbers its windows in song order INCLUDING the instrumental-gap sections
    it derives from the plan, so the plan's own `window` numbers drift by one past every
    gap (New Era pass 1, 2026-08-31: w03's 6 s take was put on w02's 11 s slot and the
    cut was refused). A take lands at startSec + trimStartSec; that start is the key.
    Falls back to the plan's `window` for a job that matches no window (a bare fixture)."""
    try:
        import select_cut  # sibling; the one implementation of the window grid
        wins = select_cut.windows_from_plan(plan_path, fps)
    except Exception:
        return {j["id"]: int(j["window"]) for j in plan.get("jobs", []) if "window" in j}
    out = {}
    for j in plan.get("jobs", []):
        if "startSec" not in j:
            if "window" in j:
                out[j["id"]] = int(j["window"])
            continue
        lands = float(j["startSec"]) + float(j.get("trimStartSec") or 0.0)
        best = min(((abs(float(w["start"]) - lands), i) for i, w in enumerate(wins) if not w.get("gap")),
                   default=None)
        if best and best[0] < 0.25:
            out[j["id"]] = best[1]
        elif "window" in j:
            out[j["id"]] = int(j["window"])
    return out


def own_clip_ids(library: dict) -> dict:
    """window id -> library clip id, for clips that ARE a window's take (queue/clips/wNN.mp4)."""
    own = {}
    for c in library.get("clips", []):
        base = os.path.basename(c.get("clip") or "")
        if base.startswith("w") and base.endswith(".mp4") and "-" not in base and c.get("origin") == "queue":
            own[base[:-4]] = c["id"]
    return own


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--library", required=True)
    ap.add_argument("--styles-drawn", required=True)
    ap.add_argument("--build", required=True)
    ap.add_argument("--note", default="every window takes its own take (author_cuts.py)")
    ap.add_argument("--fps", type=int, default=24, help="the film's fps (select_cut's window grid is in frames)")
    a = ap.parse_args()
    plan = json.load(open(a.plan, encoding="utf-8"))
    lib = json.load(open(a.library, encoding="utf-8"))
    drawn = json.load(open(a.styles_drawn, encoding="utf-8"))
    styles = [s["id"] if isinstance(s, dict) else s for s in (drawn if isinstance(drawn, list) else drawn.get("styles", []))]
    own = own_clip_ids(lib)
    index = window_index_by_start(a.plan, plan, a.fps)
    rows, missing = [], []
    for j in plan.get("jobs", []):
        cid = own.get(j["id"])
        if cid and j["id"] in index:
            rows.append({"window": index[j["id"]], "clipId": cid})
        else:
            missing.append(j["id"])
    rows.sort(key=lambda r: r["window"])
    if not rows:
        print("author_cuts: no window has its own take in the library", file=sys.stderr)
        return 2
    doc = {"assignments": rows, "_authored": a.note}
    for sid in styles:
        json.dump(doc, open(os.path.join(a.build, f"cut-{sid}.json"), "w", encoding="utf-8"), indent=1)
    print(f"author_cuts: {len(rows)} window(s) -> {len(styles)} cut file(s)"
          + (f" · no take for: {', '.join(missing)}" if missing else ""), file=sys.stderr)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
