"""Transcribe audio to text using OpenAI Whisper API."""

import os
from pathlib import Path

import httpx

WHISPER_URL = "https://api.openai.com/v1/audio/transcriptions"

MIME_TYPES = {
    ".ogg": "audio/ogg",
    ".oga": "audio/ogg",
    ".mp3": "audio/mpeg",
    ".m4a": "audio/mp4",
    ".wav": "audio/wav",
    ".webm": "audio/webm",
}


async def handler(params: dict) -> dict:
    """Transcribe an audio file to text."""
    audio_file = params["audio_file"]
    language = params.get("language")

    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("OPENAI_API_KEY not set. Required for speech-to-text transcription.")

    audio_path = Path(audio_file)
    if not audio_path.exists():
        raise ValueError(f"Audio file not found: {audio_file}")

    mime = MIME_TYPES.get(audio_path.suffix.lower(), "audio/ogg")

    headers = {"Authorization": f"Bearer {api_key}"}
    data = {"model": "whisper-1"}
    if language:
        data["language"] = language

    async with httpx.AsyncClient(timeout=60) as client:
        with open(audio_path, "rb") as f:
            resp = await client.post(
                WHISPER_URL,
                headers=headers,
                data=data,
                files={"file": (audio_path.name, f, mime)},
            )

    if resp.status_code != 200:
        raise ValueError(f"Whisper API error ({resp.status_code}): {resp.text[:300]}")

    result = resp.json()
    text = result.get("text", "").strip()

    if not text:
        raise ValueError("Whisper API returned empty transcription.")

    return {
        "text": text,
        "language": language or result.get("language", "auto"),
    }
