"""
ElevenLabs STT implementation.

Usage:
    from rehearse.audio.stt import ElevenLabsSTT

    stt = ElevenLabsSTT(api_key="your-api-key")
    text = stt.transcribe(audio_bytes)
"""

import logging
import os
import tempfile
import wave

from elevenlabs import ElevenLabs

from .base import BaseSTT

logger = logging.getLogger(__name__)


class ElevenLabsSTT(BaseSTT):
    """
    ElevenLabs STT provider using Scribe model.

    Usage:
        stt = ElevenLabsSTT(api_key="your-api-key")
        text = stt.transcribe(audio_bytes)
    """

    def __init__(self, api_key: str, language_code: str = "en"):
        """
        Create an ElevenLabs STT instance.

        Args:
            api_key: Your ElevenLabs API key
            language_code: Language code for transcription (default: "en")
        """
        self.api_key = api_key
        self.language_code = language_code
        self.client = ElevenLabs(api_key=api_key)

    def transcribe(self, audio: bytes, sample_rate: int = 24000) -> str:
        """
        Transcribe PCM16 audio to text.

        Args:
            audio: PCM16 audio bytes
            sample_rate: Sample rate of the audio

        Returns:
            Transcribed text
        """
        if not audio:
            logger.debug("No audio to transcribe")
            return ""

        logger.debug("Transcribing %d bytes of audio", len(audio))

        # ElevenLabs needs a WAV file
        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
            temp_path = f.name

            with wave.open(f, "wb") as wav:
                wav.setnchannels(1)
                wav.setsampwidth(2)
                wav.setframerate(sample_rate)
                wav.writeframes(audio)

        try:
            with open(temp_path, "rb") as audio_file:
                result = self.client.speech_to_text.convert(
                    file=audio_file,
                    model_id="scribe_v1",
                    language_code=self.language_code,
                )
            logger.debug("Transcription result: %s", result.text)
            return result.text
        finally:
            os.unlink(temp_path)
