#!/usr/bin/env python3
"""sync_review.py — does the mouth match the record's words, and does the take's voice match the record?

The picture is SILENT; the operator picks what to hear. Judging sync from a take's own audio
is circular — a model's mouth always matches its OWN voice — so build/sync-review.html plays
a take (or the master) with no audio stream and four faders beside it: the record (hook.wav),
the instrumental stem, the vocal stem, and the take's own voice. "Instrumental + own voice" is
a live preview of what vocal_swap ships. The sheet's words light up on whisper's clock as they
are sung; each window shows the verdicts the lane actually wrote — or says "not on disk yet".

Three rules from the operator's StageDirector karaoke toolkit are applied, each measured there:
  1. the <video> carries ZERO audio streams (ffprobe asserts it; a browser leaks a video
     element's own track on seek/fullscreen) — build/sync-review/<name>-silent.mp4;
  2. small audio drift is nudged by ±2.5 % playbackRate, never hard-seeked (lib/sync_player.cjs);
  3. the current word stays lit through a gap until the next word begins.

WHAT THE PAGE NEVER DOES: compute a verdict. word-sync-<sid>.json, sync-profile-<sid>.json,
shift-report-<sid>.json, sync-accepts.json and lane-render.log are READ (draws_review.parse_log
is imported, not copied); every verdict names its file and mtime; a clip newer than its verdict
is marked STALE; under vocal-swap the verdict column says "by construction". Word timings come
from the brief's own word stream (vocal_brief's loaders) against the SHEET's tokens; a line with
no whisper words in reach falls back to a linear split and SAYS so. Refs are shown as images.

The clock: song time = video time + clockOffsetSec, one per video source, with its provenance:
a raw take = plan.jobs[w].startSec; a take as cut = selection-<sid>.vocalMap.start; the master
body = 0 on hook.wav's clock, VERIFIED against the song length (a mismatch is a red warning);
the film with bookends = -front_padding. The take's own audio is extracted to PCM WAV (AAC
priming would add tens of ms on an 80 ms bar).

Usage:
  sync_review.py --project <dir> [--style <sid> ...] [--windows w03,w05] [--out build/sync-review.html]
                 [--json build/sync-review.json] [--no-master] [--open]
Exit 0 whenever a page was written (missing data is rows, not an error) · 2 bad --project.
"""
from __future__ import annotations

import argparse
import difflib
import glob
import html
import json
import os
import re
import subprocess
import sys

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

import raplib  # noqa: E402
from lane_page import page  # noqa: E402

LIB_JS = os.path.join(HERE, "lib", "sync_player.cjs")
OUT_DIR = "sync-review"     # build/sync-review/ — beside strips-review/, not build/review-*.html (the boards)
WHISPER_FLOOR_MS = 100


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


# ---------------------------------------------------------------------------------------
# media
# ---------------------------------------------------------------------------------------
def audio_streams(path: str) -> int:
    r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=index",
                        "-of", "csv=p=0", path], capture_output=True, text=True)
    return len([l for l in r.stdout.splitlines() if l.strip()])


def fps_of(path: str) -> float | None:
    r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate",
                        "-of", "csv=p=0", path], capture_output=True, text=True)
    try:
        n, d = r.stdout.strip().split("/")
        return round(float(n) / float(d), 3)
    except (ValueError, ZeroDivisionError):
        return None


def content_ok(sidecar: str, src: str) -> bool:
    doc = raplib.read_json(sidecar)
    return bool(doc) and not raplib.moved_inputs(doc) and any(v.get("path") == src for v in (doc.get("_meta", {}).get("inputs") or {}).values())


def make_silent(src: str, out_dir: str, name: str) -> dict:
    """<name>-silent.mp4 with zero audio streams (asserted), rebuilt only when the source moved."""
    out = os.path.join(out_dir, f"{name}-silent.mp4")
    side = out + ".json"
    if os.path.isfile(src) and os.path.getsize(src) == 0:
        return {"src": None, "audioStreams": None, "playable": False, "reason": "the source clip is empty (0 bytes)"}
    if not (os.path.isfile(out) and content_ok(side, src)):
        os.makedirs(out_dir, exist_ok=True)
        if audio_streams(src) == 0:
            r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-c", "copy", out], capture_output=True, text=True)
            silent_from = "source"
        else:
            r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-c:v", "copy", "-an", "-movflags", "+faststart", out],
                               capture_output=True, text=True)
            silent_from = "copy"
            if r.returncode != 0:
                r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-c:v", "libx264", "-preset", "veryfast", "-crf", "18",
                                    "-pix_fmt", "yuv420p", "-an", "-movflags", "+faststart", out], capture_output=True, text=True)
                silent_from = "re-encode"
        if r.returncode != 0:
            return {"src": None, "audioStreams": None, "playable": False, "reason": f"ffmpeg could not make a silent copy: {r.stderr.strip()[-200:]}"}
        raplib.write_json_atomic(side, {"silentFrom": silent_from}, inputs={"source": src})
    n = audio_streams(out)
    doc = raplib.read_json(side) or {}
    return {"src": out, "audioStreams": n, "playable": n == 0, "silentFrom": doc.get("silentFrom"),
            "reason": None if n == 0 else f"the silent copy still carries {n} audio stream(s)"}


def extract_own_audio(src: str, out_dir: str, name: str) -> str | None:
    """The take's own audio as PCM WAV — AAC priming would offset it by tens of ms."""
    if audio_streams(src) == 0:
        return None
    out = os.path.join(out_dir, f"{name}-own.wav")
    side = out + ".json"
    if not (os.path.isfile(out) and content_ok(side, src)):
        os.makedirs(out_dir, exist_ok=True)
        r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-vn", "-c:a", "pcm_s16le", out], capture_output=True, text=True)
        if r.returncode != 0:
            return None
        raplib.write_json_atomic(side, {"kind": "own-audio"}, inputs={"source": src})
    return out


# ---------------------------------------------------------------------------------------
# words for a line — the SHEET's tokens on whisper's clock
# ---------------------------------------------------------------------------------------
def word_stream(build: str) -> list[dict]:
    """The brief's own merged stream: transcript.json's words plus the fill passes, exactly as
    vocal_brief placed its lines. Accepts {t,w}, {t,e,w} and raw whisper shapes."""
    import vocal_brief as vb
    words: list[dict] = []
    tx = os.path.join(build, "transcript.json")
    if os.path.isfile(tx):
        try:
            words = vb.load_words(tx)
        except Exception:   # noqa: BLE001 — a malformed transcript is a missing one here
            words = []
    for fill in ("song-words.json", "stem-words.json"):
        fp = os.path.join(build, fill)
        if os.path.isfile(fp) and raplib.read_json(fp) is not None:
            try:
                words = vb.merge_word_streams(words, vb.load_word_list(fp)) if words else vb.load_word_list(fp)
            except Exception:   # noqa: BLE001
                pass
    return sorted(words, key=lambda w: (w["t0"], w["t1"]))


def words_for_line(line: dict, stream: list[dict], pad_s: float = 0.15) -> list[dict] | None:
    """[{w, s, e, src}] for the SHEET line's tokens, matched monotonically to the whisper words
    inside [start-pad, end+pad]; unmatched tokens interpolate between their matched neighbours
    (src 'interp', visibly tagged). None when no whisper word is in reach → the page falls back
    to a linear split and says so."""
    import vocal_brief as vb
    start, end = line.get("start"), line.get("end")
    if start is None or end is None:
        return None
    tokens = [t for t in re.sub(r"\([^)]*\)", "", line.get("text", "")).split() if t.strip()]
    if not tokens:
        return None
    cand = [w for w in stream if float(start) - pad_s <= w["t0"] <= float(end) + pad_s]
    if not cand:
        return None
    norm_tokens = [vb.norm_latin(vb.transliterate(t) if re.search(r"[ऀ-ॿ]", t) else t) for t in tokens]
    out: list[dict | None] = [None] * len(tokens)
    cursor = 0
    for i, nt in enumerate(norm_tokens):
        best, best_j, best_r = -1.0, -1, 0.0
        for j in range(cursor, len(cand)):
            r = difflib.SequenceMatcher(None, nt, cand[j]["lat"]).ratio() if nt and cand[j]["lat"] else 0.0
            # NEAR THE CURSOR, NOT ANYWHERE AFTER IT (vocal_brief.align's rule): "Shri" at 0.68
            # once matched a later "shri" at 3.8 because it scored a shade higher, and every
            # word after it was interpolated into the wrong half of the line. A candidate pays
            # for each whisper word it skips.
            score = r - 0.04 * (j - cursor)
            # a short token needs a close match ("shri" vs "sudhar" scores 0.6 on three
            # letters and matched the LAST word of the line, so every word before it was
            # interpolated backwards); and a match that skips most of the line is worth
            # less than leaving the token to interpolate between its neighbours
            floor = 0.75 if len(nt) <= 4 else 0.55
            if r >= floor and score >= 0.5 and score > best:
                best, best_j, best_r = score, j, r
            if r >= 0.92:
                break
        if best_j >= 0:
            w = cand[best_j]
            e = float(w["t1"]) if w["t1"] > w["t0"] else float(w["t0"]) + 0.3
            out[i] = {"w": tokens[i], "s": round(float(w["t0"]), 3), "e": round(e, 3), "src": "whisper"}
            cursor = best_j + 1
    if not any(out):
        return None
    # interpolate the unmatched tokens between matched neighbours (line edges as anchors)
    anchors = [(-1, float(start), float(start))] + [(i, o["s"], o["e"]) for i, o in enumerate(out) if o] + [(len(tokens), float(end), float(end))]
    for k in range(len(anchors) - 1):
        (i0, _, e0), (i1, s1, _) = anchors[k], anchors[k + 1]
        gap = list(range(i0 + 1, i1))
        if not gap:
            continue
        span = max(0.05, s1 - e0)
        for n, idx in enumerate(gap):
            s = e0 + span * n / len(gap)
            e = e0 + span * (n + 1) / len(gap)
            out[idx] = {"w": tokens[idx], "s": round(s, 3), "e": round(e, 3), "src": "interp"}
    # clamp: monotone, e <= next s
    res = [o for o in out if o]
    for a, b in zip(res, res[1:]):
        if a["e"] > b["s"]:
            a["e"] = b["s"]
    return res


# ---------------------------------------------------------------------------------------
# verdicts — read, never computed
# ---------------------------------------------------------------------------------------
def pill_class(verdict: str) -> str:
    v = (verdict or "").upper()
    if v in ("OK", "PASS", "KEEP", "KEPT", "ACCEPTED", "IN SYNC") or v.startswith("KEPT"):
        return "pass"
    if v in ("SLIDE", "RETIME", "EXEMPT", "ADVISORY") or "slide" in verdict.lower() or "retime" in verdict.lower():
        return "advisory"
    if v in ("WRONG-LYRIC", "RE-RENDER", "NO-TRANSCRIPT", "REJECTED", "FAIL", "NO-VOCAL") or "reject" in verdict.lower():
        return "fail"
    return "skip"


def file_stamp(path: str) -> dict:
    try:
        return {"file": os.path.relpath(path, os.path.dirname(os.path.dirname(path))), "mtime": os.path.getmtime(path)}
    except OSError:
        return {"file": path, "mtime": None}


def verdicts_for(build: str, wid: str, clip_mtime: float | None, styles: list[str], missing: list[dict]) -> list[dict]:
    out: list[dict] = []
    for sid in styles:
        for kind, fname, key in (("word-sync", f"word-sync-{sid}.json", "windows"), ("sync-profile", f"sync-profile-{sid}.json", "windows")):
            p = os.path.join(build, fname)
            doc = raplib.read_json(p)
            if doc is None:
                if not any(m["file"] == fname for m in missing):
                    missing.append({"file": fname, "role": f"{kind} verdicts ({sid})"})
                continue
            for row in doc.get(key) or []:
                clip = str(row.get("clip") or row.get("id") or "")
                if wid not in clip:
                    continue
                verdict = str(row.get("verdict") or row.get("status") or "?")
                st = file_stamp(p)
                out.append({"kind": kind, "style": sid, "verdict": verdict, "detail": row.get("note") or "",
                            "driftMs": row.get("driftMs"), "spreadMs": row.get("spreadMs"), "cls": pill_class(verdict),
                            "source": st, "stale": bool(clip_mtime and st["mtime"] and clip_mtime > st["mtime"])})
        sr = raplib.read_json(os.path.join(build, f"shift-report-{sid}.json"))
        if sr:
            for row in sr.get("shifted") or []:
                if wid in str(row.get("clip") or row.get("id") or ""):
                    out.append({"kind": "shift", "style": sid, "verdict": f"slid {row.get('shiftMs', row.get('shift', ''))} ms",
                                "detail": row.get("why") or "", "cls": "advisory", "source": file_stamp(os.path.join(build, f"shift-report-{sid}.json")), "stale": False})
    acc = raplib.read_json(os.path.join(build, "sync-accepts.json"))
    if acc:
        for k, v in (acc.items() if isinstance(acc, dict) else []):
            if k.startswith("_"):
                continue
            if wid in str(k):
                out.append({"kind": "accepted", "style": "", "verdict": "accepted by the operator", "detail": str(v)[:120], "cls": "advisory",
                            "source": file_stamp(os.path.join(build, "sync-accepts.json")), "stale": False})
    log = os.path.join(build, "lane-render.log")
    if os.path.isfile(log):
        try:
            from draws_review import parse_log, plain
            landed, draws, _ = parse_log(log)
            if wid in landed:
                txt = landed[wid]
                m = re.search(r"\((.*)\)\s*$", txt)
                v = m.group(1) if m else txt
                try:
                    v = plain(v)
                except Exception:   # noqa: BLE001
                    pass
                out.append({"kind": "driver", "style": "", "verdict": v[:160], "detail": "", "cls": pill_class(v), "source": file_stamp(log), "stale": False})
            rej = [d for (j, n), d in draws.items() if j == wid]
            if rej:
                out.append({"kind": "draws", "style": "", "verdict": f"{len(rej)} rejected draw(s)", "detail": rej[-1][:160], "cls": "skip", "source": file_stamp(log), "stale": False})
        except Exception:   # noqa: BLE001 — a log the parser cannot read is not a verdict
            pass
    return out


# ---------------------------------------------------------------------------------------
def collect(project: str, styles: list[str], windows: set[str] | None, no_master: bool) -> dict:
    build = os.path.join(project, "build")
    out_dir = os.path.join(build, OUT_DIR)
    slug = os.path.basename(project.rstrip("/"))
    missing: list[dict] = []
    warnings: list[str] = []
    plan = raplib.read_json(os.path.join(build, "plan.json"))
    brief = raplib.read_json(os.path.join(build, "vocal-brief.json"))
    hook = raplib.read_json(os.path.join(build, "hook.json")) or {}
    song_seconds = float(hook.get("durationSec") or raplib.probe_seconds(os.path.join(build, "hook.wav")) or 0.0)
    mode = raplib.audio_mode(plan)
    front_pad = None
    cards = os.path.join(build, "bookends", "cards.json")
    if os.path.isfile(cards):
        try:
            front_pad = raplib.front_padding(cards)
        except Exception:   # noqa: BLE001
            front_pad = None
    if plan is None:
        missing.append({"file": "plan.json", "role": "the windows and their clocks"})
    if brief is None:
        missing.append({"file": "vocal-brief.json", "role": "the sheet's lines on whisper's clock"})
    jobs = [j for j in (plan or {}).get("jobs", []) if str(j.get("id", "")).startswith("w")]
    if windows:
        jobs = [j for j in jobs if j["id"] in windows]
    if not styles:
        styles = sorted({str(j.get("styleId")) for j in jobs if j.get("styleId")})

    # audios
    audios = {}
    for key, rel, label in (("mix", "hook.wav", "the record (hook.wav)"),
                            ("instrumental", os.path.join("stems", "_demucs", "htdemucs", "hook", "no_vocals.wav"), "instrumental stem"),
                            ("vocals", os.path.join("stems", "vocals.wav"), "vocal stem")):
        p = os.path.join(build, rel)
        ok = os.path.isfile(p)
        audios[key] = {"src": rel if ok else None, "exists": ok, "label": label}
        if not ok:
            missing.append({"file": rel, "role": label})

    # videos
    videos: list[dict] = []
    fps = None
    stem_words = word_stream(build)
    singers = raplib.read_json(os.path.join(build, "singers.json"))
    singers_by_start = {}
    for row in (singers or {}).get("lines", []):
        try:
            singers_by_start[round(float(row.get("start", -1)), 1)] = row
        except (TypeError, ValueError):
            pass

    def add_video(kind: str, src: str, name: str, offset: float, offset_from: str, label: str, **extra) -> None:
        nonlocal fps
        if not os.path.isfile(src):
            return
        sil = make_silent(src, out_dir, name)
        own = extract_own_audio(src, out_dir, name) if sil["playable"] else None
        f = fps_of(src)
        if f and not fps:
            fps = f
        videos.append({"id": name, "kind": kind, "label": label, "src": os.path.relpath(sil["src"], build) if sil["src"] else None,
                       "clockOffsetSec": round(float(offset), 3), "offsetFrom": offset_from, "audioStreams": sil["audioStreams"],
                       "playable": sil["playable"], "reason": sil.get("reason"), "silentFrom": sil.get("silentFrom"),
                       "ownAudio": os.path.relpath(own, build) if own else None, "durationSec": raplib.probe_seconds(src), **extra})

    clips_dir = os.path.join(build, "queue", "explore", "clips")
    for j in jobs:
        wid = j["id"]
        take = os.path.join(clips_dir, f"{wid}.mp4")
        if os.path.isfile(take):
            add_video("take", take, f"take-{wid}", float(j.get("startSec") or 0.0), f"plan.json jobs.{wid}.startSec",
                      f"{wid} take as rendered (frame 0 = song {float(j.get('startSec') or 0):.2f} s)", window=wid,
                      facts={"trimStartSec": j.get("trimStartSec"), "muteHeadSec": j.get("muteHeadSec"), "tailSec": j.get("tailSec")},
                      slice=(os.path.relpath(j["voiceRef"], build) if j.get("voiceRef") and os.path.isfile(str(j["voiceRef"])) else None))
        else:
            missing.append({"file": os.path.relpath(take, build), "role": f"{wid} take"})
    for sid in styles:
        sel = raplib.read_json(os.path.join(build, f"selection-{sid}.json"))
        if sel:
            clips = {c.get("id"): c for c in sel.get("clips") or [] if isinstance(c, dict)}
            for vm in sel.get("vocalMap") or []:
                pc = vm.get("performerClip")
                c = clips.get(pc)
                if c and c.get("path") and os.path.isfile(c["path"]) and (not windows or any(w in str(pc) for w in windows)):
                    wid = next((w for w in (j["id"] for j in jobs) if w in str(pc)), str(pc))
                    add_video("take-in-film", c["path"], f"cut-{wid}-{sid}", float(vm.get("start") or 0.0),
                              f"selection-{sid}.json vocalMap.start", f"{wid} as cut in {sid}", window=wid, style=sid)
        if not no_master:
            try:
                from master_version import existing_versions
                vers = existing_versions(project, slug, sid)
            except Exception:   # noqa: BLE001
                vers = []
            if vers:
                n, path = vers[-1]
                dur = raplib.probe_seconds(path)
                if song_seconds and abs(dur - song_seconds) > 0.5:
                    warnings.append(f"master {sid} v{n} runs {dur:.1f} s but the song is {song_seconds:.1f} s — the master may carry bookends or a different cut; its clock offset of 0 is not proven, check before trusting it")
                add_video("master", path, f"master-{sid}-v{n}", 0.0, "master (the body starts at song 0)", f"master {sid} v{n} (body, song clock)", style=sid)
    if not videos and jobs:
        missing.append({"file": os.path.relpath(clips_dir, build), "role": "any take or master to play"})

    # sections
    sections: list[dict] = []
    brief_windows = {w.get("id"): w for w in (brief or {}).get("windows", [])}
    brief_lines = (brief or {}).get("lines", [])
    for j in jobs:
        wid = j["id"]
        start = float(j.get("startSec") or 0.0) + float(j.get("trimStartSec") or 0.0)
        end = start + float(j.get("sungSec") or j.get("seconds") or 0.0)
        bw = brief_windows.get(wid) or {}
        lines = []
        for sp in bw.get("spans") or []:
            ln = next((l for l in brief_lines if l.get("start") is not None and abs(float(l["start"]) - float(sp.get("absStart", -9))) < 0.05 and l.get("text") == sp.get("text")), None)
            src = ln or {"text": sp.get("text", ""), "start": sp.get("absStart"), "end": (float(sp.get("absStart", 0)) + float(sp.get("end", 0)) - float(sp.get("start", 0))) if sp.get("absStart") is not None else None, "who": sp.get("who"), "how": sp.get("how")}
            words = words_for_line(src, stem_words)
            srow = singers_by_start.get(round(float(src.get("start") or -1), 1))
            lines.append({"text": src.get("text", ""), "who": src.get("who"), "whoFrom": (ln or {}).get("whoFrom") or ("singers.json" if srow else None),
                          "how": src.get("how"), "tag": (ln or {}).get("tag"), "start": src.get("start"), "end": src.get("end"),
                          "timing": "whisper" if words else "linear", "words": words})
        who = j.get("performer")
        first = lines[0] if lines else {}
        take = os.path.join(clips_dir, f"{wid}.mp4")
        clip_mtime = os.path.getmtime(take) if os.path.isfile(take) else None
        refs = {}
        for key, name in (("identityRef", "keyframe"), ("identityRef2", "portrait")):
            p = j.get(key) or ((plan or {}).get("identityRef") if key == "identityRef2" else None)
            if p and os.path.isfile(str(p)):
                refs[name] = os.path.relpath(p, build)
        sections.append({"id": wid, "start": round(start, 3), "end": round(end, 3), "performer": who, "who": first.get("who") or "",
                         "whoFrom": first.get("whoFrom"), "how": first.get("how"), "tag": first.get("tag"), "styleId": j.get("styleId"),
                         "mode": bw.get("mode"), "coverage": bw.get("coverage"), "kind": j.get("kind"), "refs": refs,
                         "verdicts": ([{"kind": "mode", "style": "", "verdict": "vocal-swap: sync is by construction; no record-vs-take verdict exists", "cls": "skip", "source": {"file": "plan.json", "mtime": None}, "stale": False}]
                                      if mode == "vocal-swap" else verdicts_for(build, wid, clip_mtime, styles, missing)),
                         "lines": lines})
    return {"schemaVersion": 1, "slug": slug, "generatedAt": raplib.__dict__.get("now", lambda: None)() or __import__("time").strftime("%Y-%m-%dT%H:%M:%S"),
            "audioMode": mode, "songSeconds": round(song_seconds, 3), "fps": fps or 24, "frontPadSec": front_pad, "whisperFloorMs": WHISPER_FLOOR_MS,
            "styles": styles, "videos": videos, "audios": audios, "sections": sections,
            "missing": [m for i, m in enumerate(missing) if m not in missing[:i]], "warnings": warnings}


# ---------------------------------------------------------------------------------------
def render(data: dict, lib_js: str) -> str:
    def esc(s) -> str:
        return html.escape(str(s))
    videos = data["videos"]
    opts = "".join(f'<option value="{esc(v["id"])}"{"" if v["playable"] else " disabled"}>{esc(v["label"])}{"" if v["playable"] else " — not playable"}</option>' for v in videos)
    faders = []
    for key, label, default in (("mix", "record", 100), ("instrumental", "instrumental", 0), ("vocals", "vocal stem", 0), ("own", "take's own voice", 0)):
        a = data["audios"].get(key)
        present = (a and a["exists"]) or key == "own"
        faders.append(f'<label class="fader{"" if present else " off"}"><span>{esc(label)}</span>'
                      f'<input type="range" min="0" max="100" value="{default if present else 0}" data-fader="{key}"{"" if present else " disabled"}>'
                      f'{"" if present else "<small>not on disk yet</small>"}</label>')
    audio_tags = "".join(f'<audio id="au-{k}" preload="auto" src="{esc(a["src"])}"></audio>' for k, a in data["audios"].items() if a["exists"])
    audio_tags += '<audio id="au-own" preload="auto" hidden></audio>'
    warn_html = ("".join(f'<div class="warn-box">{esc(w)}</div>' for w in data["warnings"])) if data["warnings"] else ""
    missing_html = ("<details class=card><summary>Not on disk yet — " + str(len(data["missing"])) + " thing(s) this page would show</summary><ul>"
                    + "".join(f"<li><code>{esc(m['file'])}</code> — {esc(m['role'])}</li>" for m in data["missing"]) + "</ul></details>") if data["missing"] else ""
    rows = []
    for s in data["sections"]:
        pills = " ".join(f'<span class="pill {esc(v["cls"])}" title="{esc(v["source"]["file"])}">{esc(v["kind"])}: {esc(v["verdict"])}{" (STALE)" if v.get("stale") else ""}</span>' for v in s["verdicts"]) or '<span class="pill skip">not on disk yet</span>'
        who = esc(s["who"] or "—") + (' <small class=muted>verified by ear</small>' if s.get("whoFrom") == "singers.json" else (' <small class=muted>sheet tag (unverified)</small>' if s["who"] else ""))
        lines = "".join(f'<div class="ln">{esc(l["text"])}' + (' <span class="pill skip">linear</span>' if l["timing"] == "linear" else "") + "</div>" for l in s["lines"]) or '<div class="ln muted">no lines placed in this window</div>'
        rows.append(f'<tr data-start="{s["start"]}"><td class=mono>{esc(s["id"])}<br><small>{s["start"]:.2f}–{s["end"]:.2f} s</small></td>'
                    f'<td>{who}<br><small class=muted>{esc(s.get("how") or "")} {esc(s.get("tag") or "")}</small></td><td>{lines}</td><td>{pills}</td></tr>')
    body = f"""
{warn_html}{missing_html}
<section class="player card">
  <div class="row"><label>picture <select id="source">{opts}</select></label> <span id="source-facts" class="muted"></span></div>
  <video id="video" muted playsinline preload="metadata"></video>
  {audio_tags}
  <div class="row controls"><button id="play">Play</button> <span id="clock-song" class="clock"></span> <span id="clock-film" class="clock"></span> <span id="drift" class="muted mono"></span> <span id="hint" class="muted"></span></div>
  <div class="row faders">{''.join(faders)}</div>
  <canvas id="timeline" title="click to seek"></canvas>
  <div id="hud" class="hud">
    <div class="hud-row"><span id="section-badge" class="pill"></span> <span id="who" class="who"></span> <span id="verdicts"></span></div>
    <div id="lyric" class="lyric"></div>
    <div class="hud-row"><span id="refs" class="refs"></span><span id="next-up" class="muted"></span></div>
  </div>
  <p class="muted small">Keys: space/K play·pause · J/L ∓10 s · ←/→ one frame ({data['fps']} fps). Word timing is whisper's, ±{data['whisperFloorMs']} ms; an <em>interp</em> word is interpolated between matched neighbours; <em>linear</em> means no whisper word was in reach for that line. Mode: <b>{esc(data['audioMode'])}</b>.</p>
</section>
<table id="sections"><thead><tr><th>window</th><th>who</th><th>lines (click a row to seek)</th><th>verdicts as written on disk</th></tr></thead><tbody>{''.join(rows)}</tbody></table>
<script type="application/json" id="sync-review-data">{json.dumps(data, ensure_ascii=False).replace('</', '<\\/')}</script>
<script>{lib_js}</script>
<script>
(function(){{
  var data = JSON.parse(document.getElementById('sync-review-data').textContent);
  var $ = function(id){{ return document.getElementById(id); }};
  var audios = {{}};
  ['mix','instrumental','vocals'].forEach(function(k){{ var a = $('au-'+k); if (a) audios[k] = a; }});
  var faders = {{}};
  document.querySelectorAll('[data-fader]').forEach(function(f){{ faders[f.getAttribute('data-fader')] = f; }});
  SyncPlayer.attach({{ data: data, els: {{ video: $('video'), audios: audios, ownAudio: $('au-own'), sourceSelect: $('source'), sourceFacts: $('source-facts'),
    playBtn: $('play'), clockSong: $('clock-song'), clockFilm: $('clock-film'), drift: $('drift'), hint: $('hint'), faders: faders, timeline: $('timeline'),
    hud: $('hud'), who: $('who'), sectionBadge: $('section-badge'), verdicts: $('verdicts'), refs: $('refs'), lyric: $('lyric'), nextUp: $('next-up'), sectionList: $('sections') }} }});
}})();
</script>"""
    css = """
.player video{width:100%;max-height:56vh;background:#000;display:block;margin:8px 0}
.row{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin:6px 0}.controls button{font:inherit;padding:6px 14px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--ink);cursor:pointer}
.faders{gap:18px}.fader{display:flex;flex-direction:column;font-size:12px;color:var(--ink2)}.fader input{width:140px}.fader.off{opacity:.5}.fader small{color:var(--ink3)}
#timeline{width:100%;height:44px;display:block;background:var(--panel2);border-radius:6px;cursor:pointer;margin:8px 0}
.hud{border-top:1px solid var(--line);padding-top:8px}.hud-row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:4px 0}.who{font-weight:700}
.lyric{font-size:22px;line-height:1.5;margin:8px 0;min-height:1.6em}.w{opacity:.45}.w.past{color:var(--danger);opacity:.85}.w.now{color:var(--accent);font-weight:800;text-decoration:underline;opacity:1}.w.next{color:var(--ink2)}.w.interp{font-style:italic}
.refs img{height:64px;border-radius:6px;border:1px solid var(--line);margin-right:6px}
.warn-box{background:rgba(216,85,106,.16);border:1px solid var(--danger);color:var(--ink);border-radius:10px;padding:10px 14px;margin:8px 0}
#sections tr[data-start]{cursor:pointer}#sections tr[data-start]:hover{background:var(--panel)}.ln{margin:2px 0}.mono{font-family:ui-monospace,monospace}.small{font-size:12px}
"""
    return page("Sync review — does the mouth match the record?",
                f"The picture is silent; choose what to hear. {len(data['sections'])} windows · mode {esc(data['audioMode'])} · verdicts are read from disk, never computed here.",
                body, slug=data.get("slug", ""), extra_css=css)


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--style", action="append", default=[])
    ap.add_argument("--windows", default="", help="comma-separated wNN subset")
    ap.add_argument("--out", default="")
    ap.add_argument("--json", default="")
    ap.add_argument("--no-master", action="store_true")
    ap.add_argument("--open", action="store_true", help="hand use only: open the page when written")
    a = ap.parse_args()
    project = os.path.abspath(a.project)
    if not os.path.isdir(project):
        say(f"--project is not a directory: {project}")
        return 2
    build = os.path.join(project, "build")
    os.makedirs(build, exist_ok=True)
    windows = {w.strip() for w in a.windows.split(",") if w.strip()} or None
    data = collect(project, [s for s in a.style if s], windows, a.no_master)
    lib_js = open(LIB_JS, encoding="utf-8").read()
    out = a.out or os.path.join(build, "sync-review.html")
    with open(out, "w", encoding="utf-8") as fh:
        fh.write(render(data, lib_js))
    jpath = a.json or os.path.join(build, "sync-review.json")
    raplib.write_json_atomic(jpath, data)
    try:
        from lane_nav import inject_nav
        inject_nav(out)
    except Exception:   # noqa: BLE001 — the menu is a convenience
        pass
    say(f"{len(data['videos'])} picture source(s), {len(data['sections'])} window(s), {len(data['missing'])} thing(s) not on disk → {out}")
    if a.open and sys.platform == "darwin":
        subprocess.run(["open", out], check=False)
    return 0


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