"""Downscaler 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 DownscalerFilter(PostprocessingFilter):
    """Downscales image by a factor. Returns a new image from the pool."""

    filter_id = "downscaler"
    filter_name = "Downscaler"
    supports_strip = False

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

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

        h, w = image.shape[:2]
        new_h = max(1, int(h * factor))
        new_w = max(1, int(w * factor))

        if new_h == h and new_w == w:
            return None

        downscaled = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)

        result = image_pool.acquire(new_h, new_w, image.shape[2] if image.ndim == 3 else 3)
        np.copyto(result, downscaled)
        return result
