"""Fire-and-forget background task management."""

from __future__ import annotations

import asyncio
import logging
from typing import Any

log = logging.getLogger(__name__)

_background_tasks: set[asyncio.Task[Any]] = set()


def fire_and_forget(
    coro: Any,
) -> asyncio.Task[Any]:
    """
    Schedule *coro* as a background task without blocking.
    """
    task = asyncio.create_task(coro)
    _background_tasks.add(task)

    def _on_done(t: asyncio.Task[Any]) -> None:
        _background_tasks.discard(t)
        if t.cancelled():
            return
        if exc := t.exception():
            log.warning("Background task failed: %s", exc)

    task.add_done_callback(_on_done)
    return task


async def drain() -> None:
    """
    Await all pending background tasks.
    """
    while _background_tasks:
        await asyncio.gather(*_background_tasks, return_exceptions=True)
