#!/usr/bin/env python3
"""word_warp.py — retime a take's VIDEO piecewise, word by word, onto the record's word map.

WHY. A take's mouth always matches its OWN audio; what drifts is that audio against the
record. rate_fit fixes a straight-line drift (one rate), sync_shift a constant offset. On
Baby Kala Chashma's cover-reference takes (2026-09-09) the drift was neither: the model
sang the right words at its own pace — word offsets wandering from -2.5 s to +3.6 s inside
one window — so no rate and no slide could seat them, and the operator called both test
clips "totally out of sync". Every word's time in the take IS known (the clip transcript),
and so is its time in the record (the song's word map). Between two paired words the
picture is run at the ratio that lands the next word where the record sings it: a
piecewise-linear warp, each piece a mild speed change (clamped RATIO_MIN..RATIO_MAX so the
dance never freezes or blurs), the take's own audio warped with it (atempo, the same
ratios) so every gate that correlates the clip's audio against its slice still reads true.

Pairing is rate_fit.pair_words — the same in-order, consonant-skeleton pairing the driver's
rhythm judge uses — so a word the judge counted is a word this warp seats.

Usage:
  word_warp.py --clip <take.mp4> --clip-words <whisper.json of the take> --song-words <whisper.json of the song>
               --start <window startSec> --seconds <window length> --out <warped.mp4> [--song <hook.wav>]
  --song adds a second file <out stem>-check.mp4 with the RECORD laid over the warped picture, for the ear.
Prints the knots and the per-word residual (ms) after clamping; exit 4 = too few pairs to warp.
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from rate_fit import pair_words, probe_seconds, _key  # noqa: E402


def pair_words_fuzzy(song: list[dict], clip: list[dict], min_ratio: float = 0.55) -> list[tuple[float, float]]:
    """rate_fit.pair_words wants the consonant skeletons EQUAL; on a record whose whisper is
    garbled ("habiya" for "biya", "hogi parde" for "ho gaye pagal") that pairs two words of
    eighteen. In order, each song word takes the best of the next four clip words above a
    difflib ratio — the same monotone walk, a softer ear."""
    import difflib
    pairs, gi = [], 0
    for w in song:
        k = _key(w["w"])
        if len(k) < 2:
            continue
        best = None
        for j in range(gi, min(gi + 4, len(clip))):
            g = _key(clip[j]["w"])
            if not g:
                continue
            r = difflib.SequenceMatcher(None, k, g).ratio()
            if r >= min_ratio and (best is None or r > best[0]):
                best = (r, j)
        if best:
            pairs.append((float(w["t"]), float(clip[best[1]]["t"])))
            gi = best[1] + 1
    return pairs

RATIO_MIN, RATIO_MAX = 0.5, 2.0     # per piece: picture speed factor (song seconds per take second)
MIN_PAIRS = 3
FPS = 24


def whisper_words(path: str, offset: float = 0.0, window: tuple[float, float] | None = None) -> list[dict]:
    """[{w, t}] from a whisper JSON, times shifted by -offset, kept inside window (in shifted time)."""
    d = json.load(open(path, encoding="utf-8"))
    out = []
    for seg in d.get("segments", []):
        for w in seg.get("words", []):
            raw = (w.get("word") or "").strip()
            if not raw:
                continue
            t = float(w["start"]) - offset
            if window and not (window[0] - 0.1 <= t < window[1] + 0.1):
                continue
            out.append({"w": raw, "t": round(t, 3)})
    return out


def knots_from_pairs(pairs: list[tuple[float, float]], clip_len: float, seconds: float) -> list[dict]:
    """PURE. Monotone (clip_t -> song_t) knots, then the pieces between them with clamped ratios.

    Returns pieces [{c0, c1, ratio, s0 (where this piece lands), s1, wordResidualMs}] covering
    [0, clip_len]. The head before the first pair and the tail after the last run at 1.0.
    A clamped piece lands its word late/early by the residual, named per word."""
    mono = []
    last_s = last_c = -1.0
    for s, c in sorted(pairs, key=lambda p: p[1]):
        if c > last_c + 0.05 and s > last_s + 0.05:
            mono.append((c, s)); last_c, last_s = c, s
    if len(mono) < MIN_PAIRS:
        return []
    pieces, cur_s = [], None
    # head: run 1.0 from 0 to the first paired word, then jump is impossible — so the head is
    # scaled too when the first word needs to move (c0 -> s0), clamped like any piece
    c_prev, s_prev = 0.0, 0.0
    for c, s in mono:
        dc = c - c_prev
        if dc <= 0.02:
            continue
        want = (s - s_prev) / dc if cur_s is None else (s - cur_s) / dc
        ratio = min(RATIO_MAX, max(RATIO_MIN, want))
        s_land = (s_prev if cur_s is None else cur_s) + ratio * dc
        pieces.append({"c0": round(c_prev, 3), "c1": round(c, 3), "ratio": round(ratio, 4),
                       "s0": round(s_prev if cur_s is None else cur_s, 3), "s1": round(s_land, 3),
                       "wantS": round(s, 3), "wordResidualMs": int(round((s_land - s) * 1000))})
        cur_s = s_land; c_prev, s_prev = c, s
    if clip_len > c_prev + 0.02:
        pieces.append({"c0": round(c_prev, 3), "c1": round(clip_len, 3), "ratio": 1.0,
                       "s0": round(cur_s, 3), "s1": round(cur_s + (clip_len - c_prev), 3),
                       "wantS": None, "wordResidualMs": 0})
    return pieces


def render(clip: str, pieces: list[dict], seconds: float, out: str, ffmpeg: str = "ffmpeg") -> None:
    tmp = tempfile.mkdtemp(prefix="word-warp-")
    try:
        parts = []
        has_audio = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries",
                                    "stream=codec_type", "-of", "csv=p=0", clip], capture_output=True, text=True).stdout.strip() != ""
        for k, p in enumerate(pieces):
            seg = os.path.join(tmp, f"p{k:02d}.mp4")
            r = p["ratio"]
            vf = f"setpts={r:.6f}*PTS,fps={FPS}"
            cmd = [ffmpeg, "-y", "-v", "error", "-ss", f"{p['c0']:.3f}", "-to", f"{p['c1']:.3f}", "-i", clip,
                   "-vf", vf, "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p"]
            if has_audio:
                cmd += ["-af", f"atempo={1.0 / r:.6f}", "-c:a", "aac", "-b:a", "160k"]
            else:
                cmd += ["-an"]
            cmd += [seg]
            subprocess.run(cmd, check=True)
            parts.append(seg)
        lst = os.path.join(tmp, "list.txt")
        open(lst, "w").write("".join(f"file '{p}'\n" for p in parts))
        joined = os.path.join(tmp, "joined.mp4")
        subprocess.run([ffmpeg, "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", lst,
                        "-c", "copy", joined], check=True)
        # exactly the window's length: trim, or hold the last frame
        cmd = [ffmpeg, "-y", "-v", "error", "-i", joined, "-vf", f"tpad=stop_mode=clone:stop_duration={seconds:.3f},fps={FPS}",
               "-t", f"{seconds:.3f}", "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p"]
        cmd += (["-af", f"apad=whole_dur={seconds:.3f}", "-c:a", "aac", "-b:a", "160k"] if has_audio else ["-an"])
        cmd += [out]
        subprocess.run(cmd, check=True)
    finally:
        shutil.rmtree(tmp, ignore_errors=True)


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--clip", required=True)
    ap.add_argument("--clip-words", required=True, help="whisper JSON of the take (times from the clip's 0)")
    ap.add_argument("--song-words", required=True, help="whisper JSON of the song (times from the song's 0)")
    ap.add_argument("--start", type=float, required=True, help="the window's startSec on the song")
    ap.add_argument("--seconds", type=float, required=True, help="the window's render length")
    ap.add_argument("--out", required=True)
    ap.add_argument("--song", default="", help="hook.wav: also write <out>-check.mp4 with the record laid over")
    ap.add_argument("--ffmpeg", default=os.environ.get("FFMPEG_BIN", "ffmpeg"))
    a = ap.parse_args()

    clip_len = probe_seconds(a.clip)
    song = whisper_words(a.song_words, offset=a.start, window=(0.0, a.seconds))
    take = whisper_words(a.clip_words)
    pairs = pair_words(song, take)               # (song_t, clip_t)
    how = "skeleton"
    if len(pairs) < MIN_PAIRS + 2:
        fz = pair_words_fuzzy(song, take)
        if len(fz) > len(pairs):
            pairs, how = fz, "fuzzy"
    pieces = knots_from_pairs(pairs, clip_len, a.seconds)
    if not pieces:
        print(f"word_warp: only {len(pairs)} paired words — too few to warp (need {MIN_PAIRS})", file=sys.stderr)
        raise SystemExit(4)
    worst = max(abs(p["wordResidualMs"]) for p in pieces)
    print(f"word_warp: {len(pairs)} paired words ({how}) -> {len(pieces)} pieces, ratios "
          f"{min(p['ratio'] for p in pieces):.2f}–{max(p['ratio'] for p in pieces):.2f}, worst word residual {worst} ms", file=sys.stderr)
    for p in pieces:
        tail = "" if p["wantS"] is None else f"  (word wanted {p['wantS']:.2f}, {p['wordResidualMs']:+d} ms)"
        print(f"   take {p['c0']:6.2f}-{p['c1']:6.2f}  x{p['ratio']:.2f}  -> song {p['s0']:6.2f}-{p['s1']:6.2f}{tail}", file=sys.stderr)
    render(a.clip, pieces, a.seconds, a.out, a.ffmpeg)
    json.dump({"schemaVersion": 1, "clip": os.path.abspath(a.clip), "out": os.path.abspath(a.out),
               "startSec": a.start, "seconds": a.seconds, "pairs": pairs, "pieces": pieces,
               "worstWordResidualMs": worst}, open(a.out + ".json", "w", encoding="utf-8"), indent=1)
    print(f"word_warp: -> {a.out} ({probe_seconds(a.out):.2f}s)", file=sys.stderr)
    if a.song:
        chk = os.path.splitext(a.out)[0] + "-check.mp4"
        subprocess.run([a.ffmpeg, "-y", "-v", "error", "-i", a.out, "-ss", f"{a.start:.3f}", "-t", f"{a.seconds:.3f}",
                        "-i", a.song, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
                        "-shortest", chk], check=True)
        print(f"word_warp: -> {chk} (the record laid over the warped picture)", file=sys.stderr)


if __name__ == "__main__":
    main()
