"""
CatalogRegistry — maps catalog_type strings to CatalogConnector classes.

Wave 1 connectors are registered at module import time.
Wave 2 connectors register themselves only if their optional dependencies
are installed (handled by try/import in __init__.py).
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from .base import CatalogConnector

if TYPE_CHECKING:
    from autopil.models import CatalogConnection

logger = logging.getLogger(__name__)


class CatalogRegistry:
    """
    Central registry for catalog connector classes.

    Usage:
        CatalogRegistry.register(UnityCatalogConnector)
        connector = CatalogRegistry.get_connector(connection)
        types = CatalogRegistry.supported_types()
    """

    _registry: dict[str, type[CatalogConnector]] = {}

    @classmethod
    def register(cls, connector_class: type[CatalogConnector]) -> None:
        """Register a connector class by its catalog_type."""
        if not hasattr(connector_class, "catalog_type"):
            raise TypeError(
                f"{connector_class.__name__} must define a 'catalog_type' ClassVar"
            )
        cls._registry[connector_class.catalog_type] = connector_class
        logger.debug("Registered catalog connector: %s", connector_class.catalog_type)

    @classmethod
    def get_connector(cls, connection: CatalogConnection) -> CatalogConnector:
        """
        Instantiate and return the connector for a given CatalogConnection.

        Raises ValueError if no connector is registered for the catalog_type.
        """
        klass = cls._registry.get(connection.catalog_type)
        if klass is None:
            supported = ", ".join(cls._registry) or "(none installed)"
            raise ValueError(
                f"No connector registered for catalog_type='{connection.catalog_type}'. "
                f"Supported types: {supported}. "
                f"Install the matching extra: pip install autopil[catalog-{connection.catalog_type.replace('_', '-')}]"
            )
        return klass(connection)

    @classmethod
    def supported_types(cls) -> list[str]:
        """Return the list of registered catalog_type strings."""
        return sorted(cls._registry)

    @classmethod
    def get(cls, catalog_type: str) -> type[CatalogConnector] | None:
        """Return the connector class for catalog_type, or None if not registered."""
        return cls._registry.get(catalog_type)

    @classmethod
    def is_supported(cls, catalog_type: str) -> bool:
        return catalog_type in cls._registry
