"""Pixelate postprocessing filter."""

from typing import List, Optional

import cv2
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 PixelateFilter(PostprocessingFilter):
    """Pixelates the image by averaging blocks of pixels."""

    filter_id = "pixelate"
    filter_name = "Pixelate"

    @classmethod
    def get_options_schema(cls) -> List[FilterOptionDef]:
        return [
            FilterOptionDef(
                key="block_size",
                label="Block Size",
                option_type="int",
                default=8,
                min_value=2,
                max_value=64,
                step=1,
            ),
        ]

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

        h, w = image.shape[:2]

        # Resize down (area averaging) then up (nearest neighbor) —
        # vectorized C++ instead of per-block Python loop
        small_w = max(1, w // block_size)
        small_h = max(1, h // block_size)
        small = cv2.resize(image, (small_w, small_h), interpolation=cv2.INTER_AREA)
        pixelated = cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)
        np.copyto(image, pixelated)

        return None
