#!/usr/bin/env python3
"""caption_words.py — refuse to caption without word timings; never fall back to segments.

The captions stage used to fall back to make_subtitles (whisper SEGMENT boundaries) when
transcript-words.json was missing — and on a dense rap one segment swallows two or three
sheet lines, so FOUR display lines sit on screen at once and a line sung at 1:08 is still
showing at 1:13. On Smooth Like That (2026-08-29) the word file had been clobbered to
zero words; the map stage's check had passed hours earlier, and the fallback would have
shipped exactly that. transcript.json, written by the same whisper run, still had 207
word timings — so the fix is to re-derive, and to refuse loudly when nothing has words.

Exit 0: `--words` holds word timings (possibly just re-derived from `--transcript`).
Exit 5: neither file has word timings — re-run --from map (whisper --word_timestamps).
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import sys


def word_count(path: str) -> int:
    try:
        doc = json.load(open(path, encoding="utf-8"))
    except (OSError, ValueError):
        return 0
    segs = doc.get("segments") if isinstance(doc, dict) else doc
    return sum(len(s.get("words") or []) for s in (segs or []) if isinstance(s, dict))


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--words", required=True, help="build/transcript-words.json (what line_subs reads)")
    ap.add_argument("--transcript", default="", help="build/transcript.json — the same whisper run; re-derive from it")
    a = ap.parse_args()
    n = word_count(a.words) if os.path.isfile(a.words) else 0
    if n > 0:
        print(f"caption_words: {n} word timings in {os.path.basename(a.words)}")
        return 0
    m = word_count(a.transcript) if a.transcript and os.path.isfile(a.transcript) else 0
    if m > 0:
        shutil.copyfile(a.transcript, a.words)
        print(f"caption_words: {os.path.basename(a.words)} had no word timings — re-derived "
              f"{m} from {os.path.basename(a.transcript)}", file=sys.stderr)
        return 0
    print(f"caption_words: NO word timings in {a.words}"
          + (f" or {a.transcript}" if a.transcript else "")
          + " — captions would fall back to segment timing (four lines on screen at once). "
          "Re-run --from map so whisper writes word timestamps.", file=sys.stderr)
    return 5


if __name__ == "__main__":
    raise SystemExit(main())
