from typing import Callable, Coroutine, List
from core.logging import get_logger

logger = get_logger(__name__)


class LifecycleManager:
    """Manages application startup and shutdown hooks."""
    def __init__(self):
        self._startup_hooks: List[Callable[[], Coroutine]] = []
        self._shutdown_hooks: List[Callable[[], Coroutine]] = []

    def on_startup(self, func: Callable[[], Coroutine]) -> None:
        self._startup_hooks.append(func)

    def on_shutdown(self, func: Callable[[], Coroutine]) -> None:
        self._shutdown_hooks.append(func)

    async def execute_startup(self) -> None:
        for hook in self._startup_hooks:
            logger.info("executing_startup_hook", hook=hook.__name__)
            await hook()

    async def execute_shutdown(self) -> None:
        for hook in self._shutdown_hooks:
            logger.info("executing_shutdown_hook", hook=hook.__name__)
            try:
                await hook()
            except Exception as exc:
                logger.error("shutdown_hook_error", hook=hook.__name__, error=str(exc))
