#!/usr/bin/env python3
"""Whisper on Apple silicon with MLX (mlx-whisper). Writes .txt and .srt.

    pip install mlx-whisper
    python3 scripts/transcribe_mlx.py lecture.m4a --model mlx-community/whisper-large-v3-turbo

Models download from the Hugging Face Hub on first use. mlx-whisper uses ffmpeg to
read audio, so install it first (brew install ffmpeg).
"""

from __future__ import annotations

import argparse
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from stt import Segment, split_long_segments, to_srt  # noqa: E402


def main(argv=None) -> int:
    p = argparse.ArgumentParser(description="Transcribe with mlx-whisper")
    p.add_argument("audio")
    p.add_argument("--model", default="mlx-community/whisper-large-v3-turbo")
    p.add_argument("--language", default=None)
    a = p.parse_args(argv)
    try:
        import mlx_whisper
    except ImportError:
        print("Install first: pip install mlx-whisper (Apple silicon only)", file=sys.stderr)
        return 2
    res = mlx_whisper.transcribe(a.audio, path_or_hf_repo=a.model, language=a.language, word_timestamps=True)
    segs = [Segment(s["start"], s["end"], s["text"].strip(),
                    [(w["start"], w["end"], w["word"]) for w in s.get("words", [])]) for s in res["segments"]]
    base = os.path.splitext(a.audio)[0]
    with open(base + ".txt", "w", encoding="utf-8") as f:
        f.write(res["text"].strip() + "\n")
    with open(base + ".srt", "w", encoding="utf-8") as f:
        f.write(to_srt(split_long_segments(segs)))
    print(f"wrote {base}.txt and {base}.srt")
    return 0


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