"""Transcribe a saved meeting PCM with code-switch auto-detect Whisper.

Waits for the requested model to finish downloading, transcribes the whole
recording with language=None (native Arabic+English code-switching), writes
a timestamped .md transcript next to the audio, and prints the path.

Usage: python tools/transcribe_meeting.py <pcm_path> [model_repo]
Raw int16 mono 16kHz PCM in, markdown transcript out.
"""
import sys
import time
from pathlib import Path

import numpy as np

PCM = sys.argv[1]
MODEL = sys.argv[2] if len(sys.argv) > 2 else "mlx-community/whisper-large-v3-mlx"
SR = 16000


def _try_load(model: str, audio: np.ndarray):
    import mlx_whisper
    return mlx_whisper.transcribe(
        audio, path_or_hf_repo=model, language=None, fp16=True,
        word_timestamps=False)


def main() -> None:
    audio = np.fromfile(PCM, dtype=np.int16).astype(np.float32) / 32768.0
    secs = len(audio) / SR
    print(f"[transcribe] {secs:.0f}s of audio from {PCM}")

    # model preference: requested → turbo → small (whatever loads)
    chain = [MODEL, "mlx-community/whisper-large-v3-turbo",
             "mlx-community/whisper-small-mlx"]
    result = None
    used = None
    for model in dict.fromkeys(chain):
        try:
            print(f"[transcribe] trying {model} …")
            result = _try_load(model, audio)
            used = model
            break
        except Exception as e:  # noqa: BLE001 — download not done / OOM → next
            print(f"[transcribe] {model} unavailable ({e}); trying next")
            continue
    if result is None:
        print("[transcribe] FAILED — no model available")
        sys.exit(1)

    lang = result.get("language", "?")
    text = result["text"].strip()
    stem = Path(PCM).with_suffix("")
    out = Path(f"{stem}_transcript.md")
    header = (f"# Meeting transcript\n\n"
              f"- audio: `{Path(PCM).name}` ({secs/60:.1f} min)\n"
              f"- model: {used} (auto-detect, code-switch)\n"
              f"- primary language detected: {lang}\n\n---\n\n")
    # segment-by-segment keeps it readable if segments exist
    segs = result.get("segments") or []
    if segs:
        body = "\n".join(s.get("text", "").strip() for s in segs if s.get("text"))
    else:
        body = text
    out.write_text(header + body + "\n", encoding="utf-8")
    print(f"[transcribe] DONE → {out}")
    print(f"[transcribe] model={used} lang={lang} chars={len(body)}")


if __name__ == "__main__":
    main()
