#!/usr/bin/env python3
"""swap_words.py — word timings for the FILM's voice under AUDIO_MODE=vocal-swap.

The captions are timed from a word-level transcript of the record (transcript-words.json,
whisper's JSON). Under vocal-swap the film's voice inside every synced window is the
TAKE's (vocal_swap.py), and a take phrases the line its own way — a stretched pause moves
a word up to a second off the record's timing, so a caption timed from the record sits
on the wrong mouth. This writes the same whisper-shaped JSON with the record's words
outside the swap spans and the take's words (from the clip-transcripts store, primed
whisper of the take's own audio) inside them, mapped into film time:

    t_film = span.start + (t_clip - span.clipOffset)

A take word has only an onset in the store; its end is the next word's onset (capped)
or a short default. line_subs reads segments[].words[{word,start,end}]; that is what
comes out.

Usage:
  swap_words.py --record build/transcript-words.json --swap build/vocal-swap-<sid>.json \
                --clip-transcripts artifacts/clip-transcripts.json --out build/transcript-words-vocalswap-<sid>.json
"""
from __future__ import annotations

import argparse
import json
import os
import sys

WORD_MAX_S = 0.6     # a take word's end: the next onset, but never longer than this
WORD_LAST_S = 0.35   # the last word of a span, with no next onset
HEAD_GRACE_S = 0.3   # a first word the take starts just before the head pad ends is still the line's first word


def swap_words(record: dict, spans: list[dict], clip_words: dict) -> dict:
    """Pure. record = whisper JSON of the song; spans = vocal-swap segments
    [{start,end,clip,clipOffset}]; clip_words = clip path -> [{t,w}] (clip time).
    Returns whisper-shaped JSON: one segment per record segment (its words outside every
    span) plus one segment per span (the take's words inside it)."""
    spans = sorted(spans, key=lambda s: float(s["start"]))

    def in_span(t: float) -> bool:
        return any(float(s["start"]) <= t < float(s["end"]) for s in spans)

    out_segments = []
    for seg in record.get("segments") or []:
        kept = [w for w in (seg.get("words") or []) if not in_span(float(w["start"]))]
        if kept:
            out_segments.append({"start": kept[0]["start"], "end": kept[-1]["end"],
                                 "text": " ".join(str(w.get("word", "")).strip() for w in kept), "words": kept})
    swapped = 0
    for s in spans:
        a, b, off = float(s["start"]), float(s["end"]), float(s.get("clipOffset") or 0.0)
        words = clip_words.get(s.get("clip") or "") or clip_words.get(os.path.basename(s.get("clip") or "")) or []
        # A take often sings its first word a hair before the head pad ends (the model
        # leads in early): keep an onset up to HEAD_GRACE_S before the offset, clamped to
        # the span's start — w02's "Philosophy" and w03's "Foam" sat 0.1-0.2 s early.
        onsets = [(float(w["t"]), str(w["w"])) for w in words if off - HEAD_GRACE_S <= float(w["t"]) < off + (b - a)]
        # Whisper pins a clip's FIRST word to t=0.0 (the segment start), not to its real
        # onset inside the head pad — every take in the store reads 0.0 for its first
        # word. When that first word is missing from the span and the clip's next onset
        # lands inside it, the first word IS the line's first word: put it at the span
        # start (its end = the next onset).
        if words and float(words[0]["t"]) < off - HEAD_GRACE_S and (len(words) == 1 or off - HEAD_GRACE_S <= float(words[1]["t"]) < off + (b - a)):
            onsets.insert(0, (off, str(words[0]["w"])))
        rows = []
        for i, (t, w) in enumerate(onsets):
            start = round(max(a, a + (t - off)), 3)
            nxt = onsets[i + 1][0] if i + 1 < len(onsets) else None
            end = min(start + WORD_MAX_S, a + (nxt - off)) if nxt is not None else start + WORD_LAST_S
            rows.append({"word": " " + w, "start": start, "end": round(max(start, min(end, b)), 3)})
        if rows:
            out_segments.append({"start": rows[0]["start"], "end": rows[-1]["end"],
                                 "text": " ".join(r["word"].strip() for r in rows), "words": rows, "vocalSwap": s.get("window")})
            swapped += len(rows)
    out_segments.sort(key=lambda g: float(g["start"]))
    return {"text": " ".join(g["text"] for g in out_segments), "language": record.get("language", "en"),
            "segments": out_segments, "vocalSwap": {"spans": len(spans), "takeWords": swapped}}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--record", required=True, help="build/transcript-words.json (whisper JSON of the song)")
    ap.add_argument("--swap", required=True, help="build/vocal-swap-<sid>.json (the audio-swap stage's record)")
    ap.add_argument("--clip-transcripts", required=True, help="artifacts/clip-transcripts.json")
    ap.add_argument("--out", required=True)
    ap.add_argument("--extra-words", default="", help="path -> [{t,w}] for fitted copies (fit_takes' words.json)")
    a = ap.parse_args()
    record = json.load(open(a.record, encoding="utf-8"))
    spans = json.load(open(a.swap, encoding="utf-8")).get("segments") or []
    store = json.load(open(a.clip_transcripts, encoding="utf-8"))
    clip_words = {}
    for entry in (store.get("clips") or {}).values():
        if isinstance(entry, dict) and entry.get("path"):
            clip_words[entry["path"]] = entry.get("words") or []
            clip_words[os.path.basename(entry["path"])] = entry.get("words") or []
    if a.extra_words and os.path.isfile(a.extra_words):
        for pth, ws in json.load(open(a.extra_words, encoding="utf-8")).items():
            clip_words[pth] = ws
            clip_words[os.path.basename(pth)] = ws
    doc = swap_words(record, spans, clip_words)
    missing = [s.get("window") for s in spans if not (clip_words.get(s.get("clip") or "") or clip_words.get(os.path.basename(s.get("clip") or "")))]
    json.dump(doc, open(a.out, "w", encoding="utf-8"), indent=1)
    print(f"swap_words: {doc['vocalSwap']['takeWords']} take word(s) over {len(spans)} span(s) -> {a.out}"
          + (f" · NO transcript for: {', '.join(map(str, missing))} (record words kept there)" if missing else ""), file=sys.stderr)
    return 0


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