#!/usr/bin/env python3
"""master_version.py — give every master a version, and refuse to lose one.

The `cut` stage used to write `final/videos/<slug>-<style>.mp4` directly, so a
re-run overwrote the master in place and the previous cut was gone. That is not a
hypothetical loss. Great Indian Summer took EIGHT masters to get right, and at v7
the operator asked for a clip to be brought BACK from v2 — a window that had been
replaced twice since and was better in the older cut. History is load-bearing on
this lane: the review is iterative, versions get partially reverted, and "which
clip was in v4 again" is a question that gets asked out loud.

So: `<slug>-<style>-v<N>.mp4`, N allocated by looking at what is already on disk,
and a REFUSAL rather than an overwrite if the target exists. There is no --force.
A force flag on a command whose whole purpose is not losing the previous master
would be the first thing reached for on a re-run.

Three verbs:

  next     print the path the next master should be written to (and allocate N)
  record   after the master exists, append a VERSIONS.md entry saying what changed
  latest   print the newest version's path — so nothing downstream has to parse
           filenames by eye or hardcode a number, which is how a review page ends
           up showing a four-versions-stale cut

What CHANGED between versions is computed from the selections, not typed in: each
version records the clip chosen per window, so `record` diffs this version's
selection against the previous one and writes the windows that actually moved.
An operator reason per window comes from `overrides.json` when present, so the
rationale lives beside the data instead of inside a build script — on the film
this came from, every version bump meant editing a dict in a Python file.

Usage:
  master_version.py next   --project <dir> --slug <s> --style <id>
  master_version.py record --project <dir> --slug <s> --style <id>
                           --master <path> --selection <selection-<id>.json>
                           [--overrides <overrides.json>] [--note "..."]
  master_version.py latest --project <dir> --slug <s> --style <id>
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys
from datetime import datetime, timezone

VERSIONS_MD = "VERSIONS.md"


def die(msg: str) -> None:
    print(f"master_version: {msg}", file=sys.stderr)
    raise SystemExit(5)


def videos_dir(project: str) -> str:
    return os.path.join(project, "final", "videos")


def version_re(slug: str, style: str) -> re.Pattern[str]:
    return re.compile(rf"^{re.escape(slug)}-{re.escape(style)}-v(\d+)\.mp4$")


def existing_versions(project: str, slug: str, style: str) -> list[tuple[int, str]]:
    """Every version on disk, ascending. Disk is the source of truth, not a counter
    file — a counter drifts the moment someone copies or deletes a master by hand."""
    d = videos_dir(project)
    if not os.path.isdir(d):
        return []
    pat = version_re(slug, style)
    out = []
    for name in os.listdir(d):
        m = pat.match(name)
        if m:
            out.append((int(m.group(1)), os.path.join(d, name)))
    return sorted(out)


def next_version(project: str, slug: str, style: str) -> tuple[int, str]:
    versions = existing_versions(project, slug, style)
    n = (versions[-1][0] + 1) if versions else 1
    path = os.path.join(videos_dir(project), f"{slug}-{style}-v{n}.mp4")
    if os.path.exists(path):
        # Only reachable if the numbering and the filesystem disagree — a stale
        # half-written file, say. Refuse rather than clobber it.
        die(f"refusing to overwrite an existing master: {path}")
    return n, path


def selection_map(path: str) -> dict[str, str]:
    """window id -> the clip chosen for it, read from `select_cut.py`'s selection.

    The authority is `provenance` — `{window_id: {clipId, origin, ...}}` — which is
    what select_cut actually writes, resolved through `clips` to a filename so the
    VERSIONS entry names something an operator can find on disk rather than an
    internal id. The sidecar written by `record` is the flat `{wid: filename}`
    form, so that is accepted too; anything else returns empty rather than
    guessing, because a wrong diff is worse than no diff.
    """
    if not path or not os.path.isfile(path):
        return {}
    try:
        data = json.load(open(path, encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {}
    if not isinstance(data, dict):
        return {}

    prov = data.get("provenance")
    if isinstance(prov, dict):
        by_id = {}
        for c in data.get("clips", []) if isinstance(data.get("clips"), list) else []:
            if isinstance(c, dict) and c.get("id"):
                by_id[str(c["id"])] = os.path.basename(str(c.get("clip") or c["id"]))
        out = {}
        for wid, rec in prov.items():
            cid = str(rec.get("clipId", "")) if isinstance(rec, dict) else str(rec)
            if cid:
                out[str(wid)] = {"clipId": cid, "file": by_id.get(cid, cid)}
        return out

    # The sidecar form, already {window: {clipId, file}}.
    if data and all(isinstance(v, dict) and "file" in v for v in data.values()):
        return {str(k): {"clipId": v.get("clipId", ""), "file": v["file"]} for k, v in data.items()}
    return {}


def files_only(sel: dict[str, dict]) -> dict[str, str]:
    """Just window -> filename, for the human-readable diff."""
    return {w: r["file"] for w, r in sel.items()}


def sidecar(master: str) -> str:
    """Each version's selection is stored beside it, so a later `record` can diff
    against what that version ACTUALLY shipped rather than against whatever the
    live selection file happens to say now."""
    return f"{os.path.splitext(master)[0]}.selection.json"


def diff_windows(prev: dict[str, str], cur: dict[str, str]) -> list[tuple[str, str, str]]:
    out = []
    for wid in sorted(set(prev) | set(cur), key=lambda w: (len(w), w)):
        a, b = prev.get(wid, "—"), cur.get(wid, "—")
        if a != b:
            out.append((wid, a, b))
    return out


def cmd_next(args: argparse.Namespace) -> None:
    n, path = next_version(args.project, args.slug, args.style)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    print(json.dumps({"version": n, "path": path}))


def cmd_latest(args: argparse.Namespace) -> None:
    versions = existing_versions(args.project, args.slug, args.style)
    if not versions:
        die(f"no master yet for style '{args.style}' — run the cut stage first")
    n, path = versions[-1]
    print(json.dumps({"version": n, "path": path}))


def cmd_record(args: argparse.Namespace) -> None:
    if not os.path.isfile(args.master):
        die(f"master does not exist: {args.master} — record AFTER the cut, not before")
    m = version_re(args.slug, args.style).match(os.path.basename(args.master))
    if not m:
        die(f"not a versioned master: {os.path.basename(args.master)} "
            f"(expected {args.slug}-{args.style}-v<N>.mp4 — use `next` to get the path)")
    n = int(m.group(1))

    cur_full = selection_map(args.selection)
    prev_versions = [v for v in existing_versions(args.project, args.slug, args.style) if v[0] < n]
    prev_full = selection_map(sidecar(prev_versions[-1][1])) if prev_versions else {}
    cur, prev = files_only(cur_full), files_only(prev_full)

    if cur_full:
        # The sidecar keeps the clipId as well as the filename. The clipId is derived
        # from the clip's CONTENT hash, so the review board can answer "which clip is
        # in the film right now" by identity rather than by a lane name or a version
        # number — the two things that made the board show a four-versions-old cut.
        json.dump(cur_full, open(sidecar(args.master), "w", encoding="utf-8"), indent=2)

    reasons = {}
    if args.overrides and os.path.isfile(args.overrides):
        ov = json.load(open(args.overrides, encoding="utf-8"))
        rows = ov.get("windows", ov) if isinstance(ov, dict) else ov
        if isinstance(rows, dict):
            for wid, r in rows.items():
                reasons[str(wid)] = r.get("reason", "") if isinstance(r, dict) else str(r)

    changed = diff_windows(prev, cur)
    stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    lines = [f"\n## {args.slug}-{args.style} v{n} — {stamp}\n",
             f"- master: `{os.path.basename(args.master)}`"]
    if args.note:
        lines.append(f"- note: {args.note}")
    if not prev_versions:
        lines.append(f"- first version ({len(cur)} windows)")
    elif not changed:
        # Worth stating plainly: a rebuild with an identical selection is usually a
        # re-encode, and reading "no windows changed" saves re-reviewing all of them.
        lines.append(f"- no windows changed vs v{prev_versions[-1][0]} (rebuild only)")
    else:
        lines.append(f"- {len(changed)} window(s) changed vs v{prev_versions[-1][0]}:")
        for wid, a, b in changed:
            why = f" — {reasons[wid]}" if reasons.get(wid) else ""
            lines.append(f"  - `{wid}`: {a} → {b}{why}")

    path = os.path.join(videos_dir(args.project), VERSIONS_MD)
    header = "" if os.path.exists(path) else f"# {args.slug} — master versions\n"
    with open(path, "a", encoding="utf-8") as f:
        f.write(header + "\n".join(lines) + "\n")

    print(json.dumps({"version": n, "master": args.master,
                      "changedWindows": [w for w, _, _ in changed],
                      "versionsFile": path}))


def main() -> None:
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    for name in ("next", "latest", "record"):
        p = sub.add_parser(name)
        p.add_argument("--project", required=True)
        p.add_argument("--slug", required=True)
        p.add_argument("--style", required=True)
        if name == "record":
            p.add_argument("--master", required=True)
            p.add_argument("--selection")
            p.add_argument("--overrides")
            p.add_argument("--note")
    args = ap.parse_args()
    {"next": cmd_next, "latest": cmd_latest, "record": cmd_record}[args.cmd](args)


if __name__ == "__main__":
    main()
