"""Async task tracking and containment."""

from __future__ import annotations

import asyncio
import logging
from time import perf_counter

from bot.core.metrics import incr


logger = logging.getLogger("bobi.tasks")


async def run_guarded(name: str, coro, timeout: float | None = None):
    started = perf_counter()

    try:
        if timeout:
            result = await asyncio.wait_for(coro, timeout=timeout)
        else:
            result = await coro

        incr(f"task.success.{name}")
        return result

    except asyncio.TimeoutError:
        incr(f"task.timeout.{name}")

        logger.warning("Task timeout: %s exceeded %.1fs", name, timeout)
        return None

    except Exception:
        incr(f"task.failure.{name}")
        logger.exception("Task failure: %s", name)
        return None

    finally:
        elapsed = (perf_counter() - started) * 1000

        if elapsed >= 1000:
            logger.warning("Long-running task: %s took %.2f ms", name, elapsed)
