"""Tenacity retry decorators for sdkrouter network calls."""
from __future__ import annotations

from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential


def _is_transient(exc: BaseException) -> bool:
    """True for errors worth retrying: timeout, network, 429/5xx."""
    import httpx

    if isinstance(exc, (TimeoutError, ConnectionError, OSError)):
        return True
    if isinstance(exc, (httpx.TimeoutException, httpx.NetworkError)):
        return True
    if isinstance(exc, httpx.HTTPStatusError):
        return exc.response.status_code in {429, 500, 502, 503, 504}
    # openai SDK exceptions
    type_name = type(exc).__name__
    module = type(exc).__module__ or ""
    if "openai" in module and type_name in {
        "APIConnectionError",
        "APITimeoutError",
        "RateLimitError",
        "InternalServerError",
    }:
        return True
    # openai RateLimitError / InternalServerError via status_code attr
    status = getattr(exc, "status_code", None)
    if status in {429, 500, 502, 503, 504}:
        return True
    return False


api_retry = retry(
    retry=retry_if_exception(_is_transient),
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    reraise=True,
)

__all__ = ["api_retry"]
