"""STT vía Google Cloud Speech-to-Text (batch por utterance)."""

from __future__ import annotations

import asyncio
import logging

from voice.protocols import AudioFormat, SpeechToText, TranscriptResult

logger = logging.getLogger(__name__)


class GoogleSpeechToText(SpeechToText):
    provider_name = "google"

    def __init__(
        self,
        *,
        language_code: str = "es-AR",
        model: str = "default",
    ) -> None:
        self.language_code = language_code
        self.model = model
        self._client = None

    def _get_client(self):
        if self._client is None:
            from google.cloud import speech_v1 as speech

            self._client = speech.SpeechClient()
            self._speech = speech
        return self._client

    async def recognize(
        self,
        audio: bytes,
        *,
        audio_format: AudioFormat | None = None,
        language_code: str | None = None,
    ) -> TranscriptResult:
        fmt = audio_format or AudioFormat()
        lang = language_code or self.language_code
        if not audio:
            return TranscriptResult(text="", is_final=True)

        def _sync() -> TranscriptResult:
            from google.cloud import speech_v1 as speech

            client = self._get_client()
            encoding = (
                speech.RecognitionConfig.AudioEncoding.MULAW
                if fmt.encoding == "mulaw"
                else speech.RecognitionConfig.AudioEncoding.LINEAR16
            )
            config = speech.RecognitionConfig(
                encoding=encoding,
                sample_rate_hertz=fmt.sample_rate_hz,
                language_code=lang,
                model=self.model,
                enable_automatic_punctuation=True,
                audio_channel_count=fmt.channels,
            )
            response = client.recognize(
                config=config,
                audio=speech.RecognitionAudio(content=audio),
            )
            if not response.results:
                return TranscriptResult(text="", is_final=True)
            alt = response.results[0].alternatives[0]
            return TranscriptResult(
                text=(alt.transcript or "").strip(),
                is_final=True,
                confidence=float(alt.confidence) if alt.confidence else None,
            )

        try:
            return await asyncio.to_thread(_sync)
        except Exception:
            logger.exception("Google STT falló")
            raise
