"""Private helpers for disposing loop-bound httpx async clients."""

from __future__ import annotations

import asyncio
import logging

import httpx


async def _aclose_httpx_client(
    client: httpx.AsyncClient,
    *,
    recorded_loop: asyncio.AbstractEventLoop | None,
    logger: logging.Logger,
) -> None:
    """Close an httpx async client, tolerating stale closed-loop bindings."""

    try:
        await client.aclose()
    except RuntimeError as exc:
        if recorded_loop is None or not recorded_loop.is_closed() or "Event loop is closed" not in str(exc):
            raise
        logger.debug("Discarding httpx.AsyncClient bound to a closed event loop", exc_info=True)
