"""Language handler registry for multi-language support."""

from __future__ import annotations

from typing import TYPE_CHECKING

from .errors import LanguageNotFoundError

if TYPE_CHECKING:
    from collections.abc import Callable

    from .protocols import LanguageHandler


class LanguageRegistry:
    """Registry for language-specific handlers."""

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

    def register(self, language_id: str, handler: type[LanguageHandler]) -> None:
        """Register a handler for a language."""
        if language_id in self._handlers:
            existing = self._handlers[language_id]
            msg = (
                f"Handler for '{language_id}' already registered as {existing.__name__}. "
                f"Cannot register {handler.__name__}."
            )
            raise ValueError(msg)
        self._handlers[language_id] = handler

    def get_handler(self, language_id: str) -> type[LanguageHandler]:
        """Get the handler class for a language."""
        if language_id not in self._handlers:
            raise LanguageNotFoundError(language_id, self.list_available())
        return self._handlers[language_id]

    def list_available(self) -> list[str]:
        """List all registered language IDs."""
        return sorted(self._handlers.keys())


_registry = LanguageRegistry()
registry = _registry


def register_handler(language_id: str) -> Callable[[type[LanguageHandler]], type[LanguageHandler]]:
    """Register a language handler class via decorator."""

    def decorator(handler_class: type[LanguageHandler]) -> type[LanguageHandler]:
        _registry.register(language_id, handler_class)
        return handler_class

    return decorator
