# Standalone Voxtral realtime STT test — validates the STT leg WITHOUT Telnyx or a phone call.
# Feed it a 16-bit mono WAV; it streams the audio to Voxtral realtime and prints the transcript.
#
#   MISTRAL_API_KEY=... python test_stt.py path/to/speech-16k-mono.wav
#
# Tip: make a test WAV from any audio with ffmpeg:
#   ffmpeg -i input.mp3 -ac 1 -ar 16000 -sample_fmt s16 speech-16k-mono.wav

import asyncio
import os
import sys
import wave

from mistralai.client import Mistral
from mistralai.client.models import AudioFormat

MODEL = os.environ.get("VOXTRAL_MODEL", "voxtral-mini-transcribe-realtime-2602")


async def main(path: str) -> None:
    api_key = os.environ.get("MISTRAL_API_KEY")
    if not api_key:
        sys.exit("Set MISTRAL_API_KEY")

    wf = wave.open(path, "rb")
    if wf.getsampwidth() != 2 or wf.getnchannels() != 1:
        sys.exit("Need a 16-bit mono WAV (use: ffmpeg -i in -ac 1 -ar 16000 -sample_fmt s16 out.wav)")
    sr = wf.getframerate()
    frames = wf.readframes(wf.getnframes())
    chunk = max(2, sr * 2 // 50)  # ~20ms chunks

    client = Mistral(api_key=api_key)

    async def audio_iter():
        for i in range(0, len(frames), chunk):
            yield frames[i : i + chunk]
            await asyncio.sleep(0.02)  # pace at ~real-time

    print(f"[test] streaming {path} ({sr}Hz) to Voxtral...\n", flush=True)
    async for ev in client.audio.realtime.transcribe_stream(
        audio_stream=audio_iter(),
        model=MODEL,
        audio_format=AudioFormat(encoding="pcm_s16le", sample_rate=sr),
        target_streaming_delay_ms=480,
    ):
        t = getattr(ev, "type", None)
        if t == "transcription.text.delta":
            print(getattr(ev, "text", None) or getattr(ev, "delta", "") or "", end="", flush=True)
        elif t == "transcription.done":
            print("\n\n[done]", flush=True)
        elif t == "error":
            print(f"\n[ERROR] {ev}", flush=True)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit("usage: python test_stt.py <16k-mono.wav>")
    asyncio.run(main(sys.argv[1]))
