"""Addon type registry.

Built-in addon types (postgres, redis) register themselves here.
The SDK uses get_addon_def() to look up the definition for a given type.
"""

from __future__ import annotations

import importlib.metadata
import warnings

from kuberoku.addons._types import AddonDef
from kuberoku.addons.postgres import POSTGRES
from kuberoku.addons.redis import REDIS
from kuberoku.branding import TOOL_NAME
from kuberoku.exceptions import AddonTypeNotSupportedError

# Registry: type_name -> AddonDef
ADDON_REGISTRY: dict[str, AddonDef] = {}

# Built-in types (protected from plugin override)
_BUILTIN_TYPES: set[str] = set()


def register(addon_def: AddonDef) -> None:
    """Register an addon type."""
    ADDON_REGISTRY[addon_def.type_name] = addon_def


def get_addon_def(type_name: str) -> AddonDef:
    """Look up an addon definition by type name.

    Raises AddonTypeNotSupportedError if the type is not registered.
    """
    if type_name not in ADDON_REGISTRY:
        available = ", ".join(sorted(ADDON_REGISTRY.keys()))
        raise AddonTypeNotSupportedError(
            f"Addon type '{type_name}' is not supported. Available types: {available}"
        )
    return ADDON_REGISTRY[type_name]


def _register_builtins() -> None:
    """Register built-in addon types (called at import time)."""
    register(POSTGRES)
    register(REDIS)
    _BUILTIN_TYPES.update({"postgres", "redis"})


def _discover_addon_plugins() -> None:
    """Discover addon plugins via entry_points group 'kuberoku.addons'."""
    eps = importlib.metadata.entry_points(group=f"{TOOL_NAME}.addons")
    for ep in eps:
        if ep.name in _BUILTIN_TYPES:
            warnings.warn(
                f"Addon plugin '{ep.name}' conflicts with built-in type. Skipped.",
                stacklevel=2,
            )
            continue
        try:
            addon_def: AddonDef = ep.load()
            register(addon_def)
        except Exception:
            warnings.warn(
                f"Failed to load addon plugin '{ep.name}'.",
                stacklevel=2,
            )


_register_builtins()
_discover_addon_plugins()

__all__ = [
    "ADDON_REGISTRY",
    "AddonDef",
    "get_addon_def",
    "register",
]
