#!/usr/bin/env python3
"""Retry policy demo against the Barg Sabz mock API — lesson AUT-201-L04.

Shows: classify errors, retry only retryable ones, exponential backoff with jitter,
honour Retry-After, cap attempts and total time, timeouts, and an Idempotency-Key
so that retrying a POST does not create a duplicate ticket.
Standard library only. Talks to http://127.0.0.1:8787 (start shared/barg-sabz-mock-api.py first).

    python retry_demo.py flaky      # 503, 503, then 200
    python retry_demo.py limited    # call /limited 6 times; 429 with Retry-After
    python retry_demo.py slow       # 5 s endpoint with a 2 s timeout
    python retry_demo.py ticket     # POST twice with the same Idempotency-Key
    python retry_demo.py auth       # wrong token: 401 is NOT retried
"""
import json
import os
import random
import sys
import time
import urllib.error
import urllib.request
import uuid

BASE = os.environ.get("ORDERS_API_BASE_URL", "http://127.0.0.1:8787")
TOKEN = os.environ.get("ORDERS_API_TOKEN", "local-demo-token")  # demo value for the local mock only

RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
MAX_ATTEMPTS = 4
MAX_TOTAL_SECONDS = 30
BASE_DELAY = 0.5
MAX_DELAY = 8.0


def backoff_delay(attempt, retry_after=None):
    """Exponential backoff with full jitter; Retry-After is treated as a minimum."""
    exp = min(MAX_DELAY, BASE_DELAY * (2 ** (attempt - 1)))
    delay = random.uniform(0, exp)
    if retry_after is not None:
        delay = max(delay, retry_after) + random.uniform(0, 0.5)
    return delay


def request(method, path, body=None, headers=None, timeout=5.0):
    h = {"Authorization": f"Bearer {TOKEN}"}
    h.update(headers or {})
    data = None
    if body is not None:
        data = json.dumps(body, ensure_ascii=False).encode("utf-8")
        h["Content-Type"] = "application/json"
    req = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.status, json.load(r)


def call_with_retry(method, path, body=None, headers=None, timeout=5.0):
    start = time.monotonic()
    for attempt in range(1, MAX_ATTEMPTS + 1):
        retry_after = None
        try:
            status, data = request(method, path, body, headers, timeout)
            print(f"  attempt {attempt}: {status}")
            return status, data
        except urllib.error.HTTPError as e:
            status = e.code
            ra = e.headers.get("Retry-After")
            retry_after = float(ra) if ra and ra.isdigit() else None
            print(f"  attempt {attempt}: {status}" + (f" (Retry-After {ra}s)" if ra else ""))
            if status not in RETRYABLE_STATUS:
                print("  -> not retryable: fix the request or stop and alert")
                return status, None
        except (urllib.error.URLError, TimeoutError) as e:
            reason = getattr(e, "reason", e)
            print(f"  attempt {attempt}: network/timeout error ({reason.__class__.__name__})")
        if attempt == MAX_ATTEMPTS:
            break
        delay = backoff_delay(attempt, retry_after)
        if time.monotonic() - start + delay > MAX_TOTAL_SECONDS:
            print("  -> total time budget would be exceeded; giving up")
            break
        print(f"  waiting {delay:.1f}s")
        time.sleep(delay)
    print("  -> giving up: send to human queue / alert")
    return None, None


def main(case):
    global TOKEN
    if case == "flaky":
        call_with_retry("GET", "/flaky")
    elif case == "limited":
        for i in range(6):
            print(f"call {i + 1}")
            call_with_retry("GET", "/limited")
    elif case == "slow":
        call_with_retry("GET", "/slow?seconds=5", timeout=2.0)
    elif case == "ticket":
        key = str(uuid.uuid4())  # one key per logical action, reused on every retry
        body = {"customer_ref": "C-09", "category": "order_shipping", "text": "سفارش BS-1002 کجاست؟"}
        for i in range(2):
            print(f"send {i + 1} with Idempotency-Key {key[:8]}…")
            status, data = call_with_retry("POST", "/tickets", body, {"Idempotency-Key": key})
            print("  ticket id:", data and data.get("id"))
    elif case == "auth":
        TOKEN = "wrong-token"
        call_with_retry("GET", "/orders/BS-1001")
    else:
        sys.exit(__doc__)


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "")
