"""Adapter registry — register and instantiate world adapters by name.

Usage::

    registry = AdapterRegistry()
    registry.register("mock", MockWorldAdapter)
    adapter = registry.get("mock", some_kwarg="value")
"""

from __future__ import annotations

import logging
from typing import Any

from infrastructure.world.interface import WorldInterface

logger = logging.getLogger(__name__)


class AdapterRegistry:
    """Name → WorldInterface class registry with instantiation."""

    def __init__(self) -> None:
        self._adapters: dict[str, type[WorldInterface]] = {}

    def register(self, name: str, cls: type[WorldInterface]) -> None:
        """Register an adapter class under *name*.

        Raises ``TypeError`` if *cls* is not a ``WorldInterface`` subclass.
        """
        if not (isinstance(cls, type) and issubclass(cls, WorldInterface)):
            raise TypeError(f"{cls!r} is not a WorldInterface subclass")
        if name in self._adapters:
            logger.warning("Overwriting adapter %r (was %r)", name, self._adapters[name])
        self._adapters[name] = cls
        logger.info("Registered world adapter: %s → %s", name, cls.__name__)

    def get(self, name: str, **kwargs: Any) -> WorldInterface:
        """Instantiate and return the adapter registered as *name*.

        Raises ``KeyError`` if *name* is not registered.
        """
        cls = self._adapters[name]
        return cls(**kwargs)

    def list_adapters(self) -> list[str]:
        """Return sorted list of registered adapter names."""
        return sorted(self._adapters)

    def __contains__(self, name: str) -> bool:
        return name in self._adapters

    def __len__(self) -> int:
        return len(self._adapters)
