"""Gain audio filter — multiply all levels by a configurable factor."""

from dataclasses import replace
from typing import Any, Dict, List

import numpy as np

from wled_controller.core.audio.analysis import AudioAnalysis
from wled_controller.core.audio.filters.base import AudioFilter, AudioFilterOptionDef
from wled_controller.core.audio.filters.registry import AudioFilterRegistry


@AudioFilterRegistry.register
class GainFilter(AudioFilter):
    """Multiply rms, peak, spectrum, and per-channel values by a factor.

    Values are clamped to [0, 1] for rms/peak scalars.
    Spectrum bins are clamped to [0, 1] as well.
    """

    filter_id = "gain"
    filter_name = "Gain"

    def __init__(self, options: Dict[str, Any]):
        super().__init__(options)
        self._factor = self.options["factor"]

    @classmethod
    def get_options_schema(cls) -> List[AudioFilterOptionDef]:
        return [
            AudioFilterOptionDef(
                key="factor",
                label="Gain Factor",
                option_type="float",
                default=1.0,
                min_value=0.1,
                max_value=10.0,
                step=0.1,
            ),
        ]

    def process(self, analysis: AudioAnalysis) -> AudioAnalysis:
        factor = self._factor
        if factor == 1.0:
            return analysis

        return replace(
            analysis,
            rms=min(1.0, analysis.rms * factor),
            peak=min(1.0, analysis.peak * factor),
            spectrum=np.clip(analysis.spectrum * factor, 0.0, 1.0).astype(np.float32),
            left_rms=min(1.0, analysis.left_rms * factor),
            left_spectrum=np.clip(analysis.left_spectrum * factor, 0.0, 1.0).astype(np.float32),
            right_rms=min(1.0, analysis.right_rms * factor),
            right_spectrum=np.clip(analysis.right_spectrum * factor, 0.0, 1.0).astype(np.float32),
        )
