"""Turn the HAR files and client logs into results.json: one record per (scenario, client, repetition)."""
import json, pathlib, datetime, sys
W = pathlib.Path(__file__).parent
CLIENTS = [  # id, label, log file stem, host fragment, UA fragment
    ("openai-py", "OpenAI Python 3.55.0", "py-main.openai", "api.openai.com", "OpenAI/Python"),
    ("openai-js", "OpenAI Node 7.59.0", "node-main.openai", "api.openai.com", "OpenAI/JS"),
    ("anthropic-py", "Anthropic Python 2.10.0", "py-main.anthropic", "api.anthropic.com", "Anthropic/Python"),
    ("anthropic-js", "Anthropic Node 1.10.0", "node-main.anthropic", "api.anthropic.com", "Anthropic/JS"),
    ("genai-py", "Google GenAI Python 3.5.0", "py-main.genai", "generativelanguage", "gl-python"),
    ("genai-js", "Google GenAI Node 3.6.0", "node-main.genai", "generativelanguage", "gl-node"),
    ("gcs-py", "Google Cloud Storage Python 3.17.1", "py-main.gcs", "storage.googleapis.com", "gcloud-python"),
    ("boto3-new", "boto3 1.44.5", "py-main.boto3", "amazonaws.com", "Boto3/1.44.5"),
    ("boto3-old", "boto3 1.43.127", "py-awsold.boto3", "amazonaws.com", "Boto3/1.43.127"),
    ("awsjs-new", "AWS SDK JS 3.1171.0", "node-main.aws", "amazonaws.com", "aws-sdk-js/3.1170"),
    ("awsjs-old", "AWS SDK JS 3.1165.0", "node-awsold.aws", "amazonaws.com", "aws-sdk-js/3.1164"),  # installed with npm --before=2026-11-10
    ("stripe-py", "Stripe Python 17.0.0", "py-main.stripe", "api.stripe.com", "PythonBindings"),
    ("stripe-js", "Stripe Node 23.1.0", "node-main.stripe", "api.stripe.com", "NodeBindings"),
    ("pygithub", "PyGithub 2.10.0", "py-main.pygithub", "api.github.com", "PyGithub"),
    ("octokit", "Octokit 5.0.5", "node-main.octokit", "api.github.com", "octokit"),
    ("urllib3", "requests 2.34.2 + urllib3 Retry(total=3)", "py-main.urllib3", "example.com", "python-requests"),
]
SOLO = {"awsjs-old"}  # clients measured alone, in "<scenario>+<client>" runs
def ts(s): return datetime.datetime.fromisoformat(s).timestamp()
out = []
for d in sorted((W / "data").iterdir()):
    if not (d / "meta.json").exists(): continue
    meta = json.load(open(d / "meta.json"))
    # "<scenario>+<client>" holds a rerun of one client alone; it replaces that client in the main run.
    scenario, _, solo = meta["name"].partition("+")
    reqs = []
    for e in json.load(open(d / "flows.har"))["log"]["entries"]:
        ua = next((h["value"] for h in e["request"]["headers"] if h["name"].lower() == "user-agent"), "")
        reqs.append((ts(e["startedDateTime"]), e["request"]["url"], ua))
    for cid, label, stem, host, uafrag in CLIENTS:
        f = d / f"{stem}.jsonl"
        if not f.exists(): continue
        if (solo and cid != solo) or (not solo and cid in SOLO): continue
        mine = sorted(t for t, url, ua in reqs if host in url and uafrag in ua)
        ev = [json.loads(l) for l in open(f) if l.strip()]
        for rep in sorted({e["rep"] for e in ev}):
            start = next(e for e in ev if e["rep"] == rep and e["event"] == "start")
            end = next((e for e in ev if e["rep"] == rep and e["event"] == "end"), None)
            t1 = end["t"] if end else meta["t_kill"]
            # HAR timestamps are ms-rounded; allow 50 ms slack at the window edges
            times = [t for t in mine if start["t"] - 0.05 <= t <= t1 + 0.05]
            out.append({"scenario": scenario, "status": int(meta["status"]), "hdr": meta["hdr"], "val": meta["val"],
                        "client": cid, "label": label, "rep": rep, "attempts": len(times),
                        "offsets": [round(t - times[0], 3) for t in times] if times else [],
                        "gaps": [round(b - a, 3) for a, b in zip(times, times[1:])],
                        "elapsed": round(t1 - start["t"], 3), "finished": end is not None,
                        "outcome": (end["outcome"] if end else "still waiting when the window closed")})
json.dump(out, open(W / "results.json", "w"), indent=1)
if "-v" in sys.argv:
    for r in out:
        print(f'{r["scenario"]:15} {r["client"]:13} rep{r["rep"]} n={r["attempts"]:2} {"done" if r["finished"] else "KILL"} {r["elapsed"]:7.1f}s gaps={r["gaps"]}')
