#!/usr/bin/env python3
"""Recomputes every statistic in a dice-fairness report from its raw counts.

Written apart from the Swift suite: its own exact dice odds (by convolution and by listing
outcomes), Holm correction and verdicts, and it checks the report is whole (every test of its
suite version, counts that add up to the rolls). Its χ² tail, Kolmogorov tail and pooling
follow the same textbook algorithms as the Swift code, so a flaw shared by both would agree
with itself: with SciPy installed it also checks every p-value against SciPy's own (χ²,
normal and Kolmogorov). It then says whether each test's statistic, p-value, threshold and
verdict agree with the report.

    python3 check_report.py REPORT.json [REPORT.json …]

Standard library only (Python 3.8 or later).
"""
import itertools
import json
import math
import sys

try:
    from scipy.stats import chi2 as scipy_chi2, norm as scipy_norm
    from scipy.special import kolmogorov as scipy_kolmogorov
except ImportError:
    scipy_chi2 = scipy_norm = scipy_kolmogorov = None


def scipy_p(test, stat):
    """The p-value from SciPy's own distributions, for a statistic recomputed here."""
    tid = test["id"]
    if test.get("batchPValues") is not None:
        n = len(test["batchPValues"])
        root = math.sqrt(n)
        return float(scipy_kolmogorov((root + 0.12 + 0.11 / root) * stat))
    if tid.startswith(("independence.serial", "independence.runs")):
        return float(2 * scipy_norm.sf(abs(stat)))
    return float(scipy_chi2.sf(stat, test["degreesOfFreedom"]))


# --- Distributions -------------------------------------------------------------------------

def gamma_q(a, x):
    """Upper regularised incomplete gamma Q(a, x)."""
    if x <= 0:
        return 1.0
    log_prefix = -x + a * math.log(x) - math.lgamma(a)
    if x < a + 1:
        term = total = 1 / a
        ap = a
        while True:
            ap += 1
            term *= x / ap
            total += term
            if abs(term) < abs(total) * 1e-16:
                break
        return max(0.0, 1 - total * math.exp(log_prefix))
    tiny = 1e-300
    b, c = x + 1 - a, 1 / tiny
    d = 1 / b
    h, i = d, 1
    while True:
        an = -i * (i - a)
        b += 2
        d = an * d + b
        d = tiny if abs(d) < tiny else d
        c = b + an / c
        c = tiny if abs(c) < tiny else c
        d = 1 / d
        h *= d * c
        i += 1
        if abs(d * c - 1) < 1e-16:
            break
    return min(1.0, math.exp(log_prefix) * h)


def chi2_sf(x, df):
    return gamma_q(df / 2, x / 2)


def normal_two_sided(z):
    return math.erfc(abs(z) / math.sqrt(2))


def kolmogorov_sf(lam):
    if lam <= 0:
        return 1.0
    if lam < 1.18:
        s = sum(math.exp(-((2 * k - 1) ** 2) * math.pi ** 2 / (8 * lam * lam)) for k in range(1, 51))
        return min(1.0, max(0.0, 1 - math.sqrt(2 * math.pi) / lam * s))
    s = sum((1 if k % 2 else -1) * math.exp(-2 * k * k * lam * lam) for k in range(1, 101))
    return min(1.0, max(0.0, 2 * s))


def pearson(observed, expected):
    x = sum((o - e) ** 2 / e for o, e in zip(observed, expected))
    return x, len(observed) - 1, chi2_sf(x, len(observed) - 1)


def g_test(observed, expected):
    g = 2 * sum(o * math.log(o / e) for o, e in zip(observed, expected) if o > 0)
    return g, len(observed) - 1, chi2_sf(g, len(observed) - 1)


def pool(values, expected, minimum=5):
    """Neighbouring cells joined left to right until each expects ≥ minimum."""
    groups, current, total = [], [], 0.0
    for v, e in zip(values, expected):
        current.append((v, e))
        total += e
        if total >= minimum:
            groups.append(current)
            current, total = [], 0.0
    if current:
        if groups:
            groups[-1] += current
        else:
            groups = [current]
    return [([v for v, _ in g], sum(e for _, e in g)) for g in groups]


# --- Exact dice odds -----------------------------------------------------------------------

def convolve(a, b):
    out = {}
    for x, p in a.items():
        for y, q in b.items():
            out[x + y] = out.get(x + y, 0) + p * q
    return out


def uniform(low, high):
    return {v: 1 / (high - low + 1) for v in range(low, high + 1)}


def times(dist, n):
    out = dist
    for _ in range(n - 1):
        out = convolve(out, dist)
    return out


def exploding(sides, cap=20):
    out = {}
    for j in range(cap + 1):
        last = range(1, sides) if j < cap else range(1, sides + 1)
        for f in last:
            out[sides * j + f] = out.get(sides * j + f, 0) + (1 / sides) ** j / sides
    return out


def selecting(count, sides, rule, n):
    out = {}
    for faces in itertools.product(range(1, sides + 1), repeat=count):
        s = sorted(faces)
        kept = {"kh": s[len(s) - n:], "kl": s[:n], "dh": s[: len(s) - n], "dl": s[n:]}[rule]
        out[sum(kept)] = out.get(sum(kept), 0) + 1
    total = sides ** count
    return {k: v / total for k, v in out.items()}


def exact_odds(subject):
    d6 = uniform(1, 6)
    table = {
        "2d6": lambda: times(d6, 2), "3d6": lambda: times(d6, 3), "8d6": lambda: times(d6, 8),
        "4d6dl1": lambda: selecting(4, 6, "dl", 1), "4d6kh3": lambda: selecting(4, 6, "kh", 3),
        "2d20kh1": lambda: selecting(2, 20, "kh", 1), "2d20kl1": lambda: selecting(2, 20, "kl", 1),
        "5d8kl2": lambda: selecting(5, 8, "kl", 2), "4d10dh1": lambda: selecting(4, 10, "dh", 1),
        "1d6!": lambda: exploding(6), "2d6!": lambda: times(exploding(6), 2), "1d20!": lambda: exploding(20),
        "4dF": lambda: times(uniform(-1, 1), 4),
        "RollResult.rerollingFateDice": lambda: convolve(times(uniform(-1, 1), 4), {1: 1.0}),
    }
    return table[subject]()


# --- Checking one report -------------------------------------------------------------------

def close(a, b, rel=1e-6, absolute=1e-12):
    if a is None or b is None:
        return a == b
    if math.isinf(a) or math.isinf(b):
        return a == b
    return abs(a - b) <= max(absolute, rel * max(abs(a), abs(b)))


def recompute(test):
    """(statistic, p-value) from the test's own data, or a reason it can't be."""
    tid = test["id"]
    if test.get("batchPValues") is not None:
        counts = test["batchCounts"]
        for batch, p in zip(counts, test["batchPValues"]):
            e = sum(batch) / len(batch)
            if not close(pearson(batch, [e] * len(batch))[2], p, rel=1e-7, absolute=1e-12):
                return None, None, f"batch p-value {p} doesn't match its counts"
        ps = sorted(test["batchPValues"])
        n = len(ps)
        d = max(max((i + 1) / n - u, u - i / n) for i, u in enumerate(ps))
        root = math.sqrt(n)
        return d, kolmogorov_sf((root + 0.12 + 0.11 / root) * d), None
    if tid.startswith("independence.serial"):
        f = test["figures"]
        r = f["laggedProducts"] / f["sumSquares"]
        z = r * math.sqrt(f["n"])
        return z, normal_two_sided(z), None
    if tid.startswith("independence.runs"):
        f = test["figures"]
        n1, n2, runs = f["above"], f["below"], f["runs"]
        n = n1 + n2
        mean = 2 * n1 * n2 / n + 1
        var = 2 * n1 * n2 * (2 * n1 * n2 - n) / (n * n * (n - 1))
        z = (runs - mean) / math.sqrt(var)
        return z, normal_two_sided(z), None
    if tid.startswith("within-roll.positions"):
        obs, e = test["observed"], test["expectedEach"]
        x = sum((o - e) ** 2 / e for o in obs)
        return x, chi2_sf(x, test["degreesOfFreedom"]), None
    if test.get("observed") is not None:
        obs = test["observed"]
        e = sum(obs) / len(obs)
        if not close(e, test["expectedEach"]):
            return None, None, f"expected {test['expectedEach']} per cell, counts give {e}"
        x, df, p = pearson(obs, [e] * len(obs))
        return x, p, None
    cells = test["cells"]
    observed = [c["observed"] for c in cells]
    if tid.startswith("uniformity"):
        # Every face equally likely: each cell expects the total over the number of faces.
        e = sum(observed) / len(observed)
        expected = [e] * len(observed)
    elif tid.startswith("exact"):
        odds = exact_odds(test["subject"])
        n = sum(observed)
        low, high = min(odds), max(odds)
        mine = pool(list(range(low, high + 1)), [odds.get(v, 0) * n for v in range(low, high + 1)])
        if [v for v, _ in mine] != [c["values"] for c in cells]:
            return None, None, "pooled cells differ from the exact odds' pooling"
        expected = [e for _, e in mine]
    elif tid.startswith("independence.gaps"):
        gaps = sum(observed)
        k = 3 if test["subject"].endswith("F") else int(test["subject"][2:])
        p, q = 1 / k, 1 - 1 / k
        longest = 0
        while gaps * q ** longest >= 5:
            longest += 1
        raw = [gaps * p * q ** g for g in range(longest)] + [gaps * q ** longest]
        mine = pool(list(range(longest + 1)), raw)
        if [v for v, _ in mine] != [c["values"] for c in cells]:
            return None, None, "pooled gap cells differ"
        expected = [e for _, e in mine]
    else:
        return None, None, "unknown kind of test"
    for c, e in zip(cells, expected):
        if not close(c["expected"], e, rel=1e-9):
            return None, None, f"expected count {c['expected']} for {c['values']}, should be {e}"
    if test["statistic"].startswith("G"):
        x, df, pv = g_test(observed, expected)
    else:
        x, df, pv = pearson(observed, expected)
    return x, pv, None


# --- Is the report whole? --------------------------------------------------------------------

DICE = {"1d2": 2, "1d4": 4, "1d6": 6, "1d8": 8, "1d10": 10, "1d12": 12, "1d20": 20, "1d100": 100, "1dF": 3}
PER_DIE = ["uniformity.pearson", "uniformity.g-test", "independence.serial-lag1", "independence.serial-lag2",
           "independence.serial-lag3", "independence.serial-lag4", "independence.serial-lag5",
           "independence.pairs", "independence.runs", "independence.gaps", "batches.ks"]
OTHERS = ["uniformity.tens-digit.d100", "uniformity.units-digit.d100",
          "uniformity.pearson.face-d20", "uniformity.g-test.face-d20",
          "uniformity.pearson.face-d1000", "uniformity.g-test.face-d1000",
          "exact.2d6", "exact.3d6", "exact.8d6", "exact.4d6dl1", "exact.4d6kh3", "exact.2d20kh1", "exact.2d20kl1",
          "exact.5d8kl2", "exact.4d10dh1", "exact.1d6!", "exact.2d6!", "exact.1d20!", "exact.4dF", "exact.4dF+1-rerolled",
          "within-roll.pair.2d6", "within-roll.pair.2d20", "within-roll.positions.8d6"]
SUITE_TESTS = {1: sorted([f"{kind}.{die[1:]}" for kind in PER_DIE for die in DICE] + OTHERS)}


def faces_of(subject):
    if subject.endswith("dF"):
        return list(range(-1, 2))
    return list(range(1, int(subject.split("d")[-1]) + 1))


def completeness(report):
    """Problems that would hide a result: a test missing, or counts that don't add up."""
    problems = []
    expected = SUITE_TESTS.get(report["suiteVersion"])
    ids = sorted(t["id"] for t in report["tests"])
    if expected is None:
        problems.append(f"suite version {report['suiteVersion']} is unknown to this checker")
    elif ids != expected:
        missing, extra = sorted(set(expected) - set(ids)), sorted(set(ids) - set(expected))
        problems.append(f"tests missing {missing} or unexpected {extra}" if missing or extra else "a test appears twice")
    sizes = report["sampleSizes"]
    for t in report["tests"]:
        tid, rolls = t["id"], t["rolls"]
        if tid.startswith(("uniformity.pearson", "uniformity.g-test")):
            subject = tid.split(".")[-1].replace("face-", "1")
            values = [c["values"] for c in t["cells"]]
            if values != [[f] for f in faces_of("1" + subject if not subject.startswith("1") else subject)]:
                problems.append(f"{tid}: its cells aren't one per face")
        elif tid.startswith(("uniformity.tens-digit", "uniformity.units-digit")):
            if [c["values"] for c in t["cells"]] != [[d] for d in range(10)]:
                problems.append(f"{tid}: its cells aren't the digits 0 to 9")
        if t.get("cells") is not None and not tid.startswith("independence.gaps"):
            if sum(c["observed"] for c in t["cells"]) != rolls:
                problems.append(f"{tid}: counts add up to {sum(c['observed'] for c in t['cells'])}, not {rolls}")
        if tid.startswith("independence.pairs"):
            k = DICE[t["subject"]]
            if len(t["observed"]) != k * k or sum(t["observed"]) != rolls // 2:
                problems.append(f"{tid}: not {k}² cells adding up to {rolls // 2} pairs")
        if tid.startswith("within-roll.pair"):
            k = int(t["subject"].split("d")[1])
            if len(t["observed"]) != k * k or sum(t["observed"]) != rolls:
                problems.append(f"{tid}: not {k}² cells adding up to {rolls}")
        if tid == "within-roll.positions.8d6":
            rows = [t["observed"][i * 6:(i + 1) * 6] for i in range(8)]
            if len(t["observed"]) != 48 or any(sum(r) != rolls for r in rows):
                problems.append(f"{tid}: not 8 positions × 6 faces, each adding up to {rolls}")
        if t.get("batchCounts") is not None:
            k = DICE[t["subject"]]
            if (len(t["batchCounts"]) != sizes["batches"] or len(t["batchPValues"]) != sizes["batches"]
                    or any(len(b) != k or sum(b) != sizes["batchSize"] for b in t["batchCounts"])):
                problems.append(f"{tid}: not {sizes['batches']} batches of {sizes['batchSize']} rolls over {k} faces")
    return problems


def holm(pvalues, alpha):
    m = len(pvalues)
    order = sorted(range(m), key=lambda i: (pvalues[i], i))
    thresholds, adjusted, running = [0.0] * m, [0.0] * m, 0.0
    for rank, i in enumerate(order):
        thresholds[i] = alpha / (m - rank)
        running = max(running, min(1.0, (m - rank) * pvalues[i]))
        adjusted[i] = running
    return thresholds, adjusted


def check(path):
    report = json.load(open(path))
    tests = report["tests"]
    problems = completeness(report)
    for test in tests:
        stat, p, why = recompute(test)
        if why:
            problems.append(f"{test['id']}: {why}")
            continue
        if not close(stat, test["value"], rel=1e-7, absolute=1e-9):
            problems.append(f"{test['id']}: statistic {test['value']}, recomputed {stat}")
        if not close(p, test["pValue"], rel=1e-6, absolute=1e-15):
            problems.append(f"{test['id']}: p {test['pValue']}, recomputed {p}")
        if scipy_chi2 is not None and not close(scipy_p(test, stat), p, rel=1e-6, absolute=1e-14):
            problems.append(f"{test['id']}: own p {p} differs from SciPy's {scipy_p(test, stat)}")
    thresholds, adjusted = holm([t["pValue"] for t in tests], report["alpha"])
    for t, th, adj in zip(tests, thresholds, adjusted):
        verdict = "fail" if adj <= report["alpha"] else "pass"
        if not close(th, t["holmThreshold"]) or not close(adj, t["holmAdjustedP"]) or verdict != t["verdict"]:
            problems.append(f"{t['id']}: Holm threshold, adjusted p or verdict differ")
    failed = [t["id"] for t in tests if t["verdict"] == "fail"]
    print(f"{path}: {report['platform']['name']}, {report['generator']['kind']} generator, commit {report['commit'][:12]}")
    print(f"  {len(tests)} tests recomputed, {len(problems)} disagreements; {len(failed)} failed at family-wise α = {report['alpha']} (Holm)"
          + ("; every p-value also checked against SciPy" if scipy_chi2 else "; SciPy not installed, so no cross-check"))
    for problem in problems:
        print("  DISAGREES " + problem)
    for tid in failed:
        print("  FAILED    " + tid)
    for c in report["checks"]:
        print(f"  check {c['id']}: {'passed' if c['passed'] else 'FAILED'}")
    return not problems


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(2)
    sys.exit(0 if all([check(p) for p in sys.argv[1:]]) else 1)
