#!/usr/bin/env python3
"""Render the STT-01 script with open-source TTS voices (Kokoro-82M, Apache-2.0, via kokoro-onnx) into
  - mix.flac               : all speakers on one track (upload/import tests, bot-free capture tests)
  - track_<SPEAKER>.flac   : one track per speaker, same length, silence when the speaker is not talking
                             (each track is played into its own Zoom participant, so tools see 4 real participants)
  - timeline.json, reference.rttm (speaker diarization ground truth), render_manifest.json (hashes, model, voices, seed)
SYNTHETIC VOICES: any result produced from this audio must be labelled "scripted meeting, synthetic (TTS) voices".
Run with the TTS venv:  python3 render_tts.py [--limit N] [--speed 0.95] [--out audio_tts_v0.1]
"""
import argparse, hashlib, json, os, random, re
from pathlib import Path
import numpy as np, soundfile as sf
from kokoro_onnx import Kokoro

D = Path(__file__).resolve().parent
MODEL_DIR = Path(os.environ.get("KOKORO_DIR", "./kokoro"))  # folder with the Kokoro-82M ONNX model + voices file; check sha256 against render_manifest.json
VOICES = {"MAYA": "af_heart", "DANIEL": "am_michael", "PRIYA": "bf_emma", "TOMAS": "bm_george"}   # US-F, US-M, UK-F, UK-M
SAY = {"IPX6": "I P X six", "USB-C": "U S B C", "go/no-go": "go, no-go", "Beacon 2": "Beacon two", "Beacon 1": "Beacon one", "micro-USB": "micro U S B", "FAQ": "F A Q"}

def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def spoken(text):
    for k, v in SAY.items(): text = text.replace(k, v)
    return text

def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--limit", type=int); ap.add_argument("--speed", type=float, default=0.95)
    ap.add_argument("--seed", type=int, default=20261008); ap.add_argument("--out", default="audio_tts_v0.1")
    a = ap.parse_args()
    turns = json.loads((D / "turns.json").read_text())[: a.limit]
    k = Kokoro(str(MODEL_DIR / "kokoro-v1.0.onnx"), str(MODEL_DIR / "voices-v1.0.bin"))
    rng = random.Random(a.seed); sr = None; segs = []; t = 0.8
    for tr in turns:
        audio, sr = k.create(spoken(tr["text"]), voice=VOICES[tr["speaker"]], speed=a.speed, lang="en-us" if VOICES[tr["speaker"]].startswith("a") else "en-gb")
        audio = np.asarray(audio, dtype=np.float32)
        segs.append(dict(turn=tr["turn"], speaker=tr["speaker"], start=round(t, 3), end=round(t + len(audio) / sr, 3), audio=audio))
        t += len(audio) / sr + rng.uniform(0.35, 0.9)
        print(f"{tr['turn']:03d} {tr['speaker']:<6} {segs[-1]['start']:8.2f}-{segs[-1]['end']:8.2f}", flush=True)
    n = int((t + 1.0) * sr)
    out = D / a.out; out.mkdir(exist_ok=True)
    tracks = {s: np.zeros(n, dtype=np.float32) for s in VOICES}
    for s in segs:
        i = int(s["start"] * sr); tracks[s["speaker"]][i:i + len(s["audio"])] += s["audio"]
    mix = sum(tracks.values()); peak = float(np.max(np.abs(mix))) or 1.0; g = 0.89 / peak
    sf.write(out / "mix.flac", mix * g, sr)
    for s, x in tracks.items(): sf.write(out / f"track_{s}.flac", x * g, sr)
    timeline = [{k2: v for k2, v in s.items() if k2 != "audio"} for s in segs]
    (out / "timeline.json").write_text(json.dumps(timeline, indent=1))
    (out / "reference.rttm").write_text("".join(f"SPEAKER STT-01 1 {s['start']:.3f} {s['end'] - s['start']:.3f} <NA> <NA> {s['speaker']} <NA> <NA>\n" for s in timeline))
    files = sorted(p.name for p in out.iterdir() if p.name != "render_manifest.json")
    man = dict(task="STT-01", synthetic_voices=True, tts="Kokoro-82M v1.0 via kokoro-onnx (Apache-2.0)", voices=VOICES, speed=a.speed, seed=a.seed,
               turns=len(segs), duration_s=round(n / sr, 2), sample_rate=sr, gain=g, model_sha256=sha(MODEL_DIR / "kokoro-v1.0.onnx"),
               voices_sha256=sha(MODEL_DIR / "voices-v1.0.bin"), script_sha256=sha(D / "script.txt"), say_overrides=SAY,
               files={f: sha(out / f) for f in files},
               disclosure="Scripted meeting voiced by synthetic TTS voices (no real people). Results must be labelled as such and never mixed with human-recording results.",
               verification="REQUIRED before use: one person listens to mix.flac with reference_transcript.txt and logs any skipped or misread words in listen_check.md.")
    (out / "render_manifest.json").write_text(json.dumps(man, indent=1))
    print(f"duration {n / sr / 60:.1f} min -> {out}")

if __name__ == "__main__":
    main()
