#!/usr/bin/env python3
"""check_stale_outputs.py — refuse a re-render that would verify the old clip.

The source method states latest-asset discipline as advice. In this repo it is a
recorded silent failure, and it is in CLAUDE.md because it has cost real
sessions: change a scene prompt, leave the previous `outputs/scene-N.mp4` in
place, and the resumable driver SKIPS that scene. The render reports success,
the operator reviews the old clip, and everything downstream agrees.

Nothing detects this on its own. The output exists, so every existence check
passes; the file is valid, so every media probe passes. The only evidence is
that the prompt changed AFTER the clip was written, which is exactly what
`build/prompt-hashes.json` records.

So: for every scene that already has an output, compare the output file time
against the moment its prompt last changed. An output older than its prompt is
stale, and this exits non-zero with the commands to clear it.

Usage:
  check_stale_outputs.py --project <projects/slug> [--json-out <path>] [--delete]

Exit codes: 0 nothing stale · 2 the project could not be read · 3 stale outputs.
"""
from __future__ import annotations

import argparse
import datetime as _dt
import glob
import json
import os
import sys

# Where a rendered scene clip lands. Several drivers write these, and they all
# use the same scene-indexed name.
OUTPUT_PATTERNS = ("outputs/scene-{n}.mp4", "outputs/scene-{n}-*.mp4")


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


def parse_iso(value: str) -> float:
    """ISO-8601 Z timestamp -> epoch seconds."""
    try:
        return _dt.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(
            tzinfo=_dt.timezone.utc
        ).timestamp()
    except (TypeError, ValueError):
        return 0.0


def _load(path: str) -> dict:
    if not os.path.isfile(path):
        return {}
    try:
        return json.load(open(path, encoding="utf-8"))
    except json.JSONDecodeError:
        return {}


def _write(path: str, data: dict) -> None:
    tmp = f"{path}.tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=2)
        fh.write("\n")
    os.replace(tmp, path)


def orphaned_selections(project: str) -> list[dict]:
    """Scenes the drivers will SKIP because a record claims a clip that is gone.

    Deleting `outputs/scene-N.mp4` does not force a re-render. TWO records
    outlive the file and each one on its own is enough to make every resumable
    driver report that scene `skipped` for ever:

      * `scene-selection.json` still names a winning candidate; and
      * `scene-candidates.json` still holds that candidate with
        `status: "completed"` and an `outputs[].path` pointing at the deleted
        file — so clearing only the selection lets the driver re-select the
        same phantom candidate without rendering anything.

    Both were measured on a real film: after the selection alone was cleared,
    the next pool run re-selected `scene-1-take-1` and the clip still did not
    exist. Assembly then refused for a missing clip the render appeared to have
    produced.
    """
    selection = _load(os.path.join(project, "artifacts", "scene-selection.json"))
    candidates = _load(os.path.join(project, "artifacts", "scene-candidates.json"))
    orphans: dict[int, dict] = {}

    for scene in selection.get("scenes") or []:
        chosen = scene.get("selectedCandidateId")
        index = scene.get("sceneIndex")
        if chosen and index is not None and not outputs_for(project, str(index)):
            orphans[index] = {"sceneIndex": index, "selectedCandidateId": chosen,
                              "phantomCandidateIds": []}

    for scene in candidates.get("scenes") or []:
        index = scene.get("sceneIndex")
        if index is None:
            continue
        phantoms = []
        for candidate in scene.get("candidates") or []:
            if candidate.get("status") != "completed":
                continue
            paths = [o.get("path") for o in (candidate.get("outputs") or []) if o.get("path")]
            if paths and not any(os.path.isfile(p) for p in paths):
                phantoms.append(candidate.get("id"))
        if phantoms:
            entry = orphans.setdefault(
                index, {"sceneIndex": index, "selectedCandidateId": None, "phantomCandidateIds": []})
            entry["phantomCandidateIds"] = phantoms
    return [orphans[k] for k in sorted(orphans)]


def clear_selections(project: str, orphans: list[dict]) -> None:
    """Clear BOTH records, so nothing is left for a driver to reuse."""
    wanted = {o["sceneIndex"] for o in orphans}
    phantom_ids = {cid for o in orphans for cid in o["phantomCandidateIds"]}

    selection_path = os.path.join(project, "artifacts", "scene-selection.json")
    selection = _load(selection_path)
    if selection:
        for scene in selection.get("scenes") or []:
            if scene.get("sceneIndex") in wanted:
                scene["selectedCandidateId"] = None
                scene["pendingCandidateIds"] = []
                scene["rejectedCandidateIds"] = [
                    c for c in (scene.get("rejectedCandidateIds") or []) if c not in phantom_ids
                ]
        _write(selection_path, selection)

    candidates_path = os.path.join(project, "artifacts", "scene-candidates.json")
    candidates = _load(candidates_path)
    if candidates:
        for scene in candidates.get("scenes") or []:
            if scene.get("sceneIndex") not in wanted:
                continue
            # Drop the phantom outright rather than marking it failed: a record
            # that still exists is a record something can decide to reuse.
            scene["candidates"] = [
                c for c in (scene.get("candidates") or []) if c.get("id") not in phantom_ids
            ]
        _write(candidates_path, candidates)


def outputs_for(project: str, scene_index: str) -> list[str]:
    found: list[str] = []
    for pattern in OUTPUT_PATTERNS:
        found.extend(glob.glob(os.path.join(project, pattern.format(n=scene_index))))
    # A candidate directory layout keeps clips one level deeper.
    found.extend(glob.glob(os.path.join(project, "outputs", f"scene-{scene_index}", "*.mp4")))
    return sorted(set(found))


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--json-out", default="")
    ap.add_argument("--delete", action="store_true",
                    help="remove the stale outputs instead of only reporting them")
    args = ap.parse_args()

    project = os.path.abspath(args.project)
    if not os.path.isdir(project):
        die(f"project directory not found: {project}")

    hashes_path = os.path.join(project, "build", "prompt-hashes.json")
    hashes: dict = {}
    if os.path.isfile(hashes_path):
        try:
            hashes = json.load(open(hashes_path, encoding="utf-8"))
        except json.JSONDecodeError as exc:
            die(f"{hashes_path} is not valid JSON: {exc}")
    # No hashes means nothing has been composed yet, so nothing can be STALE —
    # but an orphaned selection is independent of composing and must still be
    # caught. An earlier version returned here and skipped that check entirely.

    stale: list[dict] = []
    checked = 0
    for scene_index, record in sorted(hashes.items(), key=lambda kv: int(kv[0]) if kv[0].isdigit() else 0):
        prompt_time = parse_iso((record or {}).get("updatedAt", ""))
        if not prompt_time:
            continue
        for output in outputs_for(project, scene_index):
            checked += 1
            mtime = os.path.getmtime(output)
            if mtime < prompt_time:
                stale.append({
                    "sceneIndex": scene_index,
                    "shotId": (record or {}).get("shotId", ""),
                    "output": output,
                    "outputWritten": _dt.datetime.fromtimestamp(mtime, _dt.timezone.utc)
                        .strftime("%Y-%m-%dT%H:%M:%SZ"),
                    "promptChanged": record.get("updatedAt"),
                })

    if args.json_out:
        os.makedirs(os.path.dirname(os.path.abspath(args.json_out)), exist_ok=True)
        with open(args.json_out, "w", encoding="utf-8") as fh:
            json.dump({"stale": stale, "checked": checked}, fh, indent=2)
            fh.write("\n")

    orphans = orphaned_selections(project)

    if not stale and not orphans:
        print(f"check_stale_outputs: {checked} output(s) checked, none stale", file=sys.stderr)
        print(json.dumps({"stale": [], "orphanedSelections": [], "checked": checked}))
        return

    if args.delete:
        for item in stale:
            os.remove(item["output"])
            print(f"  removed {item['output']}", file=sys.stderr)
        if orphans:
            clear_selections(project, orphans)
            for orphan in orphans:
                print(f"  cleared scene {orphan['sceneIndex']}: selection "
                      f"{orphan['selectedCandidateId'] or '-'}, phantom candidates "
                      f"{', '.join(orphan['phantomCandidateIds']) or '-'}", file=sys.stderr)
        print(f"check_stale_outputs: cleared {len(stale)} stale output(s) and "
              f"{len(orphans)} orphaned selection(s); re-render is now safe", file=sys.stderr)
        print(json.dumps({"stale": stale, "orphanedSelections": orphans,
                          "checked": checked, "deleted": True}))
        return

    if stale:
        print(f"\ncheck_stale_outputs: {len(stale)} output(s) are older than the prompt that "
              f"describes them:\n", file=sys.stderr)
        for item in stale:
            print(f"  {item['shotId'] or 'scene ' + item['sceneIndex']}: {item['output']}", file=sys.stderr)
            print(f"      clip written {item['outputWritten']}, prompt changed {item['promptChanged']}",
                  file=sys.stderr)
        print("\n  Left in place, the resumable driver SKIPS these scenes and you review the old clip.",
              file=sys.stderr)

    if orphans:
        print(f"\ncheck_stale_outputs: {len(orphans)} scene(s) still have a WINNING candidate "
              f"whose clip is gone:\n", file=sys.stderr)
        for orphan in orphans:
            bits = []
            if orphan["selectedCandidateId"]:
                bits.append(f"selected {orphan['selectedCandidateId']}")
            if orphan["phantomCandidateIds"]:
                bits.append(f"candidate(s) {', '.join(orphan['phantomCandidateIds'])} recorded completed")
            print(f"  scene {orphan['sceneIndex']}: {'; '.join(bits)}, "
                  f"but outputs/scene-{orphan['sceneIndex']}.mp4 does not exist", file=sys.stderr)
        print(
            "\n  Deleting a clip is NOT enough to force a re-render, and clearing the selection is\n"
            "  not enough either. TWO records outlive the file: the selection names a winner, and\n"
            "  the candidate still records status:completed with a path to the deleted clip — so a\n"
            "  driver just re-selects the same phantom and renders nothing. Every resumable driver\n"
            "  then reports that scene 'skipped', and assembly refuses for a clip the render\n"
            "  appeared to produce. --delete clears both.",
            file=sys.stderr,
        )

    print(f"\n  Clear both:\n\n    check_stale_outputs.py --project {args.project} --delete\n",
          file=sys.stderr)
    print(json.dumps({"stale": stale, "orphanedSelections": orphans, "checked": checked}))
    raise SystemExit(3)


if __name__ == "__main__":
    main()
