#!/usr/bin/env python3
"""cover_reference.py — a sung COVER of the sheet, retimed onto the record's clock, as the
lip-sync reference (VOICE_SOURCE=cover).

WHY THIS EXISTS. With a commercial record as the film's master (AUDIO_MODE=record), every
sung window's audio reference was a slice of that record — and Higgsfield refuses it
"due to copyright restrictions": a 13 s slice 6/6 on Baby Nimbooda part 2, a 9 s slice on
draw 1 of Baby Kala Chashma (2026-09-09; the operator read the card). Length raises the
odds; no length is a safe ceiling on a famous track. A cover is a different recording:
the model hears a vocal that is not the copyrighted master, the film keeps the record's
audio and the record's timeline (the shot-refs grid follows the reference video on the
record's clock — a cover cannot become the soundtrack without breaking that).

WHAT IT DOES
  1. whisper the cover with the sheet primed (the lane's own call: the whisper-cpp shim
     first on PATH, --initial_prompt = the sheet's head, word timestamps, the song's language);
  2. align the sheet's lines to the cover's words with vocal_brief.align — the same
     monotone aligner the record's brief was built with, so line i of the cover IS line i
     of the record;
  3. for every record line (start/end from build/vocal-brief.json — the record's own word
     map), take the cover's rendition of that line, atempo-stretch it (pitch-preserving,
     clamped ATEMPO_MIN..ATEMPO_MAX) to the record line's length and place it at the record
     line's start on a silent timeline the length of the song;
  4. loudnorm the result → build/cover/cover-retimed.wav; write cover-map.json (per line:
     record span, cover span, ratio, dropped) and cover-review.html for the operator's eye.

A line the cover did not sing (UNHEARD by the aligner) is NAMED in the map and the review
and left SILENT on the timeline — the prompt still says the words at the record's times and
tells the model to mouth only where words are sung, so a missing line closes the mouth
rather than inventing a vocal. It is never filled with the record.

Usage:
  cover_reference.py --project <dir> --cover <take.mp3> [--lyrics <sheet>] [--brief <vocal-brief.json>]
                     [--language pa] [--model medium] [--out-dir <dir>] [--min-ratio 0.45] [--dry-run]
Exit 0 = wrote the wav; 3 = the cover sang too few lines (below --min-coverage) — buy another take.
"""
from __future__ import annotations

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

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# vocal_brief (the lane's aligner) needs Python 3.12 f-strings; the librosa render runs under
# the singer-diarize venv's older interpreter, so the import is deferred to the planning path.
vocal_brief = None  # set by _aligner()


def _aligner():
    global vocal_brief
    if vocal_brief is None:
        import vocal_brief as _vb  # noqa: E402
        vocal_brief = _vb
    return vocal_brief


RENDER_PYTHON_DEFAULT = os.path.join(os.environ.get("VCLAW_WORKSPACE", os.path.expanduser(os.path.join("~", "videoclaw"))),
                                     "tools", "singer-diarize", ".venv", "bin", "python")

ATEMPO_MIN, ATEMPO_MAX = 0.5, 2.0          # ffmpeg atempo's single-stage range; chained beyond
COVER_PAD_S = 0.06                          # a hair of the cover before/after the aligned words
WHISPER_SHIM = os.path.join(os.environ.get("VCLAW_WORKSPACE", os.path.expanduser(os.path.join("~", "videoclaw"))),
                            "tools", "whisper-cpp", "bin")


def say(msg: str) -> None:
    print(f"cover_reference: {msg}", file=sys.stderr)


def die(msg: str, code: int = 1) -> None:
    say(msg)
    raise SystemExit(code)


def run(cmd: list[str], **kw) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, check=True, capture_output=True, text=True, **kw)


def probe_seconds(path: str, ffprobe: str = "ffprobe") -> float:
    out = run([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path]).stdout.strip()
    return float(out or 0.0)


def sheet_head(lyrics: str, limit: int = 700) -> str:
    """The runner's map-stage prompt: the sheet's lines, tags dropped, capped for whisper."""
    lines = [l.strip() for l in open(lyrics, encoding="utf-8")
             if l.strip() and not l.strip().startswith(("[", "#"))]
    return ". ".join(lines)[:limit]


def whisper_cover(cover: str, out_dir: str, lyrics: str, model: str, language: str) -> str:
    """whisper the cover exactly as the runner whispers the song (the shim first on PATH)."""
    env = dict(os.environ)
    if os.path.isdir(WHISPER_SHIM):
        env["PATH"] = WHISPER_SHIM + os.pathsep + env.get("PATH", "")
    cmd = ["whisper", cover, "--model", model, "--output_format", "json", "--word_timestamps", "True",
           "--output_dir", out_dir]
    if language:
        cmd += ["--language", language]
    prompt = sheet_head(lyrics)
    if prompt:
        cmd += ["--initial_prompt", prompt]
    subprocess.run(cmd, check=True, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    base = os.path.splitext(os.path.basename(cover))[0]
    tx = os.path.join(out_dir, base + ".json")
    if not os.path.isfile(tx):
        die(f"whisper produced no JSON for {cover} in {out_dir}")
    return tx


def atempo_chain(ratio: float) -> str:
    """ffmpeg atempo takes 0.5..2.0 per stage; chain stages for anything outside."""
    stages = []
    r = ratio
    while r > ATEMPO_MAX:
        stages.append(ATEMPO_MAX); r /= ATEMPO_MAX
    while r < ATEMPO_MIN:
        stages.append(ATEMPO_MIN); r /= ATEMPO_MIN
    stages.append(r)
    return ",".join(f"atempo={s:.6f}" for s in stages)


def plan_retime(record_lines: list[dict], cover_lines: list[dict]) -> list[dict]:
    """PURE. Line i of the record ↔ line i of the cover (both are parse_lyrics order).

    Each entry: {i, text, who, how, record: [start, end] | None, cover: [start, end] | None,
    ratio (cover seconds per record second: atempo's argument, >1 = the cover sang it slower
    and is sped up), dropped (why nothing is placed)}."""
    if len(record_lines) != len(cover_lines):
        die(f"the record's brief has {len(record_lines)} lines and the sheet {len(cover_lines)} — "
            "the brief was built from another sheet; re-run the plan stage first")
    out = []
    for i, (rl, cl) in enumerate(zip(record_lines, cover_lines)):
        e = {"i": i, "text": rl.get("text") or cl.get("text"), "who": rl.get("who"), "how": rl.get("how"),
             "record": None, "cover": None, "ratio": None, "dropped": ""}
        rs, re_ = rl.get("start"), rl.get("end")
        if rs is None or re_ is None or float(re_) - float(rs) < 0.15:
            e["dropped"] = "the record's brief did not place this line (nothing to lip-sync here)"
            out.append(e); continue
        cs, ce = cl.get("start"), cl.get("end")
        if cs is None or ce is None or float(ce) - float(cs) < 0.15:
            e["record"] = [round(float(rs), 3), round(float(re_), 3)]
            e["dropped"] = "the cover did not sing this line (UNHEARD) — silent on the timeline; the mouth stays closed"
            out.append(e); continue
        rd, cd = float(re_) - float(rs), float(ce) - float(cs)
        e["record"] = [round(float(rs), 3), round(float(re_), 3)]
        e["cover"] = [round(float(cs), 3), round(float(ce), 3)]
        e["ratio"] = round(cd / rd, 4)
        e["stretchNote"] = ("" if 0.8 <= e["ratio"] <= 1.25 else
                            f"the cover sang it {'slower' if e['ratio'] > 1 else 'faster'} ({e['ratio']:.2f}x) — a wide stretch; check by ear")
        out.append(e)
    return out


RATE_MAX = 1.6                          # a word is sped up at most this much
# ... and SLOWED down to fill its slot up to the next record word's onset. The first cut
# placed each word at its natural length and left the rest of the slot silent (RATE_MIN
# 0.7): Higgsfield accepted the slice, the take sang the right words — 1–1.7 s EARLY in the
# second half of the window, correlating 0.27 with the reference (Baby Kala Chashma w00
# draw 1, 2026-09-09 05:00). A chopped reference with gaps is re-sung at the model's own
# pace; a continuous one (the record's slices always were) is tracked. So a word now
# stretches to fill its slot, down to RATE_MIN — a held note in the record becomes a held
# word in the reference; the seam past that stays silent.
RATE_MIN = 0.25
ATTACK_S = 0.06                         # a word's first 60 ms is never stretched: the onset stays crisp for the mouth


def assign_words_to_lines(sheet_lines: list[dict], cover_words: list[dict]) -> list[list[dict]]:
    """PURE. Which cover words belong to which sheet line — by CHARACTER alignment.

    vocal_brief.align places a line as a span of n_words-2..n_words+3 transcript words and
    keeps the best similarity; on a cover whose whisper MERGES words ("Renabia" for "Renha
    Biya") the best span over-eats into the next line, so "Tenu Dekke" (line 2) rode at the
    END of line 1 and was placed at the record's 5.2 s instead of 6.8 s — and the take sang
    it there (Baby Kala Chashma w00 draw 1, 2026-09-09). Aligning the two CHARACTER streams
    (the sheet's normalised lines, the cover's normalised words) with difflib survives merges
    and splits: each cover word maps to the sheet position its matched characters cover, and
    that position names the line. A word with no match takes its neighbour's line (monotone)."""
    import difflib
    vb = _aligner()
    sheet_chars, bounds = "", []             # bounds[i] = (start, end) of line i in sheet_chars
    for ln in sheet_lines:
        a = len(sheet_chars)
        sheet_chars += vb.norm_latin(ln.get("text") or "").replace(" ", "")
        bounds.append((a, len(sheet_chars)))
    cover_chars, wpos = "", []
    for w in cover_words:
        a = len(cover_chars)
        cover_chars += (w.get("lat") or vb.norm_latin(w.get("raw") or "")).replace(" ", "")
        wpos.append((a, len(cover_chars)))
    sm = difflib.SequenceMatcher(None, sheet_chars, cover_chars, autojunk=False)
    blocks = [b for b in sm.get_matching_blocks() if b.size > 0]

    def line_of(pos: int) -> int:
        for i, (a, b) in enumerate(bounds):
            if a <= pos < b:
                return i
        return len(bounds) - 1

    out = [[] for _ in sheet_lines]
    last = 0
    for w, (a, b) in zip(cover_words, wpos):
        votes = {}
        for blk in blocks:
            lo, hi = max(a, blk.b), min(b, blk.b + blk.size)
            if hi > lo:
                mid = blk.a + (lo - blk.b) + (hi - lo) // 2
                votes[line_of(mid)] = votes.get(line_of(mid), 0) + (hi - lo)
        if votes:
            li = max(votes, key=votes.get)
            li = max(li, last) if li < last else li          # never go backwards
            last = li
        else:
            li = last
        out[li].append(w)
    return out


def words_in(words: list[dict], start: float, end: float, slack: float = 0.05) -> list[dict]:
    return [w for w in words if start - slack <= w["t0"] < end + slack]


def _norm(t: str) -> str:
    return " ".join((t or "").lower().replace("'", "").split())


def reuse_missing(plan: list[dict], cover_words: list[dict] | None = None, fuzzy: float = 0.85) -> None:
    """A line the cover did not sing takes cover audio from a line it DID sing when the
    words match — exactly (a hook repeat), nearly (difflib ratio ≥ `fuzzy`: "…Ladki…" for
    "…Ladko…"), or, for a line of one or two words, from the cover's heard WORDS anywhere
    ("Fire" inside "Baby Fire"). The same words, sung once, placed again; never the record."""
    import difflib
    have = [e for e in plan if e.get("cover") and e.get("record") and not e.get("reusedFrom")]
    for e in plan:
        if not e.get("record") or e.get("cover"):
            continue
        want = _norm(e.get("text"))
        best, score = None, 0.0
        for src in have:
            r = difflib.SequenceMatcher(None, want, _norm(src.get("text"))).ratio()
            if r > score:
                best, score = src, r
        note = ""
        if best and score >= fuzzy:
            e["cover"] = list(best["cover"]); e["reusedFrom"] = best["i"]
            note = (f"cover audio reused from line {best['i']:02d} (same words)" if score >= 0.999 else
                    f"cover audio reused from line {best['i']:02d} ({score:.0%} the same words)")
        elif cover_words and len(want.split()) <= 2:
            # a one/two-word line: find those words sung anywhere in the cover
            lat = [_norm(w.get("lat") or w.get("raw")) for w in cover_words]
            keys = want.split()
            hit = None
            for k in range(len(lat) - len(keys) + 1):
                if all(difflib.SequenceMatcher(None, keys[j], lat[k + j]).ratio() >= 0.8 for j in range(len(keys))):
                    hit = k; break
            if hit is not None:
                w0, w1 = cover_words[hit], cover_words[hit + len(keys) - 1]
                e["cover"] = [round(float(w0["t0"]), 3), round(float(w1["t1"]), 3)]
                e["reusedFrom"] = -1
                note = f"cover audio taken from the cover's own words {w0.get('raw')}…{w1.get('raw')} at {w0['t0']:.1f}s"
        if e.get("cover"):
            rd = e["record"][1] - e["record"][0]; cd = max(0.05, e["cover"][1] - e["cover"][0])
            e["ratio"] = round(cd / rd, 4); e["dropped"] = ""; e["stretchNote"] = note


def place_words(rec_words: list[dict], cov_words: list[dict], line_start: float, line_end: float,
                cov_start: float, cov_end: float) -> list[dict]:
    """PURE. Where each cover word goes on the record's clock.

    Cover word k is assigned to record word j by relative position (k/(nc-1) ≈ j/(nr-1));
    the cover words assigned to one record word play in order from that word's ONSET, sped
    up or slowed (RATE_MIN..RATE_MAX) so they fit before the next record word's onset, and
    trimmed there if they still do not. No record words heard: the whole cover line is
    stretched onto the whole record line (clamped). Each entry:
      {c0, c1 (cover seconds), at (record seconds), rate (>1 = sped up), maxLen}"""
    out = []
    if not cov_words:
        cov_words = [{"t0": cov_start, "t1": cov_end, "raw": "(line)"}]
    if not rec_words:
        rec_words = [{"t0": line_start, "t1": line_end, "raw": "(line)"}]
    nr, nc = len(rec_words), len(cov_words)
    groups: dict[int, list[dict]] = {}
    for k, w in enumerate(cov_words):
        j = int(round(k * (nr - 1) / (nc - 1))) if nc > 1 else 0
        groups.setdefault(j, []).append(w)
    js = sorted(groups)
    for gi, j in enumerate(js):
        onset = float(rec_words[j]["t0"])
        nxt = float(rec_words[js[gi + 1]]["t0"]) if gi + 1 < len(js) else float(line_end)
        # the group's slot runs to the next group's onset; if that is not past its own
        # record word's end, at least that word's length
        slot = max(nxt, float(rec_words[j]["t1"])) - onset
        natural = sum(max(0.05, float(w["t1"]) - float(w["t0"])) for w in groups[j])
        rate = natural / max(0.05, slot)                      # >1: the cover is longer than the slot
        rate = min(RATE_MAX, max(RATE_MIN, rate))
        cursor = onset
        for w in groups[j]:
            dur = max(0.05, float(w["t1"]) - float(w["t0"])) / rate
            out.append({"c0": round(float(w["t0"]), 3), "c1": round(float(w["t1"]), 3), "at": round(cursor, 3),
                        "rate": round(rate, 3), "maxLen": round(max(0.05, min(dur, nxt - cursor)), 3),
                        "word": w.get("raw", "")})
            cursor += dur
    return out


def render(cover: str, plan: list[dict], song_seconds: float, dest: str, ffmpeg: str, rate: int = 48000) -> None:
    """Every placed word: sliced from the cover, time-stretched (pitch-preserving, librosa),
    laid at its record onset on a silent timeline; then loudnorm. Needs librosa + soundfile
    (the singer-diarize venv has them; run this script with that interpreter)."""
    try:
        import numpy as np
        import librosa
        import soundfile as sf
    except ImportError as exc:                                   # noqa: BLE001
        die(f"render needs librosa + soundfile ({exc}) — run with "
            f"$VCLAW_WORKSPACE/tools/singer-diarize/.venv/bin/python")
    y, sr = librosa.load(cover, sr=rate, mono=True)
    line = np.zeros(int(math.ceil(song_seconds * sr)) + sr, dtype=np.float32)
    fade = int(0.008 * sr)
    n_placed = 0
    for e in plan:
        for pw in e.get("placements") or []:
            a, b = int(pw["c0"] * sr), int(pw["c1"] * sr)
            seg = y[a:b]
            if seg.size < fade * 2:
                continue
            if abs(pw["rate"] - 1.0) > 0.02:
                # stretch the body, keep the attack: a phase-vocoder stretch smears the
                # onset, and the onset is what the lip-sync follows
                atk = min(int(ATTACK_S * sr), seg.size // 2)
                seg = np.concatenate([seg[:atk], librosa.effects.time_stretch(seg[atk:], rate=float(pw["rate"]))])
            seg = seg[: int(pw["maxLen"] * sr)]
            if seg.size < fade * 2:
                continue
            seg = seg.copy()
            seg[:fade] *= np.linspace(0, 1, fade, dtype=np.float32)
            seg[-fade:] *= np.linspace(1, 0, fade, dtype=np.float32)
            at = int(pw["at"] * sr)
            end = min(line.size, at + seg.size)
            line[at:end] += seg[: end - at]
            n_placed += 1
    if n_placed == 0:
        die("nothing to place — the cover sang none of the record's lines", 3)
    peak = float(np.max(np.abs(line))) or 1.0
    if peak > 0.98:
        line *= 0.98 / peak
    raw = dest + ".raw.wav"
    sf.write(raw, line[: int(math.ceil(song_seconds * sr))], sr)
    run([ffmpeg, "-y", "-v", "error", "-i", raw, "-af", "loudnorm=I=-16:TP=-1.5:LRA=11",
         "-ac", "1", "-ar", str(rate), dest])
    os.remove(raw)
    say(f"{n_placed} cover words placed on the record's clock")


def write_review(path: str, plan: list[dict], cover: str, dest: str, coverage: float, take_label: str) -> None:
    rows = []
    for e in plan:
        rec = f"{e['record'][0]:.2f}–{e['record'][1]:.2f}" if e.get("record") else "—"
        cov = f"{e['cover'][0]:.2f}–{e['cover'][1]:.2f}" if e.get("cover") else "—"
        ratio = (f"{e['ratio']:.2f}x line · {e.get('coverWords', 0)}→{e.get('recordWords', 0)} words @ {e.get('meanRate') or 0:.2f}x"
                 if e.get("ratio") else "—")
        cls = "drop" if e.get("dropped") else ("wide" if e.get("stretchNote") and not e.get("reusedFrom") else "")
        note = e.get("dropped") or e.get("stretchNote") or ""
        rows.append(f"<tr class='{cls}'><td>{e['i']:02d}</td><td>{html.escape(str(e.get('who') or ''))} · "
                    f"{html.escape(str(e.get('how') or ''))}</td><td>{html.escape(str(e['text']))}</td>"
                    f"<td>{rec}</td><td>{cov}</td><td>{ratio}</td><td>{html.escape(note)}</td></tr>")
    doc = f"""<!doctype html><meta charset="utf-8"><title>Cover reference — {html.escape(take_label)}</title>
<style>body{{font:14px/1.4 -apple-system,Helvetica,Arial;margin:24px;color:#eee;background:#141416}}
table{{border-collapse:collapse;width:100%}}td,th{{padding:6px 8px;border-bottom:1px solid #333;vertical-align:top;text-align:left}}
tr.drop td{{color:#f88}}tr.wide td{{color:#fc6}}code{{color:#9cf}}audio{{width:100%;margin:8px 0}}</style>
<h1>Cover vocal as the lip-sync reference</h1>
<p>The record stays the film's audio and clock. The model is handed <b>this cover</b>, line by line retimed onto the
record's word map, because Higgsfield refused the record's own slices for copyright. Coverage: <b>{coverage:.0%}</b> of the
record's placed lines carry a cover line. Take: <code>{html.escape(cover)}</code>.</p>
<p>The cover as sung:</p><audio controls preload="none" src="{html.escape(os.path.relpath(cover, os.path.dirname(path)))}"></audio>
<p>The retimed reference on the record's clock (what every voice slice is cut from):</p>
<audio controls preload="none" src="{html.escape(os.path.relpath(dest, os.path.dirname(path)))}"></audio>
<p>Retiming is per WORD: each cover word lands on the record word's onset (by position in the line) and is stretched at most
0.7–1.6x, so the syllables the model hears fall where the record's do; a long held note in the record is shorter in the
reference and the mouth closes early there. A hook repeat the cover sang once reuses that audio.</p>
<table><tr><th>#</th><th>voice</th><th>line</th><th>record (s)</th><th>cover (s)</th><th>stretch</th><th>note</th></tr>
{''.join(rows)}</table>
<p>Red = no cover audio for that line (silent; the mouth stays closed there). Amber = a wide stretch, worth an ear.</p>
"""
    open(path, "w", encoding="utf-8").write(doc)


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--project", required=True)
    ap.add_argument("--cover", required=True, help="the cover take (mp3/wav) as sung by the music model")
    ap.add_argument("--lyrics", default="", help="the sheet; default <project>/references/lyrics.txt")
    ap.add_argument("--brief", default="", help="the record's vocal brief; default <project>/build/vocal-brief.json")
    ap.add_argument("--song", default="", help="the record (for its length); default <project>/build/hook.wav")
    ap.add_argument("--out-dir", default="", help="default <project>/build/cover")
    ap.add_argument("--language", default=os.environ.get("SONG_LANGUAGE", ""))
    ap.add_argument("--model", default=os.environ.get("WHISPER_MODEL", "medium"))
    ap.add_argument("--min-ratio", type=float, default=0.45, help="vocal_brief.align's bar")
    ap.add_argument("--min-coverage", type=float, default=0.75,
                    help="exit 3 when fewer of the record's placed lines got a cover line")
    ap.add_argument("--transcript", default="", help="reuse a whisper JSON of the cover instead of transcribing")
    ap.add_argument("--dry-run", action="store_true", help="align and plan only; write the map and review, no wav")
    ap.add_argument("--render-python", default=RENDER_PYTHON_DEFAULT if os.path.isfile(RENDER_PYTHON_DEFAULT) else sys.executable,
                    help="interpreter with librosa + soundfile for the render step (default: the singer-diarize venv)")
    ap.add_argument("--render-only", default="", metavar="MAP",
                    help="internal: render from a written cover-map.json (no aligner import)")
    ap.add_argument("--ffmpeg", default=os.environ.get("FFMPEG_BIN", "ffmpeg"))
    a = ap.parse_args()

    if a.render_only:
        m = json.load(open(a.render_only, encoding="utf-8"))
        render(m["cover"], m["lines"], float(m["songSeconds"]), m["out"], a.ffmpeg)
        return

    p = os.path.abspath(a.project)
    lyrics = a.lyrics or os.path.join(p, "references", "lyrics.txt")
    brief = a.brief or os.path.join(p, "build", "vocal-brief.json")
    song = a.song or os.path.join(p, "build", "hook.wav")
    out_dir = a.out_dir or os.path.join(p, "build", "cover")
    for f in (lyrics, brief, song, a.cover):
        if not os.path.isfile(f):
            die(f"not found: {f}")
    os.makedirs(out_dir, exist_ok=True)

    vocal_brief = _aligner()
    record_lines = json.load(open(brief, encoding="utf-8")).get("lines") or []
    sheet_lines = vocal_brief.parse_lyrics(lyrics)
    tx = a.transcript or whisper_cover(a.cover, out_dir, lyrics, a.model, a.language)
    words = vocal_brief.load_words(tx)
    by_line = assign_words_to_lines(sheet_lines, words)
    cover_lines = []
    for ln, ws in zip(sheet_lines, by_line):
        c = dict(ln)
        if ws:
            c["start"], c["end"] = round(float(ws[0]["t0"]), 2), round(float(ws[-1]["t1"]), 2)
            c["heard"] = " ".join(w.get("raw", "") for w in ws)
        else:
            c["start"] = c["end"] = None; c["heard"] = ""
        cover_lines.append(c)
    plan = plan_retime(record_lines, cover_lines)
    reuse_missing(plan, words)
    # the record's own word map: the primed transcript, the word pass and the stem pass filling
    # its silences — the same three ears the brief was built from
    build = os.path.join(p, "build")
    rec_words = vocal_brief.load_words(os.path.join(build, "transcript-words.json")) \
        if os.path.isfile(os.path.join(build, "transcript-words.json")) else []
    for fill in ("song-words.json", "stem-words.json"):
        fp = os.path.join(build, fill)
        if os.path.isfile(fp):
            rec_words = vocal_brief.merge_word_streams(rec_words, vocal_brief.load_word_list(fp))
    for e in plan:
        if not (e.get("record") and e.get("cover")):
            continue
        rw = words_in(rec_words, *e["record"])
        cw = by_line[e["i"]] if (by_line[e["i"]] and e.get("reusedFrom") is None) else words_in(words, *e["cover"])
        e["recordWords"], e["coverWords"] = len(rw), len(cw)
        e["placements"] = place_words(rw, cw, e["record"][0], e["record"][1], e["cover"][0], e["cover"][1])
        rates = [pw["rate"] for pw in e["placements"]]
        e["meanRate"] = round(sum(rates) / len(rates), 3) if rates else None

    placed = [e for e in plan if e.get("record")]
    got = [e for e in placed if e.get("cover")]
    coverage = (len(got) / len(placed)) if placed else 0.0
    for e in plan:
        if e.get("dropped") and e.get("record"):
            say(f"line {e['i']:02d} {e['text'][:50]!r}: {e['dropped']}")
        elif e.get("stretchNote"):
            say(f"line {e['i']:02d} {e['text'][:50]!r}: {e['stretchNote']}")
    say(f"{len(got)}/{len(placed)} of the record's placed lines carry a cover line ({coverage:.0%}); "
        f"{len(words)} cover words heard")

    dest = os.path.join(out_dir, "cover-retimed.wav")
    take_label = os.path.basename(a.cover)
    json.dump({"schemaVersion": 1, "cover": os.path.abspath(a.cover), "transcript": os.path.abspath(tx),
               "brief": os.path.abspath(brief), "lyrics": os.path.abspath(lyrics), "coverage": round(coverage, 3),
               "placedLines": len(placed), "coveredLines": len(got), "out": dest,
               "songSeconds": probe_seconds(song), "lines": plan},
              open(os.path.join(out_dir, "cover-map.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
    write_review(os.path.join(out_dir, "cover-review.html"), plan, a.cover, dest, coverage, take_label)
    if coverage < a.min_coverage:
        die(f"coverage {coverage:.0%} is under {a.min_coverage:.0%} — this take dropped too many lines; buy another", 3)
    if a.dry_run:
        say("dry run — map and review written, no wav")
        return
    map_path = os.path.join(out_dir, "cover-map.json")
    if os.path.abspath(a.render_python) == os.path.abspath(sys.executable):
        render(a.cover, plan, probe_seconds(song), dest, a.ffmpeg)
    else:
        r = subprocess.run([a.render_python, os.path.abspath(__file__), "--project", p, "--cover", a.cover,
                            "--render-only", map_path, "--ffmpeg", a.ffmpeg])
        if r.returncode != 0:
            die(f"render failed under {a.render_python} (exit {r.returncode})", r.returncode)
    say(f"-> {dest} ({probe_seconds(dest):.2f}s on the record's clock)")


if __name__ == "__main__":
    main()
