"""Print every number the post quotes, from results.json (or the file given as argv[1])."""
import json, sys, collections
R = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "results.json"))
by = collections.defaultdict(list)
for r in R: by[(r["scenario"], r["client"])].append(r)
N = {"openai-py": "OpenAI Python", "openai-js": "OpenAI Node", "anthropic-py": "Anthropic Python", "anthropic-js": "Anthropic Node",
     "genai-py": "Google GenAI Python", "genai-js": "Google GenAI Node", "gcs-py": "Google Cloud Storage", "boto3-new": "boto3",
     "awsjs-new": "AWS SDK for JavaScript", "stripe-py": "Stripe Python", "stripe-js": "Stripe Node", "pygithub": "PyGithub",
     "octokit": "Octokit", "urllib3": "requests + urllib3 `Retry`"}
def rng(v):
    a, b = min(v), max(v); f = "%.2f" if b < 1 else "%.1f"
    return (f % a) if (f % a) == (f % b) else f"{f % a}–{f % b}"
def cell(s, c):
    rs = by[(s, c)]; r = rs[0]
    if not r["finished"] and r["attempts"] == 1: return "asleep"
    if r["attempts"] == 1: return "—"
    allg = [y for x in rs for y in x["gaps"]]
    if max(allg) < 0.02: return "no wait"
    return rng([x["gaps"][0] for x in rs]) + " s"
scen = sorted({r["scenario"] for r in R})
print("TOTALS scenarios", len(scen), "calls", len(R), "requests", sum(r["attempts"] for r in R))
print("\n| Client | `0` | `2` | `20` | `61` | `86400` |\n|---|---|---|---|---|---|")
for c in N: print(f"| {N[c]} | " + " | ".join(cell(s, c) for s in ["429-ra-0", "429-ra-2", "429-ra-20", "429-ra-61", "429-ra-86400"]) + " |")
print("\n| Client | Requests | First to last | First wait, 5 runs |\n|---|---|---|---|")
for c in N:
    rs = by[("429-none", c)]; att = sorted({r["attempts"] for r in rs}); last = [r["offsets"][-1] for r in rs]; g = [r["gaps"][0] for r in rs if r["gaps"]]
    a = str(att[0]) if len(att) == 1 else f"{att[0]}–{att[-1]}"
    print(f"| {N[c]} | {a} | {'—' if max(last) < 0.02 else rng(last) + ' s'} | {(rng(g) + ' s') if g else '—'} |")
print("\nDETAILS")
def show(s, c, what="gaps"):
    for r in by[(s, c)]: print(f"  {s:14} {c:13} rep{r['rep']} n={r['attempts']:2} {'done' if r['finished'] else 'KILL'} el={r['elapsed']:7.1f} last={r['offsets'][-1] if r['offsets'] else 0:8.3f} gaps={r['gaps']} | {r['outcome'][:70]}")
for c in ["openai-py", "anthropic-py", "anthropic-js", "urllib3", "pygithub", "openai-js", "awsjs-new"]: show("429-ra-61", c)
for c in ["pygithub", "urllib3"]: show("429-ra-20", c)
for c in ["openai-py", "openai-js", "anthropic-py", "anthropic-js", "pygithub", "urllib3", "awsjs-new", "boto3-new"]: show("429-ra-86400", c)
for c in ["openai-js", "pygithub", "urllib3", "openai-py"]: show("429-ra-0", c)
# The six clients that use the header value as the wait. Every wait of every run, unfiltered
# (OpenAI Node is left out at 61 s, which is above its 60 s limit). The AWS SDK for JavaScript
# is printed apart: it takes the larger of its backoff and the header, up to backoff + 5 s.
six = ["openai-py", "openai-js", "anthropic-py", "anthropic-js", "pygithub", "urllib3"]
for s, v in [("429-ra-2", 2), ("429-ra-20", 20), ("429-ra-61", 61)]:
    g = [x for c in six if not (v == 61 and c == "openai-js") for r in by[(s, c)] for x in r["gaps"]]
    print(f"  six clients, all waits at {v}: min {min(g):.3f} max {max(g):.3f} n={len(g)}")
    print(f"  awsjs-new waits at {v}:", [r["gaps"] for r in by[(s, "awsjs-new")]])
for c in ["openai-py", "openai-js", "anthropic-py", "anthropic-js"]:
    g1 = [r["gaps"][0] for s in ("429-none", "503-none") for r in by[(s, c)]]; g2 = [r["gaps"][1] for s in ("429-none", "503-none") for r in by[(s, c)]]
    print(f"  own backoff {c}: first {min(g1):.3f}-{max(g1):.3f} second {min(g2):.3f}-{max(g2):.3f}")
for s in ["429-ra-date5", "429-ra-ms-1500", "429-ra-garbage", "503-ra-2"]:
    print(" ", s, {c: (cell(s, c), by[(s, c)][0]["attempts"]) for c in N})
for c in ["urllib3", "pygithub"]: print("  garbage outcome", c, by[("429-ra-garbage", c)][0]["outcome"][:80])
allg = [r for r in R if r["client"] == "gcs-py"]
print("  gcs attempts", min(r["attempts"] for r in allg), max(r["attempts"] for r in allg), "elapsed max", max(r["elapsed"] for r in allg), "429-none attempts", sorted({r["attempts"] for r in by[("429-none", "gcs-py")]}), "killed", sum(1 for r in allg if not r["finished"]))
for c in ["octokit", "urllib3", "boto3-old", "stripe-js"]:
    for s in ["429-none", "503-none"]:
        rs = by[(s, c)]; n = max(len(r["gaps"]) for r in rs)
        if n: print(f"  {c} {s} gap ranges:", [f"{min(r['gaps'][i] for r in rs if len(r['gaps'])>i):.3f}-{max(r['gaps'][i] for r in rs if len(r['gaps'])>i):.3f}" for i in range(n)], "requests", sorted({r["attempts"] for r in rs}), "last", rng([r["offsets"][-1] for r in rs]))
rs = [r for r in R if r["client"] == "boto3-old"]; n = 9
print("  boto3-old spread over ALL runs:", [f"{(max(r['gaps'][i] for r in rs)-min(r['gaps'][i] for r in rs))*1000:.0f}ms" for i in range(n)], "runs", len(rs))
for c in ["boto3-new", "awsjs-old", "awsjs-new", "boto3-old"]:
    rs = by[("429-none", c)]; print(f"  {c} 429-none requests {sorted({r['attempts'] for r in rs})} last {rng([r['offsets'][-1] for r in rs])}")
for c in ["pygithub", "stripe-py", "stripe-js"]: show("503-none", c)
show("503-ra-2", "stripe-js")
