"""
ElevenLabs TTS implementation.

Usage:
    from rehearse.audio.tts import ElevenLabsTTS

    tts = ElevenLabsTTS(api_key="your-api-key")
    audio = tts.synthesize("Hello world")
"""

import logging
from io import BytesIO

from elevenlabs import ElevenLabs

from .base import BaseTTS

logger = logging.getLogger(__name__)

# Default voice ID (Rachel - calm, natural)
DEFAULT_VOICE_ID = "21m00Tcm4TlvDq8ikWAM"


class ElevenLabsTTS(BaseTTS):
    """
    ElevenLabs TTS provider.

    Usage:
        tts = ElevenLabsTTS(api_key="your-api-key")
        audio = tts.synthesize("Hello world")
    """

    def __init__(
        self,
        api_key: str,
        voice_id: str = DEFAULT_VOICE_ID,
        model_id: str = "eleven_turbo_v2_5",
    ):
        """
        Create an ElevenLabs TTS instance.

        Args:
            api_key: Your ElevenLabs API key
            voice_id: Voice ID to use (default: Rachel)
            model_id: Model to use (default: eleven_turbo_v2_5)
        """
        self.api_key = api_key
        self.voice_id = voice_id
        self.model_id = model_id
        self.client = ElevenLabs(api_key=api_key)

    def synthesize(self, text: str) -> bytes:
        """
        Convert text to PCM16 audio at 24kHz.

        Args:
            text: Text to convert to speech

        Returns:
            PCM16 audio bytes at 24kHz
        """
        logger.debug("Synthesizing text: %s", text[:50] + "..." if len(text) > 50 else text)
        audio_generator = self.client.text_to_speech.convert(
            voice_id=self.voice_id,
            text=text,
            model_id=self.model_id,
            output_format="pcm_24000",
        )

        audio_data = BytesIO()
        for chunk in audio_generator:
            audio_data.write(chunk)

        result = audio_data.getvalue()
        logger.debug("Synthesized %d bytes of audio", len(result))
        return result
