"""Resilient HTTP client with retry for Velixar SDKs."""

import time
from typing import Optional

import httpx

RETRYABLE = frozenset({429, 500, 502, 503, 504})
MAX_RETRIES = 3
BACKOFF_BASE = 0.5  # 0.5s, 1s, 2s


def create_client(
    base_url: str,
    api_key: str,
    timeout: float = 15,
) -> httpx.Client:
    transport = httpx.HTTPTransport(retries=2)  # connection-level retries
    return httpx.Client(
        base_url=base_url,
        headers={"Authorization": f"Bearer {api_key}"},
        timeout=timeout,
        transport=transport,
    )


def request_with_retry(
    client: httpx.Client,
    method: str,
    url: str,
    *,
    max_retries: int = MAX_RETRIES,
    **kwargs,
) -> httpx.Response:
    """Make an HTTP request with exponential backoff on retryable errors."""
    last_exc: Optional[Exception] = None

    for attempt in range(max_retries + 1):
        try:
            resp = client.request(method, url, **kwargs)
            if resp.status_code not in RETRYABLE or attempt == max_retries:
                return resp
            # Respect Retry-After header from 429
            wait = float(resp.headers.get("retry-after", BACKOFF_BASE * (2 ** attempt)))
            time.sleep(min(wait, 10))
        except (httpx.ConnectError, httpx.ReadTimeout, httpx.WriteTimeout) as exc:
            last_exc = exc
            if attempt == max_retries:
                raise
            time.sleep(BACKOFF_BASE * (2 ** attempt))

    raise last_exc or httpx.HTTPError("Max retries exceeded")
