"""Frame-level voice activity detection (energy + spectral flatness).

Low energy alone is not treated as silence — broadband noise can be energetic
but spectrally flat; speech tends to have lower spectral flatness.
"""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np


@dataclass
class VadResult:
    frame_times: np.ndarray  # center time of each frame (seconds)
    is_speech: np.ndarray  # bool per frame
    speech_duration_seconds: float
    silence_duration_seconds: float
    silence_percentage: float
    pause_count: int
    pause_durations_seconds: list[float]
    long_pause_count: int
    method: str


def _frame_signal(
    y: np.ndarray, sr: int, *, frame_ms: float, hop_ms: float
) -> tuple[np.ndarray, np.ndarray]:
    import librosa

    frame_len = max(1, int(sr * frame_ms / 1000.0))
    hop_len = max(1, int(sr * hop_ms / 1000.0))
    y = np.ascontiguousarray(y, dtype=np.float64)
    if len(y) < frame_len:
        frames = y.reshape(1, -1)
        times = np.array([0.5 * len(y) / sr])
        return frames, times
    framed = librosa.util.frame(y, frame_length=frame_len, hop_length=hop_len)
    # librosa returns (frame_len, n_frames)
    frames = framed.T.copy()
    times = (np.arange(frames.shape[0]) * hop_len + frame_len / 2) / float(sr)
    return frames, times


def _spectral_flatness(frame: np.ndarray, eps: float = 1e-12) -> float:
    # Real FFT magnitude flatness: geometric_mean / arithmetic_mean
    windowed = frame * np.hanning(len(frame))
    mag = np.abs(np.fft.rfft(windowed)) + eps
    geo = np.exp(np.mean(np.log(mag)))
    arith = np.mean(mag)
    return float(geo / arith) if arith > 0 else 1.0


def detect_speech_activity(
    y: np.ndarray,
    sr: int,
    *,
    frame_ms: float = 25.0,
    hop_ms: float = 10.0,
    energy_percentile: float = 30.0,
    flatness_speech_max: float = 0.55,
    min_speech_ms: float = 80.0,
    min_pause_ms: float = 200.0,
    long_pause_ms: float = 1500.0,
) -> VadResult:
    """Return speech/silence segmentation using RMS + spectral flatness."""
    y = np.asarray(y, dtype=np.float64)
    duration = len(y) / float(sr) if sr else 0.0
    if duration <= 0 or len(y) == 0:
        return VadResult(
            frame_times=np.array([]),
            is_speech=np.array([], dtype=bool),
            speech_duration_seconds=0.0,
            silence_duration_seconds=0.0,
            silence_percentage=0.0,
            pause_count=0,
            pause_durations_seconds=[],
            long_pause_count=0,
            method="energy_spectral_flatness",
        )

    frames, times = _frame_signal(y, sr, frame_ms=frame_ms, hop_ms=hop_ms)
    rms = np.sqrt(np.mean(frames**2, axis=1) + 1e-12)
    flatness = np.array([_spectral_flatness(f) for f in frames])

    # Adaptive energy floor: speech frames need energy above percentile floor
    floor = float(np.percentile(rms, energy_percentile))
    # Absolute floor guards near-digital-silence
    abs_floor = max(floor, 1e-4)

    speech = (rms >= abs_floor) & (flatness <= flatness_speech_max)

    # If almost everything looks like noise (high flatness), fall back to energy-only
    # with a higher floor so we don't invent speech from white noise.
    if float(np.mean(flatness)) > 0.7 and float(np.mean(speech)) > 0.8:
        speech = rms >= max(float(np.percentile(rms, 60)), abs_floor)

    hop_sec = hop_ms / 1000.0
    min_speech_frames = max(1, int(min_speech_ms / hop_ms))
    # Morphological open: remove short speech blips
    speech = _remove_short_runs(speech, min_speech_frames, target=True)

    speech_dur = float(np.sum(speech) * hop_sec)
    # Clamp to recording duration
    speech_dur = min(speech_dur, duration)
    silence_dur = max(0.0, duration - speech_dur)
    silence_pct = (100.0 * silence_dur / duration) if duration > 0 else 0.0

    pauses = _pause_durations(~speech, hop_sec, min_pause_ms / 1000.0)
    long_pause_sec = long_pause_ms / 1000.0
    long_count = sum(1 for p in pauses if p >= long_pause_sec)

    return VadResult(
        frame_times=times,
        is_speech=speech,
        speech_duration_seconds=round(speech_dur, 4),
        silence_duration_seconds=round(silence_dur, 4),
        silence_percentage=round(silence_pct, 2),
        pause_count=len(pauses),
        pause_durations_seconds=[round(p, 4) for p in pauses],
        long_pause_count=long_count,
        method="energy_spectral_flatness",
    )


def _remove_short_runs(mask: np.ndarray, min_len: int, *, target: bool) -> np.ndarray:
    out = mask.copy()
    n = len(out)
    i = 0
    while i < n:
        if out[i] != target:
            i += 1
            continue
        j = i
        while j < n and out[j] == target:
            j += 1
        if (j - i) < min_len:
            out[i:j] = not target
        i = j
    return out


def _pause_durations(
    silence_mask: np.ndarray, hop_sec: float, min_pause_sec: float
) -> list[float]:
    pauses: list[float] = []
    n = len(silence_mask)
    i = 0
    while i < n:
        if not silence_mask[i]:
            i += 1
            continue
        j = i
        while j < n and silence_mask[j]:
            j += 1
        dur = (j - i) * hop_sec
        if dur >= min_pause_sec:
            pauses.append(dur)
        i = j
    return pauses
