#!/usr/bin/env python3
"""whisper_stub.py — a `whisper` CLI that answers from a fixture's timeline, by LISTENING.

Installed on PATH as `whisper` for the fixture proofs (dryrun.sh --fixture). It takes
whisper's own arguments and writes whisper's own JSON (segments with word timestamps)
to --output_dir/<input stem>.json — so every caller in the lane (the map stage's CLI
call, transcribe_clips.whisper_words, the judge, the slice checks) is served without
knowing it is a stub.

It does not hallucinate and it does not cheat by file name: the pipeline hands it
content-keyed wavs and re-cut slices, so the stub decodes the input, finds WHERE in the
fixture's vocal track it came from by envelope cross-correlation, and returns the
fixture's words inside that span, shifted to the input's clock. A slice with no speech
correlates with nothing and gets no words — which is what a real transcriber returns.

Environment:  RAP_FIXTURE_VOCAL=<vocal-only wav>   RAP_FIXTURE_WORDS=<words.json>
"""
from __future__ import annotations

import json
import os
import subprocess
import sys

SR = 100          # envelope rate, Hz
MIN_CORR = 0.35   # below this the input is not a stretch of the fixture's voice


def pcm(path: str) -> "list[float]":
    r = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
                       capture_output=True)
    import array
    a = array.array("f"); a.frombytes(r.stdout)
    return list(a)


def envelope(x: "list[float]", sr: int = 16000) -> "list[float]":
    w = sr // SR
    n = len(x) // w
    return [sum(abs(v) for v in x[i * w:(i + 1) * w]) / w for i in range(n)]


def best_lag(ref: "list[float]", q: "list[float]") -> tuple[int, float]:
    """(lag in envelope frames, correlation) of q inside ref — plain numpy, no scipy."""
    import numpy as np
    r = np.asarray(ref, dtype=float); s = np.asarray(q, dtype=float)
    if len(s) < 5 or len(r) < len(s):
        return 0, 0.0
    s = (s - s.mean()); sd = float(np.sqrt((s * s).sum())) or 1.0
    best, arg = -1.0, 0
    # sliding normalised correlation over every lag
    win = len(s)
    cs = np.cumsum(np.insert(r, 0, 0.0)); cs2 = np.cumsum(np.insert(r * r, 0, 0.0))
    for lag in range(0, len(r) - win + 1):
        seg = r[lag:lag + win]
        mean = (cs[lag + win] - cs[lag]) / win
        var = (cs2[lag + win] - cs2[lag]) - win * mean * mean
        if var <= 1e-9:
            continue
        c = float(((seg - mean) * s).sum() / (np.sqrt(var) * sd))
        if c > best:
            best, arg = c, lag
    return arg, best


def main() -> int:
    argv = sys.argv[1:]
    if not argv:
        print("usage: whisper <audio> [--model M] [--output_dir D] [--language L] ...", file=sys.stderr); return 2
    media = argv[0]
    def opt(name: str, default: str = "") -> str:
        return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else default
    out_dir = opt("--output_dir", ".")
    vocal = os.environ.get("RAP_FIXTURE_VOCAL", ""); words_path = os.environ.get("RAP_FIXTURE_WORDS", "")
    if not (vocal and os.path.isfile(vocal) and words_path and os.path.isfile(words_path)):
        print("whisper_stub: RAP_FIXTURE_VOCAL / RAP_FIXTURE_WORDS not set — refusing to guess", file=sys.stderr); return 3
    words = json.load(open(words_path, encoding="utf-8"))["words"]
    ref = envelope(pcm(vocal)); x = pcm(media); q = envelope(x)
    dur = len(x) / 16000.0
    lag, corr = best_lag(ref, q)
    # a whole-song input (the mix, the stem) is the fixture itself: offset 0 regardless
    if abs(len(q) - len(ref)) <= 2 * SR:
        lag, corr = 0, 1.0
    t0 = lag / SR
    heard = [w for w in words if t0 <= float(w["t"]) < t0 + dur] if corr >= MIN_CORR else []
    seg_words = [{"word": " " + w["w"], "start": round(float(w["t"]) - t0, 3),
                  "end": round(max(float(w["t"]) - t0 + 0.05, float(w.get("end", w["t"])) - t0), 3),
                  "probability": 0.95} for w in heard]
    doc = {"text": " ".join(w["w"] for w in heard), "language": opt("--language", "en"),
           "stub": {"offset": round(t0, 3), "corr": round(corr, 3), "seconds": round(dur, 3)},
           "segments": ([{"id": 0, "start": seg_words[0]["start"], "end": seg_words[-1]["end"],
                          "text": " ".join(w["w"] for w in heard), "words": seg_words}] if seg_words else [])}
    stem = os.path.splitext(os.path.basename(media))[0]
    os.makedirs(out_dir, exist_ok=True)
    json.dump(doc, open(os.path.join(out_dir, stem + ".json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print(f"whisper_stub: {os.path.basename(media)} -> {len(heard)} word(s) at offset {t0:.2f}s (corr {corr:.2f})", file=sys.stderr)
    return 0


if __name__ == "__main__":
    sys.exit(main())
