#!/usr/bin/env python3
"""salvage_plan.py — cut the film that CAN be made when a window will not render.

`render-all` can legitimately give up on a window: moderation is roughly a coin flip
per draw, and after the draws are spent the clip does not exist. The runner's answer is
"continue with fewer windows" — but "fewer" has to mean a film that can actually be
assembled, and a MISSING MIDDLE WINDOW IS NOT THAT.

  w00 w01 w02 --- w04 w05        <- the assembler has no picture for 42-56s.
                                    build_mv_config pins nothing and select_cut
                                    refuses with "no performer cut at all" — correct,
                                    and hours after the renders were paid for.

Every clip is locked to the bar it was rendered against, so a gap cannot be closed by
sliding the later windows earlier: their mouths would be on the wrong words. The only
honest reduction is the CONTIGUOUS PREFIX — the film covers the first N windows of the
song and ends. That is a shorter film, not a broken one.

It refuses to write a film that would be a fraction of its song: MIN_COVERAGE mirrors
plan_coherence, because a 26%-of-the-song film has shipped before and no gate caught it.

Usage:
  salvage_plan.py --plan build/plan.json [--clips <dir>] [--write] [--json]

Reports by default; --write trims plan.json and keeps the original beside it.
Exit 0 nothing to do or salvage possible · 4 what landed cannot make a film · 2 bad input
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import sys

MIN_COVERAGE = 0.6      # mirrors plan_coherence.MIN_SONG_COVERAGE


def landed(plan: dict, clips_dir: str) -> set[str]:
    if not os.path.isdir(clips_dir):
        return set()
    return {f[:-4] for f in os.listdir(clips_dir) if f.endswith(".mp4")}


def prefix(jobs: list[dict], have: set[str]) -> list[dict]:
    """The longest run of windows from the START that all have a clip."""
    keep: list[dict] = []
    for j in sorted(jobs, key=lambda j: float(j.get("startSec") or 0)):
        if j["id"] not in have:
            break
        keep.append(j)
    return keep


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--clips", default="")
    ap.add_argument("--write", action="store_true")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    if not os.path.isfile(args.plan):
        print(f"salvage_plan: no plan at {args.plan}", file=sys.stderr)
        raise SystemExit(2)
    plan = json.load(open(args.plan, encoding="utf-8"))
    jobs = plan.get("jobs") or []
    clips_dir = args.clips or os.path.join(plan.get("queueDir", ""), "clips")

    have = landed(plan, clips_dir)
    missing = [j["id"] for j in jobs if j["id"] not in have]
    keep = prefix(jobs, have)
    film = sum(float(j.get("seconds") or 0) for j in keep)
    song = max((float(j.get("startSec") or 0) + float(j.get("seconds") or 0))
               for j in jobs) if jobs else 0.0
    coverage = film / song if song else 0.0
    dropped = [j["id"] for j in jobs if j not in keep]

    summary = {"landed": sorted(have), "missing": missing,
               "keep": [j["id"] for j in keep], "drop": dropped,
               "filmSeconds": round(film, 2), "plannedSeconds": round(song, 2),
               "coverage": round(coverage, 3)}
    if args.json:
        print(json.dumps(summary, indent=2))

    if not missing:
        if not args.json:
            print(f"salvage_plan: every window landed — nothing to salvage")
        return

    if not args.json:
        print(f"salvage_plan: {len(missing)} window(s) never rendered: "
              f"{', '.join(missing)}")
        # Naming the hole matters more than naming the count: a missing TAIL window is
        # free to drop, a missing MIDDLE one costs every window after it.
        buried = [j["id"] for j in jobs if j["id"] in have and j not in keep]
        if buried:
            print(f"  {len(buried)} clip(s) that DID render sit after the gap and cannot "
                  f"be used: {', '.join(buried)}")
            print(f"  (every clip is locked to the bar it was rendered against, so they "
                  f"cannot slide earlier — their mouths would be on the wrong words)")

    if coverage < MIN_COVERAGE or not keep:
        print(f"salvage_plan: REFUSED — the salvageable film is {film:.0f}s of a "
              f"{song:.0f}s song ({coverage:.0%}), under the {MIN_COVERAGE:.0%} floor.\n"
              f"  Re-run render-all for the missing windows rather than shipping this.",
              file=sys.stderr)
        raise SystemExit(4)

    if not args.write:
        print(f"  salvageable: {len(keep)} window(s), {film:.0f}s of {song:.0f}s "
              f"({coverage:.0%}). Re-run with --write to trim the plan.")
        return

    backup = args.plan.replace(".json", ".full.json")
    if not os.path.exists(backup):
        shutil.copy2(args.plan, backup)
    plan["jobs"] = keep
    plan["salvagedFrom"] = os.path.basename(backup)
    json.dump(plan, open(args.plan, "w", encoding="utf-8"), indent=1)
    print(f"  trimmed to {len(keep)} window(s), {film:.0f}s ({coverage:.0%}). "
          f"The full plan is at {os.path.basename(backup)}.")


if __name__ == "__main__":
    main()
