"""TTS vía Google Cloud Text-to-Speech."""

from __future__ import annotations

import asyncio
import logging

from voice.protocols import AudioFormat, TextToSpeech
from voice.tts.sanitize import sanitize_for_tts

logger = logging.getLogger(__name__)


class GoogleTextToSpeech(TextToSpeech):
    provider_name = "google"

    def __init__(
        self,
        *,
        language_code: str = "es-US",
        voice_name: str = "es-US-Neural2-A",
        speaking_rate: float = 1.0,
    ) -> None:
        self.language_code = language_code
        self.voice_name = voice_name
        self.speaking_rate = speaking_rate
        self._client = None

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

            self._client = tts.TextToSpeechClient()
            self._tts = tts
        return self._client

    async def synthesize(
        self,
        text: str,
        *,
        audio_format: AudioFormat | None = None,
        voice: str | None = None,
        language_code: str | None = None,
    ) -> bytes:
        fmt = audio_format or AudioFormat(encoding="mulaw")
        lang = language_code or self.language_code
        voice_name = voice or self.voice_name
        clean = sanitize_for_tts(text)
        if not clean:
            return b""

        def _sync() -> bytes:
            from google.cloud import texttospeech_v1 as tts

            client = self._get_client()
            encoding = (
                tts.AudioEncoding.MULAW
                if fmt.encoding == "mulaw"
                else tts.AudioEncoding.LINEAR16
            )
            response = client.synthesize_speech(
                input=tts.SynthesisInput(text=clean),
                voice=tts.VoiceSelectionParams(
                    language_code=lang,
                    name=voice_name,
                ),
                audio_config=tts.AudioConfig(
                    audio_encoding=encoding,
                    sample_rate_hertz=fmt.sample_rate_hz,
                    speaking_rate=self.speaking_rate,
                ),
            )
            return response.audio_content or b""

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