"""Base handler for chain of responsibility pattern."""

import asyncio
from abc import ABC, abstractmethod
from typing import Any


class BaseHandler(ABC):
    def __init__(self) -> None:
        self._next_handler: BaseHandler | None = None

    def set_next(self, handler: "BaseHandler") -> "BaseHandler":
        self._next_handler = handler
        return handler

    @abstractmethod
    async def handle(self, request: Any, context: dict[str, Any] | None = None) -> Any:
        if self._next_handler:
            return await self._next_handler.handle(request, context)
        return None

    def handle_sync(self, request: Any, context: dict[str, Any] | None = None) -> Any:
        return asyncio.run(self.handle(request, context))

    def __repr__(self) -> str:
        next_handler_name = type(self._next_handler).__name__ if self._next_handler else "None"
        return f"{type(self).__name__}(next_handler={next_handler_name})"

    def get_chain_info(self) -> str:
        chain_info = [type(self).__name__]
        current_handler = self._next_handler
        while current_handler:
            chain_info.append(type(current_handler).__name__)
            current_handler = current_handler._next_handler
        return " -> ".join(chain_info)
