"""Observe reset allowances at the usage cadence, independently of redemption eligibility."""

import time

from codex_reset import _request, _reset_urls, try_auto_redeem


def _read_credits(url, headers, account_id, say):
    try:
        details = _request(url, headers)
        count = details.get("available_count")
        if type(count) is not int or not 0 <= count <= 1_000_000:
            raise ValueError("invalid reset allowance")
        return details, {"reset_credits_available": count,
                         "reset_credits_fetched_at": int(time.time())}
    except Exception as error:
        say(f"{account_id}: usage reset availability failed ({type(error).__name__})")
        return {}, {}


def refresh_reset_credits(account_dir, account_id, used_percent, usage, usage_url, headers, say, now,
                          threshold=None):
    """Read all accounts, share the GET with redemption, then read back after a mutation.

    Failed reads omit the count; neither an embedded summary nor subtraction proves
    the remaining allowance after another machine may have redeemed a credit.
    Disabling automatic redemption still permits this read-only telemetry.
    """
    list_url, _ = _reset_urls(usage_url)
    details, view = _read_credits(list_url, headers, account_id, say)
    extra = {} if threshold is None else {"threshold": threshold}
    result = try_auto_redeem(account_dir, account_id, used_percent, usage, usage_url,
                             headers, say, now, credit_details=details, **extra)
    if result.get("status") not in {"not_eligible", "cooldown", "no_credit", "error"}:
        _, view = _read_credits(list_url, headers, account_id, say)
    return result, view
