#!/usr/bin/env python3
"""Tablelight's seeded roller, re-implemented in plain Python.

Nothing here is shared with the Swift code: SplitMix64, the face mapping (Lemire's
multiply-and-reject, as Swift's `Int.random(in:using:)` does it) and the roller (dice,
exploding, keep and drop) are written out from their descriptions. If they reproduce a
report's seeded numbers exactly, the app's Swift code rolls the way it says it does.

    python3 reference.py digests REPORT.json          # every digest in any report
    python3 reference.py seeded REPORT.json [STREAM…] # a seeded report's counts, stream by stream
    python3 reference.py roll SEED NOTATION [COUNT]   # print rolls, to compare by eye

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

MASK = (1 << 64) - 1


class SplitMix64:
    """The seeded generator the suite uses (SplitMix64)."""

    def __init__(self, seed):
        self.state = seed & MASK

    def next(self):
        self.state = (self.state + 0x9E3779B97F4A7C15) & MASK
        z = self.state
        z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK
        z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK
        return z ^ (z >> 31)


def face(low, high, generator):
    """A face in low...high: the high 64 bits of word × n, rejecting the biased stretch."""
    n = high - low + 1
    m = generator.next() * n
    if (m & MASK) < n:
        t = ((1 << 64) - n) % n
        while (m & MASK) < t:
            m = generator.next() * n
    return low + (m >> 64)


def fnv1a64(data):
    value = 0xCBF29CE484222325
    for byte in data:
        value ^= byte
        value = (value * 0x100000001B3) & MASK
    return value


def stream_seed(master, stream):
    """Each stream of a seeded run: FNV-1a-64 of "master:stream"."""
    return fnv1a64(f"{master}:{stream}".encode())


TERM = re.compile(r"([+-]?)(?:(\d*)d(\d+|f|%)(!?)(kh|kl|dh|dl|k|d)?(\d*)|(\d+))")


def parse(notation):
    """The notations the suite uses: NdS, NdF, d%, '!', keep/drop, constants, + and -."""
    text = notation.lower().replace(" ", "")
    terms, at = [], 0
    while at < len(text):
        match = TERM.match(text, at)
        if not match or match.end() == at:
            raise ValueError(f"can't read {notation!r} at {at}")
        sign = -1 if match.group(1) == "-" else 1
        if match.group(7):
            terms.append((sign, int(match.group(7))))
        else:
            count = int(match.group(2) or 1)
            sides_text = match.group(3)
            sides = 0 if sides_text == "f" else 100 if sides_text == "%" else int(sides_text)
            selection = match.group(5)
            if selection == "k":
                selection = "kh"
            elif selection == "d":
                selection = "dl"
            n = int(match.group(6) or 1)
            terms.append((sign, (count, sides, match.group(4) == "!", selection, n)))
        at = match.end()
    return terms


def roll_group(group, generator):
    """One group of dice, in the roller's draw order; returns (values, kept flags)."""
    count, sides, explodes, selection, n = group
    low, high = (-1, 1) if sides == 0 else (1, sides)
    values = []
    for _ in range(count):
        value = face(low, high, generator)
        explosions = 0
        while explodes and value == sides and explosions < 20:
            values.append(value)
            value = face(1, sides, generator)
            explosions += 1
        values.append(value)
    kept = [True] * len(values)
    if selection:
        ascending = sorted(range(len(values)), key=lambda i: (values[i], i))
        if selection == "kh":
            dropped = ascending[: max(0, len(values) - n)]
        elif selection == "kl":
            dropped = ascending[n:]
        elif selection == "dh":
            dropped = ascending[max(0, len(values) - n):]
        else:
            dropped = ascending[:n]
        for i in dropped:
            kept[i] = False
    return values, kept


def roll_total(terms, generator):
    total = 0
    for sign, term in terms:
        if isinstance(term, int):
            total += sign * term
        else:
            values, kept = roll_group(term, generator)
            total += sign * sum(v for v, k in zip(values, kept) if k)
    return total


def digest(notation, seed, rolls):
    generator, terms = SplitMix64(seed), parse(notation)
    value, first = 0xCBF29CE484222325, []
    for _ in range(rolls):
        total = roll_total(terms, generator)
        if len(first) < 20:
            first.append(total)
        for byte in f"{total}\n".encode():
            value ^= byte
            value = (value * 0x100000001B3) & MASK
    return f"{value:016x}", first


def check_digests(report):
    ok = True
    for d in report["digests"]:
        got, first = digest(d["notation"], d["seed"], d["rolls"])
        same = got == d["fnv1a64"] and first == d["first"]
        ok &= same
        print(f"{'same' if same else 'DIFFERENT':9} {d['notation']:8} {d['rolls']} rolls, seed {d['seed']}: {got}")
    return ok


def counts_for(stream, seed, test):
    """Recounts one seeded stream exactly as the Swift job rolled it."""
    generator = SplitMix64(seed)
    kind, notation = stream.split(":", 1)
    rolls = test["rolls"]
    if kind == "main":
        terms = parse(notation)
        low = -1 if notation.endswith("F") else 1
        high = 1 if notation.endswith("F") else int(notation[2:])
        counts = [0] * (high - low + 1)
        for _ in range(rolls):
            counts[roll_total(terms, generator) - low] += 1
        return counts
    if kind == "direct":
        sides = int(notation[1:])
        counts = [0] * sides
        for _ in range(rolls):
            counts[face(1, sides, generator) - 1] += 1
        return counts
    if kind == "exact" and notation != "4dF+1 rerolled":
        terms = parse(notation)
        tally = {}
        for _ in range(rolls):
            total = roll_total(terms, generator)
            tally[total] = tally.get(total, 0) + 1
        return [sum(tally.get(v, 0) for v in cell["values"]) for cell in test["cells"]]
    raise ValueError(f"reference.py doesn't recount {stream} streams yet")


def check_seeded(report, streams):
    if report["generator"]["kind"] != "seeded":
        sys.exit("Only a seeded report can be repeated roll for roll.")
    master = report["generator"]["seed"]
    by_stream = {}
    for test in report["tests"]:
        digits = test["id"].startswith(("uniformity.tens", "uniformity.units"))
        if test["group"] in ("uniformity", "exact") and test.get("cells") and not digits:
            by_stream.setdefault(test["stream"], []).append(test)
    ok = True
    for stream in streams or ["main:1d20", "direct:d20", "exact:4d6dl1", "exact:2d20kh1"]:
        tests = by_stream[stream]
        got = counts_for(stream, stream_seed(master, stream), tests[0])
        for test in tests:
            same = got == [cell["observed"] for cell in test["cells"]]
            ok &= same
            print(f"{'same' if same else 'DIFFERENT':9} {stream}: {test['rolls']:,} rolls recounted ({test['id']})")
    return ok


def main(argv):
    if len(argv) >= 3 and argv[1] == "digests":
        return 0 if check_digests(json.load(open(argv[2]))) else 1
    if len(argv) >= 3 and argv[1] == "seeded":
        return 0 if check_seeded(json.load(open(argv[2])), argv[3:]) else 1
    if len(argv) >= 4 and argv[1] == "roll":
        generator, terms = SplitMix64(int(argv[2])), parse(argv[3])
        print(" ".join(str(roll_total(terms, generator)) for _ in range(int(argv[4]) if len(argv) > 4 else 20)))
        return 0
    print(__doc__)
    return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv))
