"""Voice input — local STT using Faster-Whisper.

Captures audio from the microphone, transcribes locally (no cloud),
and returns the text for DSL parsing or LLM forwarding.

Requires optional dependencies::

    pip install faster-whisper sounddevice numpy
"""

from __future__ import annotations

import structlog

logger = structlog.get_logger()


class VoiceListener:
    """Local STT: microphone → text via Faster-Whisper.

    Parameters
    ----------
    model_size : str
        Whisper model size. ``"small"`` (244 MB) is a good balance of
        quality and speed for Polish + English.
    language : str
        Primary language for transcription hints.
    """

    def __init__(self, model_size: str = "small", language: str = "pl") -> None:
        try:
            from faster_whisper import WhisperModel
        except ImportError:
            raise ImportError(
                "Voice input requires faster-whisper: pip install faster-whisper sounddevice numpy"
            )

        self.language = language
        logger.info("voice_loading_model", model_size=model_size)
        self.model = WhisperModel(model_size, device="cpu", compute_type="int8")
        logger.info("voice_model_ready", model_size=model_size)

    def listen_once(self, duration: float = 5.0, sample_rate: int = 16000) -> str:
        """Record audio for *duration* seconds and transcribe.

        Returns
        -------
        str
            Transcribed text (may be empty on silence).
        """
        import numpy as np
        import sounddevice as sd

        print("\033[33m🎤 Słucham...\033[0m")
        audio = sd.rec(
            int(duration * sample_rate),
            samplerate=sample_rate,
            channels=1,
            dtype=np.float32,
        )
        sd.wait()

        segments, info = self.model.transcribe(
            audio.flatten(), language=self.language,
        )
        text = " ".join(s.text for s in segments).strip()
        logger.debug("voice_transcribed", text=text, language=info.language)
        return text

    def listen_continuous(self, duration: float = 5.0):
        """Generator that yields transcribed phrases indefinitely.

        Yields
        ------
        str
            Each transcribed phrase (skips empty/silence).
        """
        while True:
            text = self.listen_once(duration=duration)
            if text:
                yield text
