#!/usr/bin/env python3
"""rate_fit.py — a take that sings the right words at a UNIFORMLY wrong speed is retimed,
not redrawn.

Repairs require full-content clip transcripts and song-bound word timings. Every edit
keeps an immutable original and a content-keyed rate candidate. Rate selection is
PROVISIONAL: sync_shift either verifies the combined correction or restores the prior
selection. These remain two passes because word fitting estimates tempo while audio
profiling independently verifies placement. Repeating an identical edit reuses bytes.

THE FINDING (w11 A/B, 2026-08-29, nine renders). The free-lane Seedance sang a slow-jam
line 9–12% slower than the track on EVERY take — stem or mix slice, timestamp list or one
clock, locked shot, one line per window, slowness words scrubbed: fitted rates 1.089,
1.095, 1.112, 1.120. The word onsets lie on a straight line against the song's, they are
not scattered; a slide moves every word by the same amount and cannot fix a slope, and no
prompt change moved the slope. Running the video at the measured rate did: the operator
listened to the retimed take with the song under it — "yes this is better".

WHAT THIS DOES, per synced window of a selection: pair the clip transcript's words with
the song's words for that window in order, reject ambiguous or incomplete phrase matches,
fit take_t = a + rate * song_t with a robust median slope, and when the fit is
CLEAN and the rate is MATERIAL —
    pairs >= MIN_PAIRS, |rate - 1| >= RATE_MIN, |rate - 1| <= RATE_MAX, residual <= RESIDUAL_MAX_MS
— write a retimed copy: video `setpts=PTS/rate` (tail padded by cloning the last frame back
to the window's length), audio `atempo=rate` (so the gates that correlate the clip's own
audio against the song still read true), and point the selection at it. The constant `a`
is left for sync_shift, which runs next and slides it.

Runs in the `slide` stage BEFORE sync_shift. Never touches a lipSyncExempt window, never
touches a window whose fit is uncertain (verify it) or tiny (a slide's job).

TWO MORE GUARDS (film #3, 2026-09-07). Grid w12 fitted a clean-looking rate (1.136, 9
pairs) and got retimed — pushing a take that was already PASSING sync (corr 0.74 @
-375ms, before slide) below the master gate (0.22). Neither existing guard caught it:
9 pairs clears MIN_PAIRS, and the fit was genuinely straight. Two more checks now run:

  * ALREADY ON THE BAR. Pass `--sync-report build/sync-report-<style>.json` (check_sync's
    rows) and a window whose measured correlation already clears SYNC_MIN is left alone,
    whatever the fit says — a rate fit only has something to offer a window that is NOT
    yet on its bar.
  * A MIS-PAIRING IS NOT A SLOPE. `pair_words` matches in order and greedily consumes the
    clip's word list; w12's 9-of-29 pairing was words matched to the wrong neighbours, not
    a real tempo. `decide()` now needs the majority of a window's own song words paired
    (MIN_PAIR_FRACTION) before it will trust a fit at all.
"""
from __future__ import annotations

import argparse
import copy
import json
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))   # a script loaded by path (tests) still finds its siblings
import raplib  # noqa: E402
import os
import re
import subprocess
import sys
import statistics

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sync_evidence import file_hash, is_current, number, evidence
from timing_edits import capture_source, source_problem, output_current, edit_id, apply_window, persist, video_seconds, restore_previous
from sync_profile import clip_resolver  # noqa: E402
from check_sync import SYNC_MIN  # noqa: E402 — the same bar check_sync gates on (RAP_BAR=keep lowers it)

MIN_PAIRS = 5
# A MIS-PAIRING IS NOT A SLOPE. `pair_words` matches in order, greedily consuming the
# clip's word list, so a handful of accidental matches on a mostly-wrong take can still
# fit a straight line: w12 paired 9 of its 29 song words and fitted a clean-looking 1.136
# (film #3, 2026-09-07). Below this fraction of the window's own words, the fit is not
# trusted no matter how straight it looks.
MIN_PAIR_FRACTION = 0.6
RATE_MIN = 0.03           # below this a slide is enough
# Beyond RATE_MAX the picture is another take's problem (cover). The pack can raise it
# (RAP_RATE_MAX): the New Era song came back ~35% slow on EVERY window, hook and
# rapped verse alike (rates 1.34-1.36, straight lines), and a film where every window
# is covered has no singer in it — the operator judges the sped-up motion by eye.
RATE_MAX = float(os.environ.get("RAP_RATE_MAX") or 0.25)
RESIDUAL_MAX_MS = 200     # a straight line, not a wander


def _key(w: str) -> str:
    """Latin letters only — a Devanagari word is transliterated first. Stripping to
    [a-z] turned every Hindi word into "" and rate_fit paired 0 words on a whole film
    (film #3, 2026-09-06: eleven windows "too few paired words (0)"), so the two
    windows that sang 3-6% fast were covered instead of retimed. Same seam as
    line_subs._latin and vocal_brief."""
    if re.search(r"[\u0900-\u097f]", w):
        from vocal_brief import norm_latin, transliterate
        w = norm_latin(transliterate(w))
    return re.sub(r"[^a-z0-9']", "", w.lower())


def _skeleton(w: str) -> str:
    """consonant skeleton, doubled letters collapsed — whisper hears "citty" for "city"."""
    return re.sub(r"(.)\1+", r"\1", re.sub(r"[aeiou]", "", _key(w)))


def pair_words(song: list[dict], clip: list[dict]) -> list[tuple[float, float]]:
    """Monotonic phrase alignment, preferring exact matches and balanced coverage.

    A greedy first match can consume a repeated word from the wrong phrase and strand
    the rest of the line. Dynamic programming chooses the best complete sequence.
    Relative positions break equal-score ties; timing is still judged by the fit.
    """
    wanted = [(w, _key(w["w"])) for w in song if number(w.get("t")) is not None]
    got = [(w, _key(w["w"])) for w in clip if number(w.get("t")) is not None]
    n, m = len(wanted), len(got)
    scores = [[(0, 0, 0.0) for _ in range(m + 1)] for _ in range(n + 1)]
    moves = [[None for _ in range(m + 1)] for _ in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            score, move = max((scores[i - 1][j], "song"), (scores[i][j - 1], "clip"))
            a, b = wanted[i - 1][1], got[j - 1][1]
            if a and b and (a == b or (len(a) > 3 and _skeleton(a) == _skeleton(b))):
                prior = scores[i - 1][j - 1]
                candidate = (prior[0] + 1, prior[1] + int(a == b),
                             prior[2] - abs((i - 1) / max(n - 1, 1) - (j - 1) / max(m - 1, 1)))
                if candidate >= score:
                    score, move = candidate, "match"
            scores[i][j], moves[i][j] = score, move
    pairs, i, j = [], n, m
    while i and j:
        move = moves[i][j]
        if move == "match":
            pairs.append((float(wanted[i - 1][0]["t"]), float(got[j - 1][0]["t"])))
            i, j = i - 1, j - 1
        elif move == "song":
            i -= 1
        else:
            j -= 1
    return list(reversed(pairs))


def alignment_ambiguous(want, got):
    """Does equally strong lexical evidence allow different word correspondences?"""
    a, b = [_key(w["w"]) for w in want], [_key(w["w"]) for w in got]
    n, m = len(a), len(b)
    def match(i, j):
        return bool(a[i] and b[j] and (a[i] == b[j] or (len(a[i]) > 3 and _skeleton(a[i]) == _skeleton(b[j]))))
    pre = [[(0, 0) for _ in range(m + 1)] for _ in range(n + 1)]
    post = [[(0, 0) for _ in range(m + 1)] for _ in range(n + 1)]
    for i in range(n):
        for j in range(m):
            options = [pre[i][j + 1], pre[i + 1][j]]
            if match(i, j):
                options.append((pre[i][j][0] + 1, pre[i][j][1] + int(a[i] == b[j])))
            pre[i + 1][j + 1] = max(options)
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            options = [post[i + 1][j], post[i][j + 1]]
            if match(i, j):
                options.append((post[i + 1][j + 1][0] + 1, post[i + 1][j + 1][1] + int(a[i] == b[j])))
            post[i][j] = max(options)
    song_choices, clip_choices = {}, {}
    for i in range(n):
        for j in range(m):
            if match(i, j) and (pre[i][j][0] + 1 + post[i + 1][j + 1][0],
                               pre[i][j][1] + int(a[i] == b[j]) + post[i + 1][j + 1][1]) == pre[n][m]:
                song_choices.setdefault(i, set()).add(j)
                clip_choices.setdefault(j, set()).add(i)
    return any(len(indices) > 1 for indices in [*song_choices.values(), *clip_choices.values()])


def phrase_fit(want, got):
    want = [w for w in want if number(w.get("t")) is not None]
    got = [w for w in got if number(w.get("t")) is not None]
    pairs = pair_words(want, got)
    result = fit(pairs)
    times = [float(w["t"]) for w in want]
    whole = max(times) - min(times) if len(times) > 1 else 0
    coverage = (max(p[0] for p in pairs) - min(p[0] for p in pairs)) / whole if pairs and whole > 0 else 0
    result["spanCoverage"] = round(coverage, 4)
    result["endpointsMatched"] = bool(pairs and times and min(p[0] for p in pairs) == min(times)
                                      and max(p[0] for p in pairs) == max(times))
    result["ambiguousAlignment"] = alignment_ambiguous(want, got)
    return result


def fit(pairs: list[tuple[float, float]]) -> dict:
    """Least squares take_t = a + rate*song_t; residual = RMS in ms."""
    n = len(pairs)
    if n < 2:
        return {"pairs": n, "rate": None, "offsetMs": None, "residualMs": None}
    xs, ys = [p[0] for p in pairs], [p[1] for p in pairs]
    mx, my = sum(xs) / n, sum(ys) / n
    sxx = sum((x - mx) ** 2 for x in xs)
    if sxx <= 1e-9:
        return {"pairs": n, "rate": None, "offsetMs": None, "residualMs": None}
    # Median pairwise slope prevents one late endpoint from inventing a global rate.
    def slope(points):
        candidates = [(y2 - y1) / (x2 - x1) for i, (x1, y1) in enumerate(points)
                      for x2, y2 in points[i + 1:] if x2 > x1 + 1e-9]
        return statistics.median(candidates) if candidates else None
    rate = slope(pairs)
    if rate is None:
        return {"pairs": n, "rate": None, "offsetMs": None, "residualMs": None}
    a = statistics.median(y - rate * x for x, y in pairs)
    residuals = [y - (a + rate * x) for x, y in pairs]
    res = (sum(r ** 2 for r in residuals) / n) ** 0.5
    local_change = None
    if n >= 8:
        first, last = slope(pairs[:n // 2]), slope(pairs[n // 2:])
        if first is not None and last is not None:
            local_change = abs(first - last)
    return {"pairs": n, "rate": round(rate, 4), "offsetMs": int(round(a * 1000)),
            "residualMs": int(round(res * 1000)), "rateChange": round(local_change, 4) if local_change is not None else None}


def decide(f: dict, total_words: int | None = None) -> tuple[bool, str]:
    if f["rate"] is None or f["pairs"] < MIN_PAIRS:
        return False, f"too few paired words ({f['pairs']}) to fit a rate"
    # A MIS-PAIRING IS NOT A SLOPE (see MIN_PAIR_FRACTION above). `total_words` is the
    # song's own word count for this window; omit it (None) to skip the check — callers
    # that only have the fit, not the window, keep today's behaviour.
    if total_words and f["pairs"] < MIN_PAIR_FRACTION * total_words:
        return False, (f"only {f['pairs']} of {total_words} song words paired "
                       f"({f['pairs'] / total_words:.0%}) — a mis-pairing, not a slope")
    if f.get("ambiguousAlignment"):
        return False, "ambiguous repeated-word alignment — verify the phrase before fitting tempo"
    if not f.get("endpointsMatched", True) or f.get("spanCoverage", 1.0) < 0.8:
        return False, "insufficient full-span evidence — matched words do not cover the sung beginning and end"
    if f.get("rateChange") is not None and f["rateChange"] > 0.15:
        return False, "tempo changes within the phrase — a single rate cannot repair it"
    # THE RESIDUAL LIVES IN THE TAKE'S TIME BASE, WHICH IS STRETCHED BY `rate`. A fixed
    # millisecond bar is therefore stricter the slower the take sings: the New Era desk
    # verse fitted 1.348 with residual 218 ms and read as a WANDER, yet retimed x0.74 it
    # measured 1.005 / -220 ms and the operator watched it against the track and called
    # it perfect (2026-08-30). Scaling the bar by the rate keeps the same tightness per
    # unit of the take's own time; a real rubato (residual 373 ms at 1.363, the nineties
    # w02 line) still fails.
    bar = RESIDUAL_MAX_MS * max(1.0, f["rate"])
    if f["residualMs"] > bar:
        return False, (f"not a straight line (residual {f['residualMs']}ms past "
                       f"{bar:.0f}ms at {f['rate']:.2f}x) — a wander, cover it")
    dev = abs(f["rate"] - 1.0)
    if dev < RATE_MIN:
        return False, f"rate {f['rate']:.3f} is within {RATE_MIN:.0%} — a slide's job"
    if dev > RATE_MAX:
        return False, f"rate {f['rate']:.3f} is past {RATE_MAX:.0%} — retiming would look wrong, cover it"
    return True, f"rate {f['rate']:.3f} (residual {f['residualMs']}ms over {f['pairs']} words)"


def probe_seconds(path: str) -> float:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except ValueError:
        return 0.0


def retimable(want: list[dict], got: list[dict]) -> dict | None:
    """The fit, when this take is a straight line we can retime; else None.

    THE ONE HOME for that question. Three gates asked it separately and two of them
    got it wrong: a take singing every word at 1.1-1.35x cannot correlate with its
    slice — which is exactly what makes it retimable — and both the per-draw judge and
    `check_sync` refused those takes as "moving to different words" (New Era,
    2026-08-30: 4 draws parked, then the whole cut refused).
    """
    try:
        f = phrase_fit(want, got)
        ok, _why = decide(f, total_words=len(want))
    except Exception:                     # noqa: BLE001 — a probe never kills a gate
        return None
    return f if ok else None


def load_sync_report(path: str) -> dict[int, dict]:
    """Load segment rows; callers validate content and intended reference before use."""
    if not path or not os.path.isfile(path):
        return {}
    try:
        rows = json.load(open(path, encoding="utf-8"))
    except Exception:                     # noqa: BLE001 — an unreadable report never kills the stage
        return {}
    out: dict[int, dict] = {}
    for r in rows if isinstance(rows, list) else []:
        if not isinstance(r, dict) or r.get("segment") is None or "corr" not in r:
            continue
        try:
            if number(r["corr"]) is not None:
                out[int(r["segment"])] = r
        except (TypeError, ValueError):
            continue
    return out


def retime(src: str, dst: str, rate: float, ffmpeg: str, fps: int, has_audio: bool) -> None:
    if os.path.abspath(src) == os.path.abspath(dst):
        raise ValueError("retime requires an immutable input distinct from its output")
    dur = probe_seconds(src)
    pad = max(0.0, dur - dur / rate) + 0.25
    vf = f"[0:v]setpts=PTS/{rate:.5f},tpad=stop_mode=clone:stop_duration={pad:.3f}[v]"
    cmd = [ffmpeg, "-y", "-v", "error", "-nostdin", "-i", src]
    if has_audio:
        cmd += ["-filter_complex", vf + f";[0:a]atempo={rate:.5f},apad[a]", "-map", "[v]", "-map", "[a]",
                "-c:a", "aac", "-b:a", "192k"]
    else:
        cmd += ["-filter_complex", vf, "-map", "[v]"]
    cmd += ["-t", f"{dur:.3f}", "-r", str(fps), "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", dst]
    p = subprocess.run(cmd, capture_output=True, text=True)
    if p.returncode:
        raise SystemExit(f"rate_fit: ffmpeg failed for {dst}:\n{p.stderr[-600:]}")




def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--selection", required=True)
    ap.add_argument("--store", required=True, help="artifacts/clip-transcripts.json (words per clip)")
    ap.add_argument("--song-words", required=True, help="build/song-words.json ({t,w} absolute)")
    ap.add_argument("--song", default="", help="intended reference audio; otherwise use the transcript store song path")
    ap.add_argument("--stage", default="", help="fallback dir for performerClip -> file")
    ap.add_argument("--out-dir", required=True, help="where retimed clips are written")
    ap.add_argument("--out-selection", default="", help="rewrite the selection onto the retimed clips")
    ap.add_argument("--json", default="", help="rate-report.json")
    ap.add_argument("--sync-report", default="",
                    help="check_sync's --json-out (build/sync-report-<style>.json). A window "
                         "whose measured correlation already clears the sync bar is left alone "
                         "— retiming a take that is already ON its bar only moves it off (grid "
                         "w12, film #3, 2026-09-07: a passing 0.74 fitted a clean-looking 1.136 "
                         "and got pushed below the master gate). Omit to skip this guard.")
    ap.add_argument("--fps", type=int, default=24)
    ap.add_argument("--ffmpeg", default=os.environ.get("FFMPEG_BIN", "ffmpeg"))
    a = ap.parse_args()

    sel = json.load(open(a.selection, encoding="utf-8"))
    store = json.load(open(a.store, encoding="utf-8"))
    sw = json.load(open(a.song_words, encoding="utf-8"))
    song_words = sw.get("words") if isinstance(sw, dict) else sw
    resolve = clip_resolver(sel, a.stage)
    sync_corr = load_sync_report(a.sync_report)
    os.makedirs(a.out_dir, exist_ok=True)
    rows = []
    by_id = {c["id"]: c for c in sel.get("clips", [])}
    for idx, window in enumerate(sel.get("vocalMap", [])):
        record, edit, temporary = None, {}, None
        try:
            perf = window.get("performerClip")
            if not perf or (window.get("lipSyncExempt") and window.get("lipSyncExemptBy") != "cover") \
                    or window.get("type") not in (None, "rap", "sung", "synced"):
                continue
            selected = resolve(perf)
            record = by_id.get(perf)
            if not selected or record is None:
                if record:
                    restore_previous(record, window, record.get("rejectedTimingEdit") or record.get("timingEdit") or {})
                rows.append({"clip": perf, "action": "verify", "why": "no selected file"})
                continue
            active_edit = record.get("timingEdit") or {}
            edit = record.get("rejectedTimingEdit") or active_edit
            problem = source_problem(edit) if edit else None
            if problem:
                restore_previous(record, window, edit)
                rows.append({"clip": perf, "action": "verify", "why": problem})
                continue
            origin = (edit.get("source") or {}).get("originPath", selected)
            source = (edit.get("source") or {}).get("path", selected)
            digest = file_hash(source)
            start, end = float(window["start"]), float(window["end"])
            transcript = next((entry for entry in (store.get("clips") or {}).values()
                               if entry.get("sourceSha256") == digest), None)
            if transcript is None:
                restore_previous(record, window, edit)
                rows.append({"clip": perf, "action": "verify", "why": "missing or stale full-content transcript; re-run transcribe"})
                print(f"  {perf}: verify — missing or stale full-content transcript; re-run transcribe")
                continue
            song_entry = store.get("song") or {}
            intended_song = a.song or song_entry.get("path")
            song_hash = file_hash(intended_song)
            if not song_hash or not isinstance(sw, dict) or sw.get("sourceSha256") != song_hash:
                restore_previous(record, window, edit)
                rows.append({"clip": perf, "action": "verify", "why": "song word timings are not bound to the current reference; rebuild song-words"})
                continue
            if song_entry.get("sourceSha256") and file_hash(song_entry.get("path")) != song_entry["sourceSha256"]:
                restore_previous(record, window, edit)
                rows.append({"clip": perf, "action": "verify", "why": "song changed since transcription"})
                continue
            words = transcript.get("words") or []
            in_window = [{"t": float(w["t"]) - start, "w": w["w"]} for w in song_words if start <= float(w["t"]) < end]
            fitted = phrase_fit(in_window, words)
            report = sync_corr.get(idx)
            head = float((edit.get("source") or {}).get("headSec", window.get("headSec") or 0))
            if report and is_current(report, source, start, end, intended_song, head_sec=head) and float(report["evidence"].get("headSec") or 0) == head \
                    and report["corr"] >= SYNC_MIN:
                why = f"already on the bar (corr {report['corr']:.2f}) — a rate fit would move it"
                rows.append({"clip": perf, **fitted, "action": "left", "why": why})
                print(f"  {perf}: left — {why}")
                continue
            ok, why = decide(fitted, total_words=len(in_window))
            row = {"clip": perf, "startSec": start, **fitted, "why": why,
                   "evidence": evidence(source, intended_song, start, end, head)}
            if not ok:
                row["action"] = "verify" if (not fitted.get("endpointsMatched", True) or fitted.get("ambiguousAlignment") or (fitted.get("rateChange") or 0) > 0.15) else "left"
                rows.append(row)
                print(f"  {perf}: {row['action']} — {why}")
                continue
            rate = float(fitted["rate"])
            request = {"version": 2, "sourceSha256": digest, "rate": rate, "start": start, "end": end,
                       "songWordsSha256": file_hash(a.song_words), "songSha256": song_hash, "transcript": edit_id(words), "fps": a.fps,
                       "headSec": head, "rateMax": RATE_MAX}
            key = edit_id(request)
            previous_rate = edit.get("rate") or {}
            if previous_rate.get("id") == key and output_current(previous_rate):
                # An accepted shift may already follow this exact rate. Leave it selected.
                if not output_current(edit.get("shift")) or record["path"] != edit["shift"]["path"]:
                    record["path"] = previous_rate["path"]
                    record["durationSec"] = previous_rate["durationSec"]
                    apply_window(window, previous_rate)
                record["timingEdit"] = edit
                row.update(action="reused", path=record["path"], editId=key, provisional=not previous_rate.get("verified"),
                           evidence=evidence(record["path"], intended_song, start, end, float(window.get("headSec") or 0)))
                rows.append(row)
                print(f"  {perf}: reused existing rate edit")
                continue
            if not edit:
                source_duration, _ = video_seconds(source)
                if not source_duration:
                    rows.append({"clip": perf, "action": "verify", "why": "source video coverage cannot be measured"})
                    continue
                edit = capture_source(source, window, a.out_dir, source_duration)
                source = edit["source"]["path"]
            # Rate is provisional until the following shift stage verifies timing. It can
            # restore this previous selection if the combined repair cannot be verified.
            prior_edit = copy.deepcopy(active_edit)
            prior_edit.pop("previousSelection", None)
            saved_previous = edit.get("previousSelection") if previous_rate and not previous_rate.get("verified") else None
            edit["previousSelection"] = saved_previous or {"path": record["path"], "sha256": file_hash(record["path"]),
                                         "durationSec": record.get("durationSec"), "timingEdit": prior_edit or None,
                                         "window": {k: window.get(k) for k in ("headSec", "tailSec", "realEndSec", "syntheticSpans")}}
            dst = os.path.join(a.out_dir, f"{perf}-{key[:16]}.mp4")
            temporary = dst + ".candidate.mp4"
            has_audio = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries",
                                        "stream=codec_type", "-of", "csv=p=0", source], capture_output=True, text=True).stdout.strip() != ""
            retime(source, temporary, rate, a.ffmpeg, a.fps, has_audio)
            output_duration = probe_seconds(temporary)
            if output_duration <= 0:
                os.remove(temporary)
                rows.append({"clip": perf, "action": "verify", "why": "rate candidate has no readable duration"})
                continue
            os.replace(temporary, dst)
            real_end = min(output_duration, edit["source"]["durationSec"] / rate)
            new_head = edit["source"]["headSec"] / rate
            operation = {**request, "id": key, "path": os.path.abspath(dst), "outputSha256": file_hash(dst),
                         "durationSec": output_duration, "headSec": new_head,
                         "tailSec": max(0, real_end - new_head - (end - start)), "realEndSec": real_end,
                         "syntheticSpans": [[real_end, output_duration]] if output_duration > real_end else [],
                         "verified": False}
            edit["rate"] = operation
            edit.pop("shift", None)
            record.pop("rejectedTimingEdit", None)
            record.update(path=operation["path"], durationSec=output_duration, timingEdit=edit)
            apply_window(window, operation)
            row.update(action="retimed", path=operation["path"], editId=key, provisional=True,
                       realEndSec=real_end, syntheticSpans=operation["syntheticSpans"],
                       evidence=evidence(operation["path"], intended_song, start, end, new_head))
            rows.append(row)
            print(f"  {perf}: RETIMED x{1 / rate:.3f} — {why}; pending the slide verification")
        except (Exception, SystemExit) as error:
            if temporary and os.path.isfile(temporary):
                os.remove(temporary)
            if record:
                restore_previous(record, window, edit)
            rows.append({"clip": window.get("performerClip"), "action": "verify",
                         "why": f"rate candidate could not be created: {str(error)[:200]}"})
    intended_song = a.song or (store.get("song") or {}).get("path")
    windows_by_id = {w.get("performerClip"): w for w in sel.get("vocalMap", [])}
    for row in rows:
        c, w = by_id.get(row["clip"]), windows_by_id.get(row["clip"])
        if "evidence" not in row and c and w and intended_song:
            row["evidence"] = evidence(c["path"], intended_song, w["start"], w["end"], float(w.get("headSec") or 0))
    if a.out_selection:
        persist(a.out_selection, sel)
    if a.json:
        json.dump({"schemaVersion": 1, "windows": rows,
                   "thresholds": {"minPairs": MIN_PAIRS, "minPairFraction": MIN_PAIR_FRACTION,
                                  "rateMin": RATE_MIN, "rateMax": RATE_MAX, "residualMaxMs": RESIDUAL_MAX_MS,
                                  "syncMin": SYNC_MIN}},
                  open(a.json, "w", encoding="utf-8"), indent=1)
    n = sum(1 for r in rows if r.get("action") == "retimed")
    print(f"rate_fit: {n} window(s) retimed, {len(rows) - n} left")
    return 0


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