from __future__ import annotations

from typing import Any, Callable, Dict, List

_REGISTRY: Dict[str, Callable[..., Any]] = {}


def register_encoder(name: str, factory: Callable[..., Any]) -> None:
    """Register an encoder factory under ``name``.

    The factory is a callable that returns a ``MemoryEncoder`` when invoked.
    Registering the same name again overwrites the previous entry.
    """

    key = str(name).lower()
    _REGISTRY[key] = factory


def get_encoder(name: str) -> Callable[..., Any]:
    """Retrieve a registered encoder factory by name.

    Raises ``KeyError`` if ``name`` is unknown.
    """

    key = str(name).lower()
    if key not in _REGISTRY:
        available = ", ".join(sorted(_REGISTRY)) or "<empty>"
        raise KeyError(f"unknown encoder '{name}'. Available: {available}")
    return _REGISTRY[key]


def list_encoders() -> List[str]:
    """Return the list of registered encoder names."""

    return sorted(_REGISTRY.keys())


__all__ = ["register_encoder", "get_encoder", "list_encoders"]
