"""@handler decorator for class-based agents."""
from __future__ import annotations

from typing import Any, Callable


def handler(message_type: type) -> Callable:
    """Decorator to register a method as a handler for a message type."""
    def decorator(fn: Callable) -> Callable:
        fn._logos_handler_type = message_type
        return fn
    return decorator


def collect_handlers(instance: Any) -> dict[type, Callable]:
    """Collect all @handler-decorated methods from an instance.

    Raises:
        TypeError: If two methods handle the same message type.
    """
    handlers: dict[type, Callable] = {}
    for name in dir(instance):
        if name.startswith("_"):
            continue
        attr = getattr(instance, name, None)
        if attr is None or not callable(attr):
            continue
        msg_type = getattr(attr, "_logos_handler_type", None)
        if msg_type is not None:
            if msg_type in handlers:
                raise TypeError(
                    f"duplicate handler for {msg_type.__name__}: "
                    f"{handlers[msg_type].__name__} and {name}"
                )
            handlers[msg_type] = attr
    return handlers
