import logging

from ..types.base import Action, Datatype, Event

logger = logging.getLogger(__name__)

_ACTIONS: dict[str, Action] = {}
_EVENTS: dict[str, Event] = {}
_DATA: dict[str, Datatype] = {}


def _norm(name: str) -> str:
    return (name or "").strip().lower()


def register_action(cls: Action) -> Action:
    key = _norm(cls.__name__)
    prev = _ACTIONS.get(key)
    _ACTIONS[key] = cls
    if prev and prev is not cls:
        logger.warning("Overwriting action '%s'", key)
    else:
        logger.debug("Registered action '%s'", key)
    return cls


def register_event(cls: Event) -> Event:
    key = _norm(cls.__name__)
    prev = _EVENTS.get(key)
    _EVENTS[key] = cls
    if prev and prev is not cls:
        logger.warning("Overwriting event '%s'", key)
    else:
        logger.debug("Registered event '%s'", key)
    return cls


def register_data(cls: Datatype) -> Datatype:
    key = _norm(cls.__name__)
    prev = _DATA.get(key)
    _DATA[key] = cls
    if prev and prev is not cls:
        logger.warning("Overwriting datatype '%s'", key)
    else:
        logger.debug("Registered datatype '%s'", key)
    return cls


def get_action(name: str) -> Action | None:
    return _ACTIONS.get(_norm(name))


def get_event(name: str) -> Event | None:
    return _EVENTS.get(_norm(name))


def get_data(name: str) -> Datatype | None:
    return _DATA.get(_norm(name))
