"""Recalculate the October 27 controlled browser comparison from recorded trials."""

import csv
from collections import defaultdict
from pathlib import Path
from statistics import median


def main():
    source = Path(__file__).with_name("trials.csv")
    groups = defaultdict(lambda: defaultdict(dict))
    with source.open(encoding="utf-8", newline="") as stream:
        for row in csv.DictReader(stream):
            key = (row["model"], row["tier"], row["workflow"])
            arm, trial = row["arm"], int(row["round"])
            if trial in groups[key][arm]:
                raise ValueError(f"Duplicate trial {key}, {arm}, round {trial}")
            if row["passed"] not in {"yes", "no"}:
                raise ValueError(f"Unknown outcome {row['passed']}")
            groups[key][arm][trial] = (row["passed"] == "yes", int(row["elapsed_ms"]))

    totals = defaultdict(int)
    passes = defaultdict(int)
    reductions = []
    print("Model / tier / workflow | passed (Temivor, baseline) | median seconds | reduction")
    for key, arms in sorted(groups.items()):
        if set(arms) != {"temivor", "baseline"} or arms["temivor"].keys() != arms["baseline"].keys():
            raise ValueError(f"Unpaired trial records for {key}")
        times = {}
        counts = []
        for arm in ("temivor", "baseline"):
            trials = arms[arm].values()
            passed_times = [elapsed for passed, elapsed in trials if passed]
            if not passed_times:
                raise ValueError(f"No passing times for {key}, {arm}")
            times[arm] = median(passed_times) / 1000
            totals[arm] += len(trials)
            passes[arm] += len(passed_times)
            counts.append(f"{len(passed_times)}/{len(trials)}")
        reduction = 100 * (1 - times["temivor"] / times["baseline"])
        reductions.append(reduction)
        print(f"{' / '.join(key)} | {', '.join(counts)} | "
              f"{times['temivor']:.2f}, {times['baseline']:.2f} | {reduction:.1f}%")
    for arm in ("temivor", "baseline"):
        print(f"{arm}: {passes[arm]}/{totals[arm]} passed")
    print(f"Median time reduction across comparisons: {min(reductions):.0f}% to {max(reductions):.0f}%")


if __name__ == "__main__":
    main()
