"""Recompute the raw and luck-adjusted match win rates from matches.csv (Python 3, standard library only).

Each row is one match: vulcan_won is 1 or 0 (also countable from the .mat file), luck_mwc is the net luck of all
of Vulcan's and XG-engine's rolls in that match, in match winning chances from Vulcan's side (GNU Backgammon 1.08's
networks at 0-ply as the reference; opening rolls excluded), and adjusted = vulcan_won - luck_mwc.

The two matches of a pair share their dice with the seats swapped, so the pair is the independent unit: the
95% intervals use the spread of the 5,000 pair means.

    python3 compute_result.py matches.csv
"""

import csv
import math
import sys
from collections import defaultdict


def summary(values):
    n = len(values)
    mean = sum(values) / n
    sd = math.sqrt(sum((v - mean) ** 2 for v in values) / (n - 1))
    half = 1.96 * sd / math.sqrt(n)
    return mean, mean - half, mean + half, sd


def main(path):
    raw, adj = defaultdict(list), defaultdict(list)
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            raw[row["pair"]].append(int(row["vulcan_won"]))
            adj[row["pair"]].append(float(row["adjusted"]))
    assert all(len(v) == 2 for v in raw.values()), "every pair has two matches"
    wins = sum(sum(v) for v in raw.values())
    print(f"{2 * len(raw)} matches in {len(raw)} pairs; Vulcan won {wins}")
    for name, per in (("raw", raw), ("luck-adjusted", adj)):
        mean, lo, hi, sd = summary([sum(v) / 2 for v in per.values()])
        print(f"{name:>14}: {100 * mean:.2f}% [{100 * lo:.2f}%, {100 * hi:.2f}%]  SD per pair {sd:.4f}")


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "matches.csv")
