#!/usr/bin/env python3
"""vocal_swap.py — the film's audio follows the picture: the record's beat, the take's voice.

THE OPERATOR'S CALL (2026-08-31, New Era): "use the video it has created … the audio on
the video is not too bad." A lip-sync model's mouth always matches its OWN voice; it only
drifts against the record it was asked to follow. So instead of bending the picture to the
record (slide, retime, cover) the film's audio is rebuilt from two stems:

    the ORIGINAL song's instrumental (Demucs no_vocals)  — continuous, the whole film
  + the TAKE's vocal (Demucs vocals of the take's own audio) wherever a synced window's
    performer sings, level-matched to the record's vocal, cross-faded at both edges
  + the ORIGINAL song's vocal everywhere else

The beat never changes character; only who is singing swaps, and sync is exact by
construction. Costs: the vocal timbre shifts a little window to window (each take is a
re-performance), and the film commits to the model's phrasing over the record's.

Reads the selection (which clip sits on which window, after slide/cover) and the plan
(sung spans per window). Writes one full-length WAV and remuxes it onto the master.

Usage:
  vocal_swap.py --plan build/plan.json --selection build/selection-<sid>.json \
                --song build/hook.wav --stems build/stems --master <master.mp4> \
                --out build/audio-vocalswap-<sid>.wav [--json build/vocal-swap-<sid>.json] \
                [--fade 0.15] [--keep-original]
"""
from __future__ import annotations

import argparse
import hashlib
import json
import re
import os
import shutil
import subprocess
import sys
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
import raplib  # noqa: E402

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

FADE_S = 0.15


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 lufs(path: str, t0: float = 0.0, dur: float | None = None) -> float | None:
    cmd = ["ffmpeg", "-v", "info", "-ss", f"{t0:.3f}"] + (["-t", f"{dur:.3f}"] if dur else []) \
        + ["-i", path, "-af", "loudnorm=print_format=summary", "-f", "null", "-"]
    r = subprocess.run(cmd, capture_output=True, text=True)
    for line in r.stderr.splitlines():
        if "Input Integrated" in line:
            try:
                return float(line.split(":")[1].split()[0])
            except (IndexError, ValueError):
                return None
    return None


def demucs_vocal(python: str, media: str, out_dir: str) -> str | None:
    """The take's vocal via the singer-diarize venv's Demucs; cached by the media's stem."""
    # Keyed by CONTENT (path + size + mtime): a joined/trimmed copy shares its source's
    # basename, and a cache keyed by name alone would hand back the untrimmed voice.
    st = os.stat(media)
    stem = os.path.splitext(os.path.basename(media))[0] + "-" + hashlib.md5(f"{media}|{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:8]
    want = os.path.join(out_dir, "htdemucs", stem, "vocals.wav")
    if os.path.isfile(want):
        return want
    wav = os.path.join(out_dir, f"{stem}.wav")
    os.makedirs(out_dir, exist_ok=True)
    if subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", media, "-vn", "-ac", "2", "-ar", "44100", wav]).returncode:
        return None
    r = subprocess.run([python, "-m", "demucs", "--two-stems", "vocals", "-n", "htdemucs", "-o", out_dir, wav],
                       capture_output=True, text=True)
    if r.returncode or not os.path.isfile(want):
        print(f"vocal_swap: demucs failed on {media}: {r.stderr[-300:]}", file=sys.stderr)
        return None
    return want


EDGE_TOL_S = 0.08


def edge_words(segments: list[dict], clip_words: dict) -> list[dict]:
    """Take words that sit within EDGE_TOL_S of a swap segment's edge, or straddle it —
    each one is a half-faded word in the film (film3 item 11, advisory). `clip_words`
    maps a clip path to its whisper words [{t, w[, end]}] on the CLIP's clock; a
    segment plays clip[clipOffset..] from `start`, so a word lands at
    start + (t - clipOffset) in film time."""
    out = []
    for seg in segments:
        words = clip_words.get(seg.get("clip") or "") or []
        s0, s1, off = float(seg["start"]), float(seg["end"]), float(seg.get("clipOffset") or 0.0)
        for w in words:
            t = float(w.get("t", 0.0)); e = float(w.get("end") or t + 0.25)
            a, b = s0 + (t - off), s0 + (e - off)
            if b <= s0 - EDGE_TOL_S or a >= s1 + EDGE_TOL_S:
                continue                                   # not in this segment at all
            for edge, name in ((s0, "start"), (s1, "end")):
                if (a < edge < b) or abs(a - edge) < EDGE_TOL_S or abs(b - edge) < EDGE_TOL_S:
                    out.append({"window": seg.get("window"), "word": w.get("w"), "at": round(a, 3),
                                "edge": name, "edgeAt": round(edge, 3)})
    return out


def load_clip_words(store_path: str, extra_path: str = "") -> dict:
    """clip path -> [{t, w}] from artifacts/clip-transcripts.json (+ fit_takes' words.json
    for the fitted copies) — join_cuts' loader, shared."""
    words: dict = {}
    if store_path and os.path.isfile(store_path):
        store = json.load(open(store_path, encoding="utf-8")).get("clips") or {}
        for entry in store.values():
            if isinstance(entry, dict) and entry.get("path"):
                words[entry["path"]] = entry.get("words") or []
    if extra_path and os.path.isfile(extra_path):
        words.update(json.load(open(extra_path, encoding="utf-8")))
    return words


def subtract_spans(segs: list[dict], keep_record: list[tuple[float, float]]) -> list[dict]:
    """Cut `keep_record` spans (film seconds) out of the swap, so the RECORD's vocal plays
    there instead of the take's. The tool for a window whose take sings the wrong thing —
    e.g. one that straddles a performer handover and puts the boy's voice on the girl's
    line (Baby Ram & Sita w04, 2026-09-01). Pure."""
    out = []
    for s in segs:
        pieces = [(float(s["start"]), float(s["end"]))]
        for ka, kb in keep_record:
            nxt = []
            for a, b in pieces:
                if kb <= a or ka >= b:
                    nxt.append((a, b))
                    continue
                if a < ka:
                    nxt.append((a, ka))
                if kb < b:
                    nxt.append((kb, b))
            pieces = nxt
        for a, b in pieces:
            if b - a <= FADE_S * 2:
                continue
            out.append({**s, "start": round(a, 3), "end": round(b, 3),
                        "clipOffset": round(float(s["clipOffset"]) + (a - float(s["start"])), 3)})
    return out


def other_voice_lines(plan: dict, job: dict, min_s: float = 0.0, partials: bool = False):
    """Lines sung by the OTHER performer inside a performer-a or -b window, as
    (absStart, absEnd, who, text). ONE definition for the gate (plan_coherence #15) and
    the swap: they once disagreed on partial fragments and on a minimum length, so a plan
    could pass the gate and still be carved by the swap. `partials` keeps the mute-edge
    fragments of a neighbour's line (partialHead/partialTail); `min_s` drops short ones."""
    who = job.get("performer") or "a"
    if who not in ("a", "b"):
        return []
    prons = [x.strip() for x in str(plan.get("pronouns") or "he").split("|")]
    pron = prons[1 if who == "b" else 0] if len(prons) > (1 if who == "b" else 0) else "he"
    gender = {"he": "male", "she": "female"}.get(pron)
    if not gender:
        return []
    other = "female" if gender == "male" else "male"
    out = []
    for sp in (job.get("vocal") or {}).get("spans") or []:
        if sp.get("who") != other:
            continue
        if not partials and (sp.get("partialHead") or sp.get("partialTail")):
            continue
        length = float(sp.get("end", 0.0)) - float(sp.get("start", 0.0))
        if length <= 0 or length < min_s:
            continue
        abs0 = float(sp.get("absStart", float(job.get("startSec", 0.0)) + float(sp.get("start", 0.0))))
        out.append((round(abs0, 3), round(abs0 + length, 3), other, str(sp.get("text") or "")))
    return out


def foreign_spans(plan: dict) -> list[tuple[float, float, str, str, str]]:
    """Film-time spans the RECORD keeps: a line in the OTHER performer's voice inside a
    performer-a or -b window, as (start, end, jobId, who, text). A take sings its whole
    slice, so where the plan let a window straddle the handover the boy's take sang the
    girl's line — and vocal-swap put his voice on it (Baby Ram & Sita w04, 2026-09-01).
    A neighbour line's mute-edge fragment is NOT a foreign span: the slice is muted there
    and the take sings nothing — and subtracting it (from every window, as this once did)
    carved his last word and her first word out of the swap at every handover (review
    finding, 2026-09-02). Pure. Empty for solo films and `both` windows."""
    out = []
    for j in plan.get("jobs", []):
        for a0, a1, other, text in other_voice_lines(plan, j, partials=False):
            out.append((a0, a1, j["id"], other, text))
    return out


def plan_segments(plan: dict, selection: dict, clips_by_id: dict,
                  covered: list[tuple[float, float]] | None = None,
                  covered_clips: set | None = None) -> list[dict]:
    """The sung spans, in film time, each with the take that sings them.

    Pure: no I/O. A segment = {start, end, clip, clipOffset} — film time [start, end)
    is covered by the take's audio starting at clipOffset seconds into the clip —
    always 0: the assembler plays the clip from frame 0 at the window start. The
    span is the WHOLE window the take occupies on screen (the selection's start..end),
    not just the record's sung length: the model may stretch a phrase pause and sing
    its last words after the record's line ends (w00, +0.8 s), and the picture shows
    that mouth — its voice must play with it. The pads around the singing are silent
    in the record vocal by construction, so nothing of the record is lost. The span is clipped to the audio the clip actually has (seconds).
    """
    jobs = {j["id"]: j for j in plan.get("jobs", [])}
    out = []
    for s in selection.get("vocalMap", []):
        perf = s.get("performerClip")
        # A COVER'S EXEMPTION IS NOT A GAP SECTION'S. select_cut exempts a gap section that
        # shows a take silent (nothing sung: the record's voice plays) — skip those. A
        # cover exempts a window it partly replaced with B-roll; skipping that dropped the
        # take's own voice from the 54 % of the window still showing its mouth (Baby Ram
        # & Sita w04, v2/v3, 2026-09-01). The covered spans are subtracted below instead.
        by_cover = s.get("lipSyncExemptBy") == "cover" or perf in (covered_clips or set())   # a record proves a cover
        if not perf or (s.get("lipSyncExempt") and not by_cover):
            continue
        c = clips_by_id.get(perf)
        if not c:
            continue
        # The plan job is the one the CLIP was rendered for (queue/clips/<jobId>.mp4) —
        # NOT the selection's window id: select_cut numbers its grid with the
        # instrumental-gap sections included, so past the first gap its `w03` is the
        # plan's w02 (New Era v2, 2026-08-31: w02's 12 s take got w03's 6 s geometry and
        # lost its last two lines to the record; w07's take got no voice at all).
        stem = os.path.splitext(os.path.basename(c.get("path") or ""))[0]
        j = jobs.get(stem) or jobs.get(perf)
        if not j or not j.get("voiceRef"):
            continue
        w_start = float(s["start"])
        end = float(s["end"])
        # THE PICTURE IS THE CLIP FROM FRAME 0 AT THE WINDOW START. The selection carries
        # headSec (the plan's trimStartSec) but the assembler (music-video.ts) consumes no
        # in-point — in record mode the slide stage baked the offset into shifted clips,
        # and vocal-swap skips slide. Reading the voice from trimStartSec in put it
        # 0.3-0.7 s AHEAD of the mouth on every window but w00 (trim 0), which the
        # operator heard at once ("only the first video is correct lip sync", 2026-08-31
        # 08:40). Measured on the master: picture lag 0.00 s in all 8 windows. So the
        # voice starts at the clip's t=0 too, and the span is clipped to the clip's length.
        secs = float(c.get("durationSec") or j.get("seconds") or 0.0)   # a fitted copy is shorter than the plan's seconds
        if secs > 0:
            end = min(end, w_start + secs - float(s.get("headSec") or 0.0))
        if end - w_start <= FADE_S * 2:
            continue
        # the voice starts where the picture starts: the section's headSec (0 after fit_takes;
        # the assembler honours it since 2026-08-31)
        out.append({"window": perf, "job": j["id"], "start": round(w_start, 3), "end": round(end, 3),
                    "clip": c["path"], "clipOffset": round(float(s.get("headSec") or 0.0), 3)})
    # the other performer's lines stay the record's (see foreign_spans) — carved from the
    # window they sit in, never from a neighbour's segment
    by_job: dict = {}
    for a0, a1, jid, _, _ in foreign_spans(plan):
        by_job.setdefault(jid, []).append((a0, a1))
    if by_job:
        carved = []
        for seg in out:
            spans = by_job.get(seg.get("job") or "")
            carved.extend(subtract_spans([seg], spans) if spans else [seg])
        out = carved
    # ... and so does every second a cutaway replaced the mouth (cover_mouthing's record)
    if covered:
        out = subtract_spans(out, [(float(a0), float(a1)) for a0, a1 in covered])
    return out


def build_filter(segments: list[dict], n_song: int, fade: float, gains: list[float]) -> tuple[str, list[str]]:
    """The ffmpeg filter graph: [0]=instrumental, [1]=original vocal, [2..]=take vocals.

    The vocal track is the original vocal with each segment's span replaced by the
    take's vocal: the original is silenced over the span (volume enable) and the take's
    vocal, delayed to the span's start and faded at both edges, is summed in. Fades
    at both edges of both signals give a clean hand-over. Returns (filter, inputs)."""
    parts = [f"[1:a]aformat=channel_layouts=stereo[ov0]"]
    prev = "ov0"
    for i, seg in enumerate(segments):
        a, b = seg["start"], seg["end"]
        # carve the span out of the original vocal (keep a fade on either side)
        parts.append(f"[{prev}]volume=enable='between(t,{a + fade:.3f},{b - fade:.3f})':volume=0[ov{i + 1}]")
        prev = f"ov{i + 1}"
    idx = 2
    mixed = [prev]
    for i, seg in enumerate(segments):
        a, b = seg["start"], seg["end"]
        span = b - a
        parts.append(
            f"[{idx}:a]aformat=channel_layouts=stereo,atrim=start={seg['clipOffset']:.3f}:end={seg['clipOffset'] + span:.3f},"
            f"asetpts=PTS-STARTPTS,volume={gains[i]:.2f}dB,afade=t=in:st=0:d={fade:.3f},"
            f"afade=t=out:st={max(0.0, span - fade):.3f}:d={fade:.3f},adelay={int(a * 1000)}|{int(a * 1000)}[tv{i}]")
        mixed.append(f"tv{i}")
        idx += 1
    parts.append("".join(f"[{m}]" for m in mixed) + f"amix=inputs={len(mixed)}:duration=first:normalize=0[voc]")
    parts.append("[0:a]aformat=channel_layouts=stereo[inst];[inst][voc]amix=inputs=2:duration=first:normalize=0[a]")
    return ";".join(parts), [s["clip"] for s in segments]


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--selection", required=True)
    ap.add_argument("--song", required=True, help="hook.wav (the record)")
    ap.add_argument("--stems", required=True, help="build/stems (vocals.wav + _demucs/htdemucs/hook/no_vocals.wav)")
    ap.add_argument("--master", required=True, help="the cut master; its audio is replaced in place")
    ap.add_argument("--out", required=True, help="the full-length swapped audio (wav)")
    ap.add_argument("--json", default="")
    ap.add_argument("--fade", type=float, default=FADE_S)
    ap.add_argument("--python",
                    default=os.path.join(os.environ.get("VCLAW_WORKSPACE") or os.path.expanduser(os.path.join("~", "videoclaw")),
                                         "tools", "singer-diarize", ".venv", "bin", "python"),
                    help="the Demucs interpreter: $VCLAW_WORKSPACE/tools/singer-diarize/.venv (the lane's own venv)")
    ap.add_argument("--keep-original", action="store_true", help="leave the master untouched; only write --out")
    ap.add_argument("--cutaways", default="", metavar="JSON",
                    help="cover_mouthing's record of covered spans (default: cutaways-<sid>.json beside "
                         "the selection) — a covered second shows B-roll, so the record's voice plays there")
    ap.add_argument("--cards", default="", help="build/bookends/cards.json — lets a span use the film clock (1:48-1:53)")
    ap.add_argument("--store", default="", help="artifacts/clip-transcripts.json — for the edge-word advisory")
    ap.add_argument("--extra-words", default="", help="fit_takes' words.json for the fitted copies")
    ap.add_argument("--keep-record", action="append", default=[], metavar="A-B",
                    help="film-second span where the RECORD's vocal stays (repeatable) — for a "
                         "stretch the take sings wrongly, e.g. a window that straddles a performer "
                         "handover and puts one child's voice on the other's line")
    a = ap.parse_args()

    plan = json.load(open(a.plan, encoding="utf-8"))
    sel = json.load(open(a.selection, encoding="utf-8"))
    clips = {c["id"]: c for c in sel.get("clips", [])}
    inst = os.path.join(a.stems, "_demucs", "htdemucs", "hook", "no_vocals.wav")
    ovoc = os.path.join(a.stems, "vocals.wav")
    for need in (inst, ovoc):
        if not os.path.isfile(need):
            print(f"vocal_swap: missing {need} — run the stem stage (singer_diarize --separate-only)", file=sys.stderr)
            return 2
    cut_path = a.cutaways
    if not cut_path:
        m_sid = re.search(r"selection-(.+)\.json$", os.path.basename(a.selection))
        cut_path = os.path.join(os.path.dirname(os.path.abspath(a.selection)),
                                f"cutaways-{m_sid.group(1)}.json" if m_sid else "cutaways.json")
    if not os.path.isfile(cut_path):
        legacy = os.path.join(os.path.dirname(os.path.abspath(a.selection)), "cutaways.json")
        if os.path.isfile(legacy):
            cut_path = legacy        # a film cut before the per-style record (the runner's cutaways_for)
    covered, covered_clips = [], set()
    if os.path.isfile(cut_path):
        for c in json.load(open(cut_path, encoding="utf-8")).get("cutaways", []):
            covered.append((float(c["startSec"]), float(c["endSec"])))
            covered_clips.add(str(c.get("clip") or ""))
            print(f"vocal_swap: {c.get('clip')}: the record keeps {float(c['startSec']):.2f}-{float(c['endSec']):.2f}s — "
                  f"a cutaway ({c.get('broll')}) replaces the mouth there", file=sys.stderr)
    segments = plan_segments(plan, sel, clips, covered=covered, covered_clips=covered_clips)
    for a0, a1, jid, who, text in foreign_spans(plan):
        print(f"vocal_swap: {jid}: the record keeps the {who} line \"{text[:40]}\" at "
              f"{a0:.2f}-{a1:.2f}s — the other performer's line inside this window", file=sys.stderr)
    keep = []
    for sp in a.keep_record:
        # song seconds or the film clock (raplib.parse_span); a reversed span is refused
        # there — it once made subtract_spans return two OVERLAPPING pieces and the take's
        # voice mixed twice, +6 dB (review finding, 2026-09-02)
        try:
            ps = raplib.parse_span(sp, cards=a.cards or None)
        except ValueError as e:
            print(f"vocal_swap: --keep-record {e}", file=sys.stderr)
            return 2
        keep.append((ps["start"], ps["end"]))
    if keep:
        before = len(segments)
        segments = subtract_spans(segments, keep)
        print(f"vocal_swap: the record's vocal kept over "
              + ", ".join(f"{x:.2f}-{y:.2f}s" for x, y in keep)
              + f" ({before} span(s) -> {len(segments)})", file=sys.stderr)
    if not segments:
        print("vocal_swap: no sung windows with a performer clip — nothing to swap", file=sys.stderr)
        return 0
    build = os.path.dirname(os.path.abspath(a.out))
    dem = os.path.join(build, "vocal-swap-demucs")
    gains, take_vocals, rows, mismatches = [], [], [], []
    for seg in segments:
        tv = demucs_vocal(a.python, seg["clip"], dem)
        if not tv:
            print(f"vocal_swap: {seg['window']}: no vocal from {os.path.basename(seg['clip'])} — kept the record's vocal there",
                  file=sys.stderr)
            continue
        span = seg["end"] - seg["start"]
        # THE VOICE, NOT JUST THE WORDS (raplib.same_voice): a take that sang its slice in
        # a different voice keeps the record's vocal over its span and is named for the
        # operator's ear — the film never carries a stranger's voice (w05, 2026-09-02).
        p_take = raplib.voice_profile(tv, seg["clipOffset"], span)
        p_rec = raplib.voice_profile(ovoc, seg["start"], span)
        verdict = raplib.same_voice(p_take, p_rec)
        if verdict is False:
            mismatches.append({"window": seg["window"], "start": round(seg["start"], 3), "end": round(seg["end"], 3),
                               "take": p_take, "record": p_rec, "clip": seg["clip"]})
            print(f"vocal_swap: {seg['window']}: the take's voice sits at {p_take['median']:.0f} Hz "
                  f"({p_take['lowShare']:.0%} under {raplib.LOW_VOICE_HZ:.0f} Hz) against the record's "
                  f"{p_rec['median']:.0f} Hz ({p_rec['lowShare']:.0%}) over {seg['start']:.2f}-{seg['end']:.2f}s — "
                  f"a different voice; the record's vocal is kept there (verify:voice)", file=sys.stderr)
            continue
        lo = lufs(ovoc, seg["start"], span)
        lt = lufs(tv, seg["clipOffset"], span)
        g = round((lo - lt), 2) if (lo is not None and lt is not None) else 0.0
        g = max(-12.0, min(12.0, g))
        gains.append(g)
        take_vocals.append({**seg, "takeVocal": tv, "gainDb": g, "recordLufs": lo, "takeLufs": lt})
        rows.append(f"  {seg['window']}: {seg['start']:.2f}-{seg['end']:.2f}s from {os.path.basename(seg['clip'])} "
                    f"(+{seg['clipOffset']:.2f}s in), gain {g:+.1f} dB")
    if not take_vocals:
        return 1
    fc, inputs = build_filter(take_vocals, 2, a.fade, gains)
    # the swapped audio is cut to the MASTER's video, not the song: a master a frame or
    # two shorter than the song (the synthetic dry run's 75.458 s vs 75.53 s) failed
    # check_master's audio-video-aligned by 72 ms once the AAC frames rounded up
    total = probe_seconds(a.song)
    if os.path.isfile(a.master):
        r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=duration",
                            "-of", "csv=p=0", a.master], capture_output=True, text=True)
        try:
            total = float(r.stdout.strip())      # the audio is exactly as long as the picture
        except ValueError:
            pass
    cmd = ["ffmpeg", "-v", "error", "-y", "-i", inst, "-i", ovoc]
    for s in take_vocals:
        cmd += ["-i", s["takeVocal"]]
    cmd += ["-filter_complex", fc, "-map", "[a]", "-t", f"{total:.3f}", "-ar", "44100", a.out]
    p = subprocess.run(cmd, capture_output=True, text=True)
    if p.returncode:
        print(f"vocal_swap: ffmpeg failed:\n{p.stderr[-600:]}", file=sys.stderr)
        return 1
    print("vocal_swap: the film's audio = the record's beat + the take's voice on:", file=sys.stderr)
    print("\n".join(rows), file=sys.stderr)
    if not a.keep_original and os.path.isfile(a.master):
        # in build/, not beside the master: final/ holds deliverables only (final_qc's
        # foreign-content check; a re-cut's QC once summed every mp4 it found there)
        keep = os.path.join(os.path.dirname(os.path.abspath(a.out)),
                            os.path.basename(a.master)[:-4] + ".songaudio.mp4")
        beside = a.master[:-4] + ".songaudio.mp4"       # where it lived before 2026-09-01
        if not os.path.isfile(keep) and os.path.isfile(beside):
            shutil.move(beside, keep)                    # migrate: final/ holds deliverables only
        if not os.path.isfile(keep):
            shutil.copy2(a.master, keep)
        tmp = a.master[:-4] + ".vocalswap.tmp.mp4"
        # NO -shortest: with a copied video stream it truncates at a packet boundary and
        # took four frames off the picture (75.542 -> 75.375 s, dry run 2026-08-31). The
        # WAV above is already cut to the video's length.
        p = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", a.master, "-i", a.out, "-map", "0:v", "-map", "1:a",
                            "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", tmp], capture_output=True, text=True)
        if p.returncode:
            print(f"vocal_swap: remux failed:\n{p.stderr[-400:]}", file=sys.stderr)
            return 1
        os.replace(tmp, a.master)
        print(f"vocal_swap: master remuxed -> {a.master} (record-audio copy: {os.path.basename(keep)})", file=sys.stderr)
    if a.json:
        # EVERY TAKE WORD LIES INSIDE ONE SEGMENT (item 11, advisory): a word on a segment's
        # edge is half-faded in the film. Named here; the review page shows the row.
        clip_words = load_clip_words(a.store, a.extra_words)
        edges = edge_words(take_vocals, clip_words)
        wordless = [seg["window"] for seg in take_vocals if not clip_words.get(seg.get("clip") or "")]
        if wordless:
            # silence here would read as "clean" — say the check did not run (2026-09-02)
            print(f"vocal_swap: no words for {len(wordless)} segment(s) ({', '.join(str(w) for w in wordless[:6])}) — "
                  f"the edge-word check did not run there (fit_takes' words.json / the transcript store)", file=sys.stderr)
        for ew in edges:
            print(f"vocal_swap: {ew['window']}: the word {ew['word']!r} at {ew['at']:.2f}s sits on the segment's "
                  f"{ew['edge']} ({ew['edgeAt']:.2f}s) — half-faded; move the cut or the span (advisory)", file=sys.stderr)
        json.dump({"segments": take_vocals, "audio": a.out, "fade": a.fade, "voiceMismatch": mismatches,
                   "edgeWords": edges},
                  open(a.json, "w", encoding="utf-8"), indent=1)
    return 0


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