"""Filter registry for discovering and instantiating postprocessing filters."""

from typing import Dict, Type

from wled_controller.core.filters.base import PostprocessingFilter
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class FilterRegistry:
    """Singleton registry of all available postprocessing filter types."""

    _filters: Dict[str, Type[PostprocessingFilter]] = {}

    @classmethod
    def register(cls, filter_cls: Type[PostprocessingFilter]) -> Type[PostprocessingFilter]:
        """Register a filter class. Can be used as a decorator."""
        filter_id = filter_cls.filter_id
        if not filter_id:
            raise ValueError(f"Filter class {filter_cls.__name__} must define filter_id")
        if filter_id in cls._filters:
            logger.warning(f"Overwriting filter registration for '{filter_id}'")
        cls._filters[filter_id] = filter_cls
        logger.debug(f"Registered filter: {filter_id} ({filter_cls.__name__})")
        return filter_cls

    @classmethod
    def get(cls, filter_id: str) -> Type[PostprocessingFilter]:
        """Get a filter class by ID.

        Raises:
            ValueError: If filter_id is not registered.
        """
        if filter_id not in cls._filters:
            raise ValueError(f"Unknown filter type: '{filter_id}'")
        return cls._filters[filter_id]

    @classmethod
    def get_all(cls) -> Dict[str, Type[PostprocessingFilter]]:
        """Get all registered filter types."""
        return dict(cls._filters)

    @classmethod
    def create_instance(cls, filter_id: str, options: dict) -> PostprocessingFilter:
        """Create a filter instance from a filter_id and options dict."""
        filter_cls = cls.get(filter_id)
        return filter_cls(options)

    @classmethod
    def is_registered(cls, filter_id: str) -> bool:
        """Check if a filter ID is registered."""
        return filter_id in cls._filters
