"""
Silero VAD (Voice Activity Detection) service.

Used for:
- Detecting when user starts/stops speaking
- Enabling barge-in (interrupt TTS when user speaks)
"""

import torch
import numpy as np


class SileroVADService:
    """Voice Activity Detection using Silero VAD."""

    def __init__(self):
        self._model = None
        self._utils = None

    async def initialize(self):
        """Load Silero VAD model."""
        self._model, self._utils = torch.hub.load(
            repo_or_dir='snakers4/silero-vad',
            model='silero_vad',
            force_reload=False,
        )

    def detect_speech(self, audio_chunk: bytes) -> bool:
        """Detect if audio chunk contains speech."""
        audio_np = np.frombuffer(audio_chunk, dtype=np.int16).astype(np.float32) / 32768.0
        audio_tensor = torch.from_numpy(audio_np)

        confidence = self._model(audio_tensor, 16000).item()
        return confidence > 0.5
