"""Contrast postprocessing filter."""

from typing import Any, Dict, List, Optional

import numpy as np

from wled_controller.core.filters.base import FilterOptionDef, PostprocessingFilter
from wled_controller.core.filters.image_pool import ImagePool
from wled_controller.core.filters.registry import FilterRegistry


@FilterRegistry.register
class ContrastFilter(PostprocessingFilter):
    """Adjusts contrast around mid-gray (128) using a lookup table.

    value < 1.0 = reduced contrast (washed out)
    value = 1.0 = unchanged
    value > 1.0 = increased contrast (punchier)
    """

    filter_id = "contrast"
    filter_name = "Contrast"

    def __init__(self, options: Dict[str, Any]):
        super().__init__(options)
        value = self.options["value"]
        # LUT: output = clamp(128 + (input - 128) * value, 0, 255)
        lut = np.clip(128.0 + (np.arange(256, dtype=np.float32) - 128.0) * value, 0, 255)
        self._lut = lut.astype(np.uint8)

    @classmethod
    def get_options_schema(cls) -> List[FilterOptionDef]:
        return [
            FilterOptionDef(
                key="value",
                label="Contrast",
                option_type="float",
                default=1.0,
                min_value=0.0,
                max_value=3.0,
                step=0.05,
            ),
        ]

    def process_image(self, image: np.ndarray, image_pool: ImagePool) -> Optional[np.ndarray]:
        if self.options["value"] == 1.0:
            return None
        image[:] = self._lut[image]
        return None
