"""Format the paired driver JSON captures as readable before/after output.

Usage: python3 format-output.py <directory containing final-arm64.json/final-x64.json>
"""
from pathlib import Path
import json
import sys

p = Path(sys.argv[1])
data = {arch: json.loads((p / f"final-{arch}.json").read_text()) for arch in ["arm64", "x64"]}
for side, label in [("base", "before"), ("head", "after")]:
    sha = data["arm64"]["commits"][side]
    lines = [
        f"{label.upper()}: [{sha[:10]}](https://github.com/pingdotgg/t3code/commit/{sha})",
        "macOS 26.6.2, Apple silicon, 12 cores, 12 GiB RAM; Node 26.13.1; electron-updater 6.8.9.",
        "Actual published payloads repacked with this commit's createBuildConfig. HTTP 206 serves real ZIP bytes at 10,000,000 bytes/s.",
        "Seven interleaved runs per layout and architecture. Timing covers differential reconstruction and downloader checksum validation.",
        "",
    ]
    for arch, d in data.items():
        s = d[side]
        lines += [arch, "run  fetched_body_bytes  ranges  elapsed_ms  output_sha512_matches"]
        for r in sorted((r for r in d["runs"] if r["side"] == side), key=lambda r: r["run"]):
            lines += [f"{r['run']:3d}  {r['bodyBytes']:18d}  {r['ranges']:6d}  {r['milliseconds']:10.3f}  {str(r['sha512Matches']).lower()}"]
        lines += [
            f"Median bytes: {s['bodyBytes']['median']}; byte spread: {s['bodyBytes']['spread']}",
            f"Median elapsed: {s['milliseconds']['median']:.3f} ms; min: {s['milliseconds']['min']:.3f}; max: {s['milliseconds']['max']:.3f}; spread: {s['milliseconds']['spread']:.3f} ms",
            f"Every reconstructed ZIP matched SHA-512: {s['allSha512Match']}",
            f"Logical payload files preserved per release: {d['payloads']['new']['logicalFiles']}. All 87 font/model files ({d['payloads']['new']['assetBytes']} bytes) were byte-identical across releases.",
            "",
        ]
    (p / f"{label}-measurement-output.txt").write_text("\n".join(lines))
