"""Registry for game integration adapters.

Follows the EngineRegistry pattern from capture_engines/factory.py:
class-level dict, register/get/list methods, clear for testing.
"""

from typing import Type

from wled_controller.core.game_integration.base_adapter import GameAdapter
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class AdapterRegistry:
    """Registry of available game adapters.

    Maintains a mapping of adapter_type strings to GameAdapter subclasses.
    All methods are classmethods operating on shared class-level state.
    """

    _adapters: dict[str, Type[GameAdapter]] = {}

    @classmethod
    def register(cls, adapter_class: Type[GameAdapter]) -> None:
        """Register a game adapter class.

        Args:
            adapter_class: Must be a subclass of GameAdapter.

        Raises:
            ValueError: If not a GameAdapter subclass or has reserved type.
        """
        if not (isinstance(adapter_class, type) and issubclass(adapter_class, GameAdapter)):
            raise ValueError(f"{adapter_class} must be a subclass of GameAdapter")

        adapter_type = adapter_class.ADAPTER_TYPE
        if adapter_type == "base":
            raise ValueError("Cannot register adapter with reserved type 'base'")

        if adapter_type in cls._adapters:
            logger.warning(f"Adapter '{adapter_type}' already registered, overwriting")

        cls._adapters[adapter_type] = adapter_class
        logger.info(f"Registered game adapter: {adapter_type}")

    @classmethod
    def get_adapter(cls, adapter_type: str) -> Type[GameAdapter]:
        """Look up an adapter class by type.

        Args:
            adapter_type: Adapter type identifier.

        Returns:
            The adapter class.

        Raises:
            ValueError: If the adapter type is not registered.
        """
        if adapter_type not in cls._adapters:
            available = ", ".join(cls._adapters.keys()) or "none"
            raise ValueError(f"Unknown adapter type: '{adapter_type}'. Available: {available}")
        return cls._adapters[adapter_type]

    @classmethod
    def get_all_adapters(cls) -> dict[str, Type[GameAdapter]]:
        """Return all registered adapters (copy).

        Returns:
            Dict mapping adapter_type to adapter class.
        """
        return dict(cls._adapters)

    @classmethod
    def get_available_adapters(cls) -> list[dict]:
        """Return metadata for all registered adapters.

        Returns:
            List of dicts with adapter_type, display_name, game_name,
            supported_events for each registered adapter.
        """
        result = []
        for adapter_type, adapter_class in cls._adapters.items():
            result.append(
                {
                    "adapter_type": adapter_type,
                    "display_name": adapter_class.DISPLAY_NAME,
                    "game_name": adapter_class.GAME_NAME,
                    "supported_events": list(adapter_class.SUPPORTED_EVENTS),
                }
            )
        return result

    @classmethod
    def clear_registry(cls) -> None:
        """Clear all registered adapters (for testing)."""
        cls._adapters.clear()
        logger.debug("Cleared adapter registry")
