"""Recalculate the table from nine retained observations; no experiment is run.

Download the observation JSON alongside this script, then run:
  python3 lab-research-cpu-verifier-recompute.py > comparison.csv

An optional first argument selects the downloaded JSON. The exact data hash is
checked. This reproduces the table arithmetic, not the private measurement run.
"""
import csv
import hashlib
import json
from pathlib import Path
import sys

EXPECTED_SHA256 = "1cbc548f4d07873264dd53f90409056b6bf18cb38c2900190c7a933e599eea05"


def main():
    if len(sys.argv) > 2:
        raise SystemExit("Usage: python3 lab-research-cpu-verifier-recompute.py [observation.json]")
    path = Path(sys.argv[1]) if len(sys.argv) == 2 else Path(__file__).with_name(
        "lab-research-cpu-verifier-observation.json"
    )
    raw = path.read_bytes()
    if hashlib.sha256(raw).hexdigest() != EXPECTED_SHA256:
        raise SystemExit("The observation file does not match this version's data hash.")
    data = json.loads(raw)
    rows = data["observations"]
    if len(rows) != 9 or data["observations_per_setting"] != 1:
        raise SystemExit("Unexpected observation coverage.")
    serial = {r["group_index"]: r["wall_seconds"] for r in rows if r["requested_workers"] == 1}
    writer = csv.writer(sys.stdout, lineterminator="\n")
    writer.writerow([
        "group", "shape_T", "shape_H", "case_count", "requested_workers",
        "configured_worker_bound", "execution", "wall_seconds", "process_cpu_seconds",
        "wall_time_divided_by_serial"
    ])
    for row in rows:
        writer.writerow([
            row["group_index"], row["shape"]["T"], row["shape"]["H"], row["case_count"],
            row["requested_workers"], row["effective_workers"],
            "direct_iteration" if row["effective_workers"] == 1 else "fresh_thread_pool",
            repr(row["wall_seconds"]), repr(row["process_cpu_seconds"]),
            format(row["wall_seconds"] / serial[row["group_index"]], ".12g")
        ])


if __name__ == "__main__":
    main()
