"""Automatic rate-limit handling for HTTP responses.

Inspects ``429`` responses and transparently waits before re-raising so
that callers can use the retry utility to recover.
"""

from __future__ import annotations

from openhedge.exceptions import RateLimitError


def extract_retry_after(headers: dict) -> float:
    """Parse ``Retry-After`` from response headers.

    Returns the number of seconds to wait, defaulting to **1.0** if the
    header is absent or unparseable.
    """
    raw = headers.get("retry-after") or headers.get("Retry-After")
    if raw is None:
        return 1.0
    try:
        return float(raw)
    except (ValueError, TypeError):
        return 1.0


def check_rate_limit(status_code: int, headers: dict) -> None:
    """Raise :class:`RateLimitError` if the response signals a 429.

    This helper is meant to be called right after receiving an HTTP response
    so that the retry middleware can catch the exception and wait.
    """
    if status_code == 429:
        retry_after = extract_retry_after(headers)
        raise RateLimitError(retry_after=retry_after)
