
import asyncio
import logging

logger = logging.getLogger(__name__)


class AsyncTaskManager:

    def __init__(self):
        self.tasks = set()

    def create_task(self, coroutine, name=None):
        task = asyncio.create_task(
            coroutine,
            name=name
        )

        self.tasks.add(task)
        task.add_done_callback(self._task_completed)

        return task

    def _task_completed(self, task):
        self.tasks.discard(task)

        if task.cancelled():
            logger.info("Background task cancelled: %s", task.get_name())
            return

        exception = task.exception()

        if exception:
            logger.exception(
                "Background task failed: %s",
                task.get_name(),
                exc_info=(
                    type(exception),
                    exception,
                    exception.__traceback__
                )
            )
        else:
            logger.info("Background task completed: %s", task.get_name())

    async def cancel_all(self):
        tasks = list(self.tasks)

        for task in tasks:
            task.cancel()

        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)


task_manager = AsyncTaskManager()