"""Create a draft SRT from local audio using faster-whisper."""
import argparse
import wave
import numpy as np
from pathlib import Path
from faster_whisper import WhisperModel

def timestamp(seconds):
    total_ms = round(seconds * 1000)
    total_seconds, ms = divmod(total_ms, 1000)
    minutes, seconds = divmod(total_seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return f"{hours:02}:{minutes:02}:{seconds:02},{ms:03}"

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("audio", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--model", default="tiny", help="Model name or local CTranslate2 directory")
args = parser.parse_args()
if not args.audio.is_file() or args.output.exists():
    parser.error("Supply an existing input file and a new output filename")
model = WhisperModel(args.model, device="cpu", compute_type="int8", cpu_threads=2)
with wave.open(str(args.audio), "rb") as audio:
    if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) != (1, 2, 16000):
        parser.error("Use mono 16 kHz signed 16-bit PCM WAV")
    samples = np.frombuffer(audio.readframes(audio.getnframes()), dtype="<i2")
segments, _ = model.transcribe(samples.astype(np.float32) / 32768, language="en", beam_size=5)
cues = []
for segment in segments:
    text = " ".join(segment.text.split())
    if text and round(segment.end * 1000) > round(segment.start * 1000):
        cues.append(f"{len(cues)+1}\n{timestamp(segment.start)} --> "
                    f"{timestamp(segment.end)}\n{text}")
if not cues:
    raise SystemExit("No usable speech segments found.")
with args.output.open("x", encoding="utf-8") as out:
    out.write("\n\n".join(cues) + "\n")
print(f"{len(cues)} draft cues written to {args.output}")
