"""OpenAI Whisper transcription (stateless; bill seconds on success only)."""
from __future__ import annotations

import io
import math
from typing import Optional, Tuple

from openai import AsyncOpenAI


async def transcribe_audio_bytes(
    *,
    api_key: str,
    audio_bytes: bytes,
    filename: str,
    language: Optional[str] = None,
    model: str = "whisper-1",
) -> Tuple[str, float]:
    """Return (text, duration_seconds). Raises ``ValueError`` for silent / empty speech."""
    if not api_key.strip():
        raise RuntimeError("OpenAI API key is not configured")
    client = AsyncOpenAI(api_key=api_key.strip())
    bio = io.BytesIO(audio_bytes)
    bio.name = filename or "audio.webm"
    kwargs = {"model": model, "file": bio}
    if language and str(language).strip().lower() not in ("auto", "detect", ""):
        kwargs["language"] = str(language).strip().lower()[:16]
    tr = await client.audio.transcriptions.create(
        **kwargs,
        response_format="verbose_json",
    )
    text = (getattr(tr, "text", None) or "").strip()
    duration = float(getattr(tr, "duration", None) or 0.0)
    if not text:
        raise ValueError("silent_audio")
    return text, duration
