"""Draw the SVG charts for the post from results.json and data/stack."""
import json, collections, pathlib, datetime, statistics as st
W = pathlib.Path(__file__).parent; OUT = W / "out"
R = json.load(open(W / "results.json"))
by = collections.defaultdict(list)
for r in R: by[(r["scenario"], r["client"])].append(r)
FG, MUTED, RULE, ACC = "#1a1a17", "#8a877d", "#d9d5c8", "#b8842a"
FONT = "font-family=\"Inter, -apple-system, 'Helvetica Neue', Arial, sans-serif\""
LABEL = {r["client"]: r["label"] for r in R}
LABEL["urllib3"] = "requests + urllib3 Retry(3)"
LABEL["gcs-py"] = "Google Cloud Storage Py 3.17.1"

def svg(w, h, body, title):
    return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" aria-label="{title}" {FONT} font-size="12">'
            f'<title>{title}</title>{"".join(body)}</svg>')

def timeline(name, scenario, clients, xmax, title, ticks, note_clip=True):
    left, right, top, lane, gap = 204, 200, 34, 5, 12
    rows = [(c, by[(scenario, c)]) for c in clients]
    rowh = [max(len(rs), 1) * lane + gap for _, rs in rows]
    w = 720; pw = w - left - right; h = top + sum(rowh) + 34
    X = lambda s: left + pw * min(s, xmax) / xmax
    b = []
    for t in ticks:
        b.append(f'<line x1="{X(t):.1f}" y1="{top-6}" x2="{X(t):.1f}" y2="{h-30}" stroke="{RULE}" stroke-width="1"/>')
        b.append(f'<text x="{X(t):.1f}" y="{h-14}" text-anchor="middle" fill="{MUTED}">{t} s</text>')
    b.append(f'<text x="{left}" y="14" fill="{MUTED}" font-size="11" letter-spacing="1.2">SECONDS SINCE THE FIRST REQUEST · ONE ROW OF DOTS PER RUN</text>')
    y = top
    for (c, rs), rh in zip(rows, rowh):
        mid = y + (rh - gap) / 2
        b.append(f'<text x="{left-12}" y="{mid+4:.1f}" text-anchor="end" fill="{FG}">{LABEL[c]}</text>')
        clipped = False
        for i, r in enumerate(sorted(rs, key=lambda r: r["rep"])):
            ly = y + i * lane + lane / 2
            for off in r["offsets"]:
                if off > xmax: clipped = True; continue
                b.append(f'<circle cx="{X(off):.1f}" cy="{ly:.1f}" r="2.3" fill="{FG}" fill-opacity="0.85"/>')
        att = sorted({r["attempts"] for r in rs}); last = [r["offsets"][-1] for r in rs if r["offsets"]]
        a = f"{att[0]}" if len(att) == 1 else f"{att[0]}–{att[-1]}"
        span = f"{min(last):.1f} s" if max(last) - min(last) < 0.15 else f"{min(last):.1f}–{max(last):.1f} s"
        txt = f'{a} request{"s" if att[-1] > 1 else ""}' + ("" if max(last) == 0 else f" · {span}")
        b.append(f'<text x="{left+pw+12}" y="{mid+4:.1f}" fill="{ACC if clipped else MUTED}">{txt}{" →" if clipped else ""}</text>')
        y += rh
        b.append(f'<line x1="0" y1="{y-gap/2:.1f}" x2="{w}" y2="{y-gap/2:.1f}" stroke="{RULE}" stroke-width="0.5"/>')
    (OUT / name).write_text(svg(w, h, b, title))

ALL = ["openai-py", "openai-js", "anthropic-py", "anthropic-js", "boto3-new", "awsjs-new", "urllib3", "octokit", "boto3-old", "gcs-py", "pygithub", "stripe-py", "stripe-js", "genai-py", "genai-js"]
timeline("timeline-429.svg", "429-none", ALL, 30, "Every request each client sent after a 429 with no Retry-After header, five runs each", [0, 5, 10, 15, 20, 25, 30])
timeline("timeline-aws.svg", "429-none", ["boto3-old", "boto3-new", "awsjs-old", "awsjs-new"], 27, "AWS SDK requests after a 429, before and after the 10 November 2026 default change", [0, 5, 10, 15, 20, 25])
timeline("timeline-zero.svg", "429-ra-0", ["openai-js", "pygithub", "urllib3", "openai-py", "anthropic-py", "anthropic-js"], 3.2, "Requests sent after a 429 with Retry-After: 0", [0, 1, 2, 3])

# stacked retries
def ts(s): return datetime.datetime.fromisoformat(s).timestamp()
har = sorted(ts(e["startedDateTime"]) for e in json.load(open(W / "data/stack/flows.har"))["log"]["entries"])
cases = [("sdk", "OpenAI SDK alone"), ("langchain", "LangChain ChatOpenAI"), ("langchain_with_retry", "LangChain .with_retry()"), ("cookbook", "SDK + the guide's tenacity decorator")]
stack = []
for key, label in cases:
    ev = [json.loads(l) for l in open(W / f"data/stack/{key}.jsonl")]
    runs = []
    for s, e in zip(ev[0::2], ev[1::2]):
        runs.append((sum(1 for t in har if s["t"] - 0.05 <= t <= e["t"] + 0.05), e["elapsed"]))
    stack.append({"case": key, "label": label, "requests": [n for n, _ in runs], "elapsed": [t for _, t in runs]})
json.dump(stack, open(W / "stack.json", "w"), indent=1)
w, left, bh, top = 720, 232, 26, 30; pw = w - left - 180; mx = max(max(s["requests"]) for s in stack)
b = [f'<text x="{left}" y="14" fill="{MUTED}" font-size="11" letter-spacing="1.2">REQUESTS SENT FOR ONE CALL TO chat.completions.create</text>']
for i, s in enumerate(stack):
    y = top + i * (bh + 12); n = s["requests"][0]
    b.append(f'<text x="{left-12}" y="{y+bh/2+4}" text-anchor="end" fill="{FG}">{s["label"]}</text>')
    b.append(f'<rect x="{left}" y="{y}" width="{pw*n/mx:.1f}" height="{bh}" fill="{ACC if n == mx else FG}"/>')
    el = s["elapsed"]; b.append(f'<text x="{left+pw*n/mx+10:.1f}" y="{y+bh/2+4}" fill="{FG}">{n} requests <tspan fill="{MUTED}">· {min(el):.1f}–{max(el):.1f} s</tspan></text>')
(OUT / "stacked.svg").write_text(svg(w, top + len(stack) * (bh + 12) + 6, b, "Requests sent for one logical call as retry layers are stacked"))
print(json.dumps(stack))
