"""
faster-whisper STT service configuration.

Model: large-v3 (GPU accelerated)
Languages: Chinese (primary), English (auto-detect)
"""

import numpy as np


class WhisperSTTService:
    """Speech-to-Text service using faster-whisper."""

    def __init__(self, model: str = "base", device: str = "cpu", language: str = "zh"):
        self.model_name = model
        self.device = device
        self.language = language
        self._model = None

    async def initialize(self):
        """Load the Whisper model."""
        from faster_whisper import WhisperModel

        compute_type = "float16" if self.device == "cuda" else "int8"
        try:
            self._model = WhisperModel(
                self.model_name, device=self.device, compute_type=compute_type
            )
        except Exception as e:
            print(f"Failed to load Whisper model on {self.device}: {e}")
            if self.device != "cpu":
                self._model = WhisperModel(
                    self.model_name, device="cpu", compute_type="int8"
                )

    async def transcribe(self, audio_data: bytes) -> str:
        """Transcribe audio to text."""
        audio_np = np.frombuffer(audio_data, dtype=np.int16).astype(np.float32) / 32768.0

        segments, _ = self._model.transcribe(
            audio_np,
            language=self.language,
            beam_size=5,
            vad_filter=True,
        )

        text = "".join(segment.text for segment in segments)
        return text
