"""Registry for declarative team subscription handlers."""
from __future__ import annotations

from typing import Any, Callable


class SubscriptionHandlerRegistry:
    """Global registry of named subscription handlers."""

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

    def register(self, name: str, handler: Any) -> None:
        """Register a handler under a stable name."""
        self._handlers[name] = handler

    def get(self, name: str) -> Any | None:
        """Get a handler by name."""
        return self._handlers.get(name)

    def list(self) -> list[str]:
        """List all registered handler names."""
        return sorted(self._handlers)

    def clear(self) -> None:
        """Remove all registered handlers."""
        self._handlers.clear()


subscription_handler_registry = SubscriptionHandlerRegistry()


def subscription_handler(name: str | None = None) -> Callable[[Any], Any]:
    """Decorator that registers a function as a subscription handler."""

    def decorator(fn: Any) -> Any:
        handler_name = name or getattr(fn, "__name__", None)
        if not isinstance(handler_name, str) or not handler_name:
            raise ValueError("subscription_handler name must be a non-empty string")
        subscription_handler_registry.register(handler_name, fn)
        return fn

    return decorator


__all__ = [
    "SubscriptionHandlerRegistry",
    "subscription_handler",
    "subscription_handler_registry",
]
