"""Retry wrapper for SublimePDF render calls, as published in /guides/pdf-api-error-handling.
Python 3.8+, standard library only."""
import email.utils
import json
import os
import random
import socket
import time
import urllib.error
import urllib.request
import uuid

RETRYABLE = {429, 500, 502, 503, 504}


def parse_retry_after(value, now=None):
    """Retry-After is delay-seconds or an HTTP-date (RFC 9110, section 10.2.3). Returns seconds or None."""
    if not value:
        return None
    value = value.strip()
    if value.isdigit():
        return float(value)
    try:
        when = email.utils.parsedate_to_datetime(value).timestamp()
    except (TypeError, ValueError):
        return None
    return max(0.0, when - (now or time.time()))


def _api_error(status, raw, reason):
    try:
        err = json.loads(raw).get("error", {})
    except (ValueError, AttributeError):
        err = {}
    out = {
        "status": status,
        "type": err.get("type") or f"http_{status}",
        "message": err.get("message") or reason or f"HTTP {status}",
        "retryable": status in RETRYABLE,
    }
    if isinstance(err.get("field"), str):
        out["field"] = err["field"]
    return out


def render_with_retry(path, body, *, api_key=None, base_url=None, max_attempts=4, base_delay=0.5,
                      max_delay=8.0, max_retry_after=30.0, attempt_timeout=60.0, deadline=120.0,
                      idempotency_key=None, log=lambda event: None):
    api_key = api_key or os.environ["SUBLIMEPDF_API_KEY"]
    base_url = base_url or os.environ.get("SUBLIMEPDF_API_BASE_URL", "https://api.sublimepdf.com/v1")
    idempotency_key = idempotency_key or str(uuid.uuid4())  # one key per logical render
    started = time.monotonic()
    error = None
    attempt = 0

    while attempt < max_attempts:
        attempt += 1
        wait = None
        req = urllib.request.Request(
            base_url + path,
            data=json.dumps(body).encode(),
            method="POST",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
                "Accept": "application/pdf",
                "Idempotency-Key": idempotency_key,
            },
        )
        timeout = min(attempt_timeout, deadline - (time.monotonic() - started))
        try:
            with urllib.request.urlopen(req, timeout=timeout) as res:
                pdf = res.read()
            log({"attempt": attempt, "status": 200, "outcome": "success", "idempotency_key": idempotency_key})
            return {"ok": True, "pdf": pdf, "attempts": attempt, "idempotency_key": idempotency_key}
        except urllib.error.HTTPError as e:
            error = _api_error(e.code, e.read(), e.reason)
            if e.code == 429:
                wait = parse_retry_after(e.headers.get("Retry-After"))
        except (socket.timeout, TimeoutError):
            error = {"status": None, "type": "timeout", "retryable": True,
                     "message": "No response before the timeout. The render may still have run."}
        except (urllib.error.URLError, ConnectionError) as e:
            reason = getattr(e, "reason", e)
            timed_out = isinstance(reason, (socket.timeout, TimeoutError))
            error = {"status": None, "type": "timeout" if timed_out else "network_error", "retryable": True,
                     "message": "No response before the timeout. The render may still have run." if timed_out else str(reason)}

        log({"attempt": attempt, "status": error["status"], "type": error["type"],
             "retryable": error["retryable"], "idempotency_key": idempotency_key})
        if not error["retryable"] or attempt == max_attempts:
            break
        delay = max(wait or 0.0, random.uniform(0, min(max_delay, base_delay * 2 ** (attempt - 1))))
        if (wait or 0.0) > max_retry_after or time.monotonic() - started + delay >= deadline:
            log({"attempt": attempt, "outcome": "give_up", "reason": "wait exceeds budget", "wait_s": round(delay, 2)})
            break
        time.sleep(delay)

    return {"ok": False, "error": error, "attempts": attempt, "idempotency_key": idempotency_key}
