import logging

from .auth import get_auth_context
from .config import get_account_url

logger = logging.getLogger("iis_access")


async def report_usage(
    service: str,
    credits: float = 0,
    requests: int = 1,
) -> None:
    """
    Fire-and-forget usage report to iis-account.
    Never raises - logs warnings on failure.
    Skipped if not authenticated.
    """
    context = await get_auth_context()
    if context is None:
        return

    try:
        import aiohttp

        account_url = get_account_url()
        timeout = aiohttp.ClientTimeout(total=5)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            await session.post(
                f"{account_url}/usage/record",
                json={
                    "accountId": context.account_id,
                    "service": service,
                    "requests": requests,
                    "credits": credits,
                },
                headers={"Authorization": f"Bearer {context.access_token}"},
            )
    except Exception as e:
        logger.debug("Usage reporting failed (non-fatal): %s", e)
