#!/usr/bin/env python3
"""slice_check.py — HEAR every voice slice before it is shown to the operator.

WHY. The contract page claimed, per window, which lines the slice carried; nobody had
listened. The operator did, and found a couplet cut in half, a line cut off at the
slice's end, and a silenced "next line" still listed as sung (2026-08-23: "this is the
stupid stuff you are showing me and not checking — this is the problem with you").

WHAT. For every window that carries a voice reference, transcribe the SLICE ITSELF
(whisper, word timestamps, in the song's language) and compare with the card:
  * the last word heard begins within the card's last sung line — nothing cut off,
    nothing extra past it;
  * no word is heard inside the silenced head/tail;
  * the heard text covers the card's lines (consonant-skeleton alignment, the same
    measure the driver uses for a take).
Writes `build/slice-check.json`; the contract page shows "heard ✓ …" or the mismatch.
A mismatch is a refusal: the page is not shown as correct.

Usage:
  slice_check.py --plan build/plan.json --contract build/submit-contract.json
                 --out build/slice-check.json [--language hi] [--model small]
"""
from __future__ import annotations

import argparse
import json
import os
import sys

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


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


def transcribe(path: str, language: str, model: str,
               prompt: str | None = None) -> list[tuple[float, float, str]]:
    """Word-level transcript of a media file via the installed `whisper` CLI (cached by
    content hash under build/slice-check-tx/)."""
    from transcribe_clips import whisper_words  # the lane's own store (content-hashed, language-keyed)
    cache = os.path.join(os.path.dirname(os.path.abspath(path)), "..", "slice-check-tx")
    os.makedirs(cache, exist_ok=True)
    doc = whisper_words(path, model, cache, language=language, prompt=prompt)
    out = []
    for w in doc.get("words", []):
        t0 = float(w.get("t", w.get("t0", 0.0)))
        t1 = float(w.get("t1", w.get("end", t0)))
        out.append((t0, max(t1, t0), str(w.get("w", "")).strip()))
    return out


def _latin(word: str) -> str:
    """Heard words come back in the song's script; the card is romanised. Compare in one."""
    import re
    from vocal_brief import norm_latin, transliterate
    return norm_latin(transliterate(word) if re.search(r"[\u0900-\u097f]", word) else word)


def _similar(a: str, b: str) -> float:
    import difflib
    return difflib.SequenceMatcher(None, a, b).ratio()


def _is_silent(path: str, t0: float, t1: float | None, floor_db: float = -60.0) -> bool:
    """True when the media's audio between t0 and t1 peaks below floor_db."""
    import subprocess
    cmd = ["ffmpeg", "-v", "info", "-ss", f"{t0:.3f}"] + (["-t", f"{max(0.05, t1 - t0):.3f}"] if t1 else []) \
        + ["-i", path, "-vn", "-af", "volumedetect", "-f", "null", "-"]
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
    except Exception:                     # noqa: BLE001 — cannot prove silence: keep the words
        return False
    import re as _re
    m = _re.search(r"max_volume:\s*(-?[\d.]+) dB", r.stderr)
    return bool(m) and float(m.group(1)) <= floor_db


def check_window(job: dict, card: dict, language: str, model: str) -> dict:
    mh = float(job.get("muteHeadSec") or 0.0)
    mt = float(job.get("muteTailSec") or 0.0) or None
    sung = [sp for sp in card.get("sung", []) if sp.get("performer") and not sp["performer"].startswith("lips")
            and "next window" not in sp["performer"] and "silenced" not in sp["performer"]]
    # THE CARD PRIMES THE EAR. Whisper given the card's own lines as its initial prompt
    # hears a chanted "old era, old era" it otherwise wrote as "uh nuh nuh nuh" and
    # refused (New Era, 2026-08-30: two slices refused on hearing alone). A wrong slice
    # still fails: the prompt biases spelling, not which words are there or when.
    prompt = ". ".join(sp["text"] for sp in sung) if sung else None
    words = transcribe(job["voiceRef"], language, model, prompt=prompt)
    # A WORD HEARD IN DIGITAL SILENCE IS A HALLUCINATION. Primed with the chant's own
    # lines, whisper wrote "all the old era" into the muted tail of New Era's w00 —
    # the audio there measures -91 dB (2026-08-31). The mute bounds come from the plan;
    # when the file really is silent there (volumedetect), words inside are dropped and
    # noted rather than refusing a correct slice.
    dropped = []
    bounds = []
    if mh > 0:
        bounds.append((0.0, mh - 0.15))
    if mt:
        bounds.append((mt + 0.15, None))
    for lo, hi in bounds:
        inside = [w for w in words if w[0] >= lo and (hi is None or w[0] < hi)]
        if inside and _is_silent(job["voiceRef"], lo, hi):
            dropped += inside
            words = [w for w in words if w not in inside]
    out = {"id": job["id"], "words": len(words), "ok": True, "problems": []}
    if dropped:
        out["hallucinated"] = [w[2] for w in dropped]
    if not sung:
        out["note"] = "no sung lines on the card"
        return out
    last_expected = max(float(sp["end"]) for sp in sung)
    first_expected = min(float(sp["start"]) for sp in sung)
    if not words:
        out["ok"] = False
        out["problems"].append("nothing heard in the slice at all")
        return out
    # the store keeps word STARTS; "last heard" is the last word's onset
    first_heard, last_heard = words[0][0], words[-1][0]
    out.update({"firstHeard": round(first_heard, 2), "lastHeard": round(last_heard, 2),
                "firstExpected": round(first_expected, 2), "lastExpected": round(last_expected, 2)})
    heard = [_latin(w[2]) for w in words]
    card_words = [_latin(t) for t in " ".join(sp["text"] for sp in sung).replace(",", " ").split()]
    # CUT OFF? the card's last line's final word must be among the last few words heard
    # (a held final note makes "last heard start" a poor clock; the word itself is not)
    last_word = card_words[-1] if card_words else ""
    tail_heard = heard[-4:]
    found = max((_similar(last_word, h) for h in tail_heard), default=0.0)
    out["lastWordMatch"] = round(found, 2)
    last_line_start = max(float(sp["start"]) for sp in sung)
    # two ways to be cut off: no word heard after the last line BEGINS, or the last word
    # of the card not heard near the end ("haath" vs "baat" alone is too close to trust)
    if last_heard < last_line_start + 0.3:
        out["ok"] = False
        out["problems"].append(f"no word is heard after the card's last line begins ({last_line_start:.1f}s; "
                               f"last word heard at {last_heard:.1f}s) — a line is cut off")
    elif last_word and found < 0.5:
        out["ok"] = False
        out["problems"].append(f"the card's last word \u201c{last_word}\u201d is not heard at the end "
                               f"(heard \u201c{' '.join(tail_heard)}\u201d) — a line is cut off")
    # A LINE past the card is several words; ONE stray word over the instrumental after
    # the last line is whisper noise (primed with the card, it wrote one lyric word into
    # the 3 s gap after the New Era chant, 2026-08-30). Two or more words there is a line.
    past = [w for w in words if w[0] > last_expected + 0.5]
    if len(past) >= 2:
        out["ok"] = False
        out["problems"].append(f"words heard until {last_heard:.1f}s, past the card's last line ({last_expected:.1f}s) "
                               f"— the slice carries a line the card does not list")
    # whisper pins a first word to 0.0 s whatever the audio; a leak needs a real onset
    leak = [w for w in words if 0.15 < w[0] < mh - 0.15 or (mt is not None and w[0] > mt + 0.15)]
    if leak:
        out["ok"] = False
        out["problems"].append(f"{len(leak)} word(s) heard inside the silenced part "
                               f"(head {mh:.2f}s / tail {mt if mt is not None else '-'})")
    # the card's lines vs what was heard, romanised both, aligned as strings
    cov = _similar(" ".join(card_words), " ".join(heard)) if card_words else 1.0
    out["lineCoverage"] = round(cov, 2)
    if cov < 0.35:
        out["ok"] = False
        out["problems"].append(f"the words heard match only {cov:.0%} of the card's lines")
    out["heardText"] = " ".join(heard)[:300]
    return out


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--plan", required=True)
    ap.add_argument("--contract", required=True, help="submit-contract.json (its per-window sung lines)")
    ap.add_argument("--out", required=True)
    ap.add_argument("--language", default=os.environ.get("SONG_LANGUAGE") or "en")
    ap.add_argument("--model", default="small")
    ap.add_argument("--skip-on-disk", action="store_true", default=True,
                    help="windows whose clip is already on disk are not re-checked (default)")
    args = ap.parse_args()
    plan = json.load(open(args.plan, encoding="utf-8"))
    contract = json.load(open(args.contract, encoding="utf-8"))
    cards = {w["id"]: w for w in contract.get("windows", [])}
    results, bad = [], []
    for job in plan.get("jobs", []):
        if not job.get("voiceRef") or job["id"] not in cards:
            continue
        if args.skip_on_disk and cards[job["id"]].get("onDisk"):
            continue
        r = check_window(job, cards[job["id"]], args.language, args.model)
        results.append(r)
        say(f"{r['id']}: {'OK' if r['ok'] else 'MISMATCH'} — heard {r.get('firstHeard')}–{r.get('lastHeard')}s, "
            f"card {r.get('firstExpected')}–{r.get('lastExpected')}s, lines {r.get('lineCoverage')}"
            + ("; " + "; ".join(r["problems"]) if r["problems"] else ""))
        if not r["ok"]:
            bad.append(r["id"])
    json.dump({"schemaVersion": 1, "language": args.language, "model": args.model, "windows": results},
              open(args.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
    if bad:
        say(f"REFUSED — the slice does not match its card for: {', '.join(bad)}")
        raise SystemExit(4)
    say(f"every render slice carries exactly its card's lines ({len(results)} checked)")


if __name__ == "__main__":
    main()
