#!/usr/bin/env python3
"""replace_window.py — everything that must happen when one window's clip changes.

WHY THE RUNNER OWNS THIS. Every re-render on the last film meant hand-deciding which
artifacts to void and where to rewind the state file — and the agent driving it got the
rewind point wrong twice in one day: once leaving a stale selection pointing at deleted
files ("performer clip 'w00' does not resolve"), once forgetting the transcript store.
The dependency knowledge belongs in the tool, not in whoever is driving it.

THE TWO PARKS THAT ARE NOT OPTIONAL:
  * the CLIP — obviously.
  * the LIVE-JOB RECORD — the lesson that cost a render: parking the clip alone lets
    `reconcile` legitimately hand the very same take back (the record still matches the
    plan, so recovery is correct behaviour). Park the record and the driver renders
    fresh.
  * operator-authored cut-<sid>.json files are parked too: their clipIds are CONTENT
    hashes, so a replaced clip invalidates the assignment and the `select` gate must
    re-fire rather than silently mis-assign.

WHAT IS VOIDED (the dependency table, encoded here so nobody re-derives it):
  global   library-index/ids/html, strips/, cutaways.json, captions.ass,
           segments/, concat-*            (all derived from the clip set)
  per sid  selection- sync- windows- cut-*.html sync-report- shift-report-
           word-sync- sync-profile- review- mv- sheet- shifted-*/ deliver-* 4k-*/
WHAT IS LEFT:
  artifacts/clip-transcripts.json   content-keyed; heals itself on re-transcribe
  final/videos/                     masters are append-only versioned; master_version
                                    bumps to v(N+1) and VERSIONS.md records it
  build/broll*                      cutaways are content-independent of performance takes
  voice/, plan.json, hook.*         the plan did not change — only one take did

Everything parked goes to <queueDir>/superseded/ named for the reason, never deleted.

Usage:
  replace_window.py --project <dir> --windows w01[,w02] [--reason <slug>] [--dry-run]

Exit 0 done (or nothing to do) · 2 unknown window / bad input.
"""
from __future__ import annotations

import argparse
import glob
import json
import os
import shutil
import sys
import time


def park(src: str, superseded: str, name: str, log: list) -> None:
    if os.path.isfile(src):
        os.makedirs(superseded, exist_ok=True)
        dest = os.path.join(superseded, name)
        shutil.move(src, dest)
        log.append(f"parked  {src} -> {dest}")


def void(paths: list[str], log: list) -> None:
    for p in paths:
        if os.path.isdir(p):
            shutil.rmtree(p)
            log.append(f"voided  {p}/")
        elif os.path.isfile(p):
            os.remove(p)
            log.append(f"voided  {p}")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--windows", default="", help="comma list, e.g. w01,w04")
    ap.add_argument("--replan", action="store_true",
                    help="the plan's geometry changed: park nothing in the queue (clips are pinned by "
                         "geometry), void everything the OLD plan derived — selections, cuts, sync/shift/"
                         "cover records, fitted/joined copies, the collapse. New Era 2026-08-31: stale "
                         "selections from the night before un-collapsed the film and stale shift/cover "
                         "records fed KNOWN-ISSUES.")
    ap.add_argument("--reason", default="replaced",
                    help="stamped into the parked filenames")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

    P = args.project
    lock_path = os.path.join(P, "build", "reuse-cut.lock")
    if os.path.isfile(lock_path):
        print(f"replace_window: REFUSED — {lock_path} locks the approved reuse cut. "
              "Remove that file only when the operator has explicitly approved new "
              "provider renders. Nothing was changed.", file=sys.stderr)
        raise SystemExit(2)
    plan_path = os.path.join(P, "build", "plan.json")
    if not os.path.isfile(plan_path):
        print(f"replace_window: no plan at {plan_path}", file=sys.stderr)
        raise SystemExit(2)
    plan = json.load(open(plan_path, encoding="utf-8"))
    known = {j["id"] for j in plan.get("jobs", [])}
    # CUTAWAYS TOO (operator, 2026-09-05): a bNN from build/broll-plan.json parks in the
    # b-roll queue — three empty-set cutaways had to be moved by hand because this
    # script only knew the performance windows.
    broll_path = os.path.join(P, "build", "broll-plan.json")
    broll_known: set[str] = set()
    broll_queue = os.path.join(P, "build", "broll")
    if os.path.isfile(broll_path):
        try:
            bplan = json.load(open(broll_path, encoding="utf-8"))
            broll_known = {j["id"] for j in bplan.get("jobs", [])}
            bq = bplan.get("queueDir") or broll_queue
            broll_queue = bq if os.path.isabs(bq) else os.path.join(P, bq)
        except (OSError, ValueError):
            pass
    wanted = [w.strip() for w in args.windows.split(",") if w.strip()]
    if not wanted and not args.replan:
        print("replace_window: --windows wNN[,wNN] or --replan is required. Nothing was changed.", file=sys.stderr)
        raise SystemExit(2)

    # VALIDATE EVERYTHING BEFORE TOUCHING ANYTHING. A typo'd window id must not leave
    # the project half-voided.
    unknown = [w for w in wanted if w not in known and w not in broll_known]
    if unknown:
        print(f"replace_window: unknown window(s) {', '.join(unknown)} — the plan has "
              f"{', '.join(sorted(known))}"
              f"{(' and the cutaways ' + ', '.join(sorted(broll_known))) if broll_known else ''}. "
              f"Nothing was changed.", file=sys.stderr)
        raise SystemExit(2)

    queue = plan.get("queueDir") or os.path.join(P, "build", "queue", "explore")
    if not os.path.isabs(queue):
        queue = os.path.join(P, queue)
    superseded = os.path.join(queue, "superseded")
    stamp = time.strftime("%m%d-%H%M")
    build = os.path.join(P, "build")

    # THE PLAN OF RECORD, printed before acting — the operator sees what will happen
    # to which files, and a --dry-run stops here.
    per_style_globs = [
        "selection-*.json", "sync-*.json", "windows-*.json", "cut-*.html", "cutaways-*.json",
        "sync-report-*.json", "shift-report-*.json", "word-sync-*.json",
        "sync-profile-*.json", "review-*.html", "review-*.json", "mv-*.json",
        "sheet-*.jpg", "deliver-*.json", "deliver-*.log", "deliver-*.out",
        "deliver-*.pid", "qc-report.json", "qc-report.html", "qc-sheet-*.jpg",
    ]
    global_paths = [os.path.join(build, n) for n in (
        "library-index.json", "library-ids.json", "library.html",
        "cutaways.json", "captions.ass",
        # derived from the selections; a stale collapse would silently skip styles
        "styles-effective.json")]
    dir_globs = ["shifted-*", "segments", "strips", "4k-*", "fitted-*", "joined-*", "rated-*"]
    if args.replan:
        per_style_globs += ["needs-*.json", "needs-*.html", "fits-*.json", "joins-*.json",
                            "transcript-words-vocalswap-*.json", "vocal-swap-*.json", "audio-vocalswap-*.wav"]
        global_paths += [os.path.join(build, n) for n in ("salvage-cover.json", "slices.json", "slices.html")]
    file_globs = ["concat-*"]

    voids: list[str] = list(global_paths)
    for g in per_style_globs + file_globs:
        voids += glob.glob(os.path.join(build, g))
    for g in dir_globs:
        voids += [d for d in glob.glob(os.path.join(build, g)) if os.path.isdir(d)]
    # broll artifacts are content-independent of performance takes — never void them
    voids = [v for v in voids if "/broll" not in v]

    print(f"replace_window: {', '.join(wanted) or 'RE-PLAN (no window parked)'} — the plan of record:")
    for w in wanted:
        print(f"  park  {queue}/clips/{w}.mp4")
        print(f"  park  {queue}/{w}-live-job.json   <- without this, reconcile hands "
              f"the same take back")
    cut_jsons = sorted(glob.glob(os.path.join(build, "cut-*.json")))
    for c in cut_jsons:
        print(f"  park  {c}   <- clipIds are content hashes; the assignment is stale")
    existing = [v for v in voids if os.path.exists(v)]
    for v in sorted(existing):
        print(f"  void  {v}")
    print(f"  then: state rewinds to render-all — it renders ONLY the missing "
          f"window(s) and every later stage rebuilds")
    if args.dry_run:
        print("replace_window: --dry-run — nothing changed")
        return

    log: list[str] = []
    for w in wanted:
        q = broll_queue if w in broll_known and w not in known else queue
        sup = os.path.join(q, "superseded")
        os.makedirs(sup, exist_ok=True)
        park(os.path.join(q, "clips", f"{w}.mp4"), sup,
             f"{w}-{args.reason}-{stamp}.mp4", log)
        park(os.path.join(q, f"{w}-live-job.json"), sup,
             f"{w}-live-job-{args.reason}-{stamp}.json", log)
    for c in cut_jsons:
        park(c, superseded, f"{os.path.basename(c)}.{args.reason}-{stamp}", log)
    void(existing, log)

    for line in log:
        print(f"  {line}")
    print(f"replace_window: done — {len(log)} action(s). Re-run the runner; render-all "
          f"resumes and renders only {', '.join(wanted)}.")


if __name__ == "__main__":
    main()
