"""Transcription entry point. Routers call this, never a provider directly."""

from __future__ import annotations

import logging

from app.services.ai.providers.base import (
    AI_AUDIO_UNSUPPORTED,
    TranscriptionError,
)
from app.services.ai.registry import get_transcription_provider

logger = logging.getLogger("coachpapa.ai")

# What a browser MediaRecorder actually produces: Chrome/Android emit webm,
# iOS Safari emits mp4. Both are accepted upstream.
SUPPORTED_AUDIO_MIME = {
    "audio/webm",
    "audio/ogg",
    "audio/mp4",
    "audio/mpeg",
    "audio/wav",
    "audio/x-m4a",
}


def normalise_audio_mime(raw: str) -> str:
    """Strip codec parameters: MediaRecorder sends 'audio/webm;codecs=opus'."""
    return (raw or "").split(";")[0].strip().lower()


def is_configured() -> bool:
    return get_transcription_provider().is_configured()


async def transcribe(audio: bytes, mime: str) -> str:
    """Transcribe one recording. Raises TranscriptionError on failure."""
    normalised = normalise_audio_mime(mime)
    if normalised not in SUPPORTED_AUDIO_MIME:
        raise TranscriptionError(
            AI_AUDIO_UNSUPPORTED,
            f"{normalised or 'that audio format'} cannot be transcribed.",
            "Record with the in-app recorder, or type the description.",
        )

    provider = get_transcription_provider()
    text = await provider.transcribe(audio, normalised)
    # Entity-free logging: how much audio and which provider, never the
    # content and never the key (coding.md).
    logger.info(
        "transcribed %d bytes of %s via %s -> %d chars",
        len(audio),
        normalised,
        provider.name,
        len(text),
    )
    return text
