"""Inverter audio filter — invert all audio levels (1.0 - value)."""

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 InverterFilter(AudioFilter):
    """Invert all audio levels: ``output = 1.0 - input``.

    When ``invert_spectrum`` is True (default), spectrum bins are also inverted.
    Beat fields (beat, beat_intensity) are always passed through unchanged.
    """

    filter_id = "inverter"
    filter_name = "Inverter"

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

    @classmethod
    def get_options_schema(cls) -> List[AudioFilterOptionDef]:
        return [
            AudioFilterOptionDef(
                key="invert_spectrum",
                label="Invert Spectrum",
                option_type="bool",
                default=True,
                min_value=None,
                max_value=None,
                step=None,
            ),
        ]

    def process(self, analysis: AudioAnalysis) -> AudioAnalysis:
        kwargs = {
            "rms": 1.0 - analysis.rms,
            "peak": 1.0 - analysis.peak,
            "left_rms": 1.0 - analysis.left_rms,
            "right_rms": 1.0 - analysis.right_rms,
        }

        if self._invert_spectrum:
            kwargs["spectrum"] = (1.0 - analysis.spectrum).astype(np.float32)
            kwargs["left_spectrum"] = (1.0 - analysis.left_spectrum).astype(np.float32)
            kwargs["right_spectrum"] = (1.0 - analysis.right_spectrum).astype(np.float32)

        return replace(analysis, **kwargs)
