#!/usr/bin/env python3
"""reuse_clips — place clips the project ALREADY OWNS on the windows they fit, so the
driver renders only what is missing.

WHY. Twenty clips sat on disk at 21:00 on 2026-08-22 (two landed, the rest parked or
archived from earlier cuts of the same film) while the plan was about to send every
window to a single-slot lane at ~30 minutes a draw. Three of those clips fit the new
windows outright. The operator: "always create a database of the videos you have, with
transcripts, so it can intelligently suggest and use them so nothing is wasted."

HOW. `index_library.py --plan --brief --song` writes a FIT TABLE on every indexed clip —
for each current window, the envelope correlation and offset measured only over the
seconds that window's face sings (the same judge the driver uses), and whether the
clip's recorded face is the window's face. This script reads that table and, for each
window with no clip in `<queueDir>/clips/`, installs the best USABLE fit (face matches,
corr >= --min-corr, |offset| <= --max-offset-ms) as `clips/<id>.mp4` with a
`<id>-reused.json` note beside it (where it came from, the numbers). Nothing is
installed on a window that already has a clip, and nothing is ever deleted.

THE GATE STAYS. lane_render re-verifies every clip already on disk when it resumes
(own-spans judge), so a reuse that does not actually sing the window's bar is parked
and rendered fresh — this script is a suggestion the driver checks, not a bypass.

`--force wNN=<path>` places a clip the operator chose by eye regardless of the table
(logged as forced, still re-verified by the driver). `--dry-run` prints the placements.
"""
import argparse
import json
import os
import shutil
import sys
import time


def say(msg: str) -> None:
    print(f"reuse_clips: {msg}", file=sys.stderr)


def load(path: str) -> dict:
    with open(path, encoding="utf-8") as handle:
        return json.load(handle)


def place(src: str, dest: str, note_path: str, note: dict, dry: bool) -> None:
    if dry:
        say(f"would place {note['window']} <- {src} ({note.get('why')})")
        return
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    shutil.copy2(src, dest)
    # beside the driver's own <id>-live-job.json, where the Draws page and the contract look
    with open(note_path, "w", encoding="utf-8") as handle:
        json.dump(note, handle, indent=1)
    say(f"{note['window']}: placed from {src} — {note.get('why')}")


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--plan", required=True, help="build/plan.json (its queueDir is where clips go)")
    ap.add_argument("--index", required=True, help="build/library-index.json with a fit table")
    ap.add_argument("--min-corr", type=float, default=0.6)
    ap.add_argument("--max-offset-ms", type=int, default=350)
    ap.add_argument("--force", action="append", default=[], metavar="wNN=PATH",
                    help="place this clip on this window regardless of the table")
    ap.add_argument("--judge", action="store_true",
                    help="run the driver's own verdict (lane_render.judge_landed: words + timing "
                         "on the face's own lines) on each candidate BEFORE placing it. The fit "
                         "table is envelope-only and cannot hear words: a take of the hook's "
                         "line 1 scored 0.93 on line 3's window (2026-08-23) and would have "
                         "cost that window its render slack.")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    plan = load(args.plan)
    index = load(args.index)
    queue = plan["queueDir"]
    clips_dir = os.path.join(queue, "clips")
    jobs = {j["id"]: j for j in plan.get("jobs", [])}

    forced = {}
    for f in args.force:
        if "=" not in f:
            sys.exit(f"reuse_clips: --force wants wNN=PATH, got {f!r}")
        wid, path = f.split("=", 1)
        if wid not in jobs:
            sys.exit(f"reuse_clips: --force names a window not in the plan: {wid}")
        if not os.path.isfile(path):
            sys.exit(f"reuse_clips: --force path does not exist: {path}")
        forced[wid] = os.path.abspath(path)

    # best usable fit per window from the table
    best = {}
    for row in index.get("clips", []):
        for fit in row.get("fits") or []:
            if not fit.get("usable"):
                continue
            if fit["corr"] < args.min_corr or abs(fit["offsetMs"]) > args.max_offset_ms:
                continue
            # SAME WORDS, OTHER WORLD IS NOT A FIT. A hook's lines repeat, so a take from the
            # lantern-evening final hook fitted the courtyard-daytime second hook on its words
            # and correlation alone — a night shot inside a day section (2026-09-02). The
            # clip's origin world must be the window's (RAP_REUSE_ANY_WORLD=1 to allow).
            w_style = fit.get("styleId") or (jobs.get(fit["window"]) or {}).get("styleId")   # the window's world
            c_style = row.get("styleId")                                                    # the clip's origin world (its live-job record)
            if w_style and c_style and c_style != w_style and os.environ.get("RAP_REUSE_ANY_WORLD") != "1":
                continue
            cur = best.get(fit["window"])
            if cur is None or fit["corr"] > cur[1]["corr"]:
                best[fit["window"]] = (row, fit)

    placed, kept, missing, suggestions = [], [], [], {}
    for wid, job in jobs.items():
        dest = os.path.join(clips_dir, f"{wid}.mp4")
        if os.path.isfile(dest):
            kept.append(wid)
            continue
        if wid in forced:
            note = {"window": wid, "from": forced[wid], "forced": True,
                    "why": "operator --force", "placedAt": time.strftime("%Y-%m-%dT%H:%M:%S%z")}
            place(forced[wid], dest, os.path.join(queue, f"{wid}-reused.json"), note, args.dry_run)
            placed.append(wid)
            continue
        hit = best.get(wid)
        if hit is None:
            missing.append(wid)
            # near-misses are worth showing: a human may accept by eye
            near = [(r, f) for r in index.get("clips", []) for f in (r.get("fits") or [])
                    if f["window"] == wid and f.get("faceOk") is not False and f["corr"] >= args.min_corr]
            if near:
                r, f = max(near, key=lambda x: x[1]["corr"])
                suggestions[wid] = {"clip": r["clip"], "corr": f["corr"], "offsetMs": f["offsetMs"],
                                    "faceOk": f.get("faceOk")}
            continue
        row, fit = hit
        if os.path.realpath(row["clip"]) == os.path.realpath(dest):
            kept.append(wid)
            continue
        if args.judge:
            import lane_render  # the driver's judge, same thresholds, same cache dir
            v = lane_render.judge_landed(dict(plan), job, row["clip"])
            if not v.get("ok"):
                say(f"{wid}: the fit table liked {os.path.basename(row['clip'])} ({fit['corr']:.2f} @ "
                    f"{fit['offsetMs']:+d} ms) but the driver's judge refuses it — {v.get('why')}; not placed")
                missing.append(wid)
                suggestions[wid] = {"clip": row["clip"], "corr": fit["corr"], "offsetMs": fit["offsetMs"],
                                    "faceOk": fit.get("faceOk"), "judge": v.get("why")}
                continue
        note = {"window": wid, "from": row["clip"], "clipId": row.get("id"), "origin": row.get("origin"),
                "corr": fit["corr"], "offsetMs": fit["offsetMs"], "styleId": fit.get("styleId"),
                "why": f"fits {wid}: corr {fit['corr']:.2f} @ {fit['offsetMs']:+d} ms on the face's own lines",
                "placedAt": time.strftime("%Y-%m-%dT%H:%M:%S%z")}
        place(row["clip"], dest, os.path.join(queue, f"{wid}-reused.json"), note, args.dry_run)
        placed.append(wid)

    summary = {"placed": placed, "alreadyOnDisk": kept, "toRender": missing,
               "nearMisses": suggestions, "dryRun": args.dry_run}
    if not args.dry_run:
        with open(os.path.join(os.path.dirname(os.path.abspath(args.plan)), "reuse-report.json"),
                  "w", encoding="utf-8") as handle:
            json.dump(summary, handle, indent=1)
    if args.json:
        print(json.dumps(summary, indent=1))
    else:
        say(f"{len(kept)} already on disk, {len(placed)} placed from the library, "
            f"{len(missing)} to render ({', '.join(missing) or 'nothing'})")
        for wid, s in suggestions.items():
            say(f"  {wid}: nearest is {os.path.basename(s['clip'])} corr {s['corr']:.2f} "
                f"@ {s['offsetMs']:+d} ms face={'?' if s['faceOk'] is None else s['faceOk']} — "
                f"not placed; --force {wid}={s['clip']} to accept by eye")


if __name__ == "__main__":
    main()
