#!/usr/bin/env python3
"""Regenerate every roll of `bg league` / `bg external-league --mat-out` games.

    python3 verify_mat_dice.py --seed S --games DIR

Python 3 standard library only (copy this file anywhere). It reads every
`pair_NNNNNN.mat` / `pair_NNNNNN_a.mat` / `pair_NNNNNN_b.mat` under DIR
(recursively) and checks that each roll follows from the run's seed S, and
that the seats are the league's.

How bg draws the dice (`bg_core::DeterministicRng`, `docs/mat_export.md`):

- Pair N of a run with `--seed S` has the pair seed P = S + N * 12345 (mod
  2**64); the file name carries N.
- A money pair file holds the pair's two games. Both roll from P, each game
  from a fresh generator: game 1 with player 1 (left column) moving first,
  game 2 with player 2 moving first.
- A match file holds one match: game k (from 0, ply-capped games included)
  rolls from a fresh generator seeded P + k * 1_000_003. In `_a` files player
  1 moves first in game 1, in `_b` files player 2; the first mover then
  alternates game by game.
- By default there is no opening roll: the game's first seat (player 1 in
  money game 1, player 2 in game 2; in matches as above) moves first and
  rolls two dice like any later turn (doubles allowed). Files with the tag
  `; [Opening Roll "standard"]` (`--opening-roll standard`) start each game
  with the standard opening roll instead: from the game's stream, the first
  seat draws one die, then the other seat one, again while they tie; the
  higher die moves first and plays the pair, written in that draw order
  (first seat's die first) as the game's first roll.
- Every later checker turn, including one with no legal move, draws two
  dice, written in draw order as `dd:`; cube actions draw nothing.
- The generator is Rust `rand` 0.9's `StdRng::seed_from_u64(seed)`: the seed
  expanded to a 32-byte ChaCha key with PCG32 (rand_core's seed_from_u64),
  ChaCha with 12 rounds, a zero nonce and a 64-bit block counter from 0, its
  keystream read as little-endian 32-bit words; a die is
  `random_range(1..=6)` on u8, which rand samples from one u32 with a
  widening multiply (Canon's method, a second u32 only when the low half is
  above 2**32 - 6).
"""

from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

M32 = (1 << 32) - 1
M64 = (1 << 64) - 1
PAIR_SEED_STEP = 12345
MATCH_GAME_SEED_STEP = 1_000_003
# An entry starting this many characters after a move number's ")" is in the
# right column (bg writes it 37 in, GnuBG 29, HedgeHog 37).
SECOND_COLUMN = 18
NAME = re.compile(r"^pair_(\d+)(?:_([ab]))?\.mat$")
TAG = re.compile(r'^;\s*\[(.+?) "(.*)"\]\s*$')
ROLL = re.compile(r"^([1-6])([1-6]):$")


def _rotl32(x: int, k: int) -> int:
    return ((x << k) | (x >> (32 - k))) & M32


def _pcg32_key(state: int) -> list[int]:
    """rand_core 0.9 `seed_from_u64`: eight PCG32 outputs as the 32-byte key."""
    words = []
    for _ in range(8):
        state = (state * 6364136223846793005 + 11634580027462260723) & M64
        xorshifted = (((state >> 18) ^ state) >> 27) & M32
        rot = state >> 59
        words.append(((xorshifted >> rot) | (xorshifted << ((32 - rot) & 31))) & M32)
    return words


def _chacha12_block(key: list[int], counter: int) -> list[int]:
    s = [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574, *key]
    s += [counter & M32, (counter >> 32) & M32, 0, 0]
    x = list(s)

    def qr(a: int, b: int, c: int, d: int) -> None:
        x[a] = (x[a] + x[b]) & M32
        x[d] = _rotl32(x[d] ^ x[a], 16)
        x[c] = (x[c] + x[d]) & M32
        x[b] = _rotl32(x[b] ^ x[c], 12)
        x[a] = (x[a] + x[b]) & M32
        x[d] = _rotl32(x[d] ^ x[a], 8)
        x[c] = (x[c] + x[d]) & M32
        x[b] = _rotl32(x[b] ^ x[c], 7)

    for _ in range(6):
        qr(0, 4, 8, 12)
        qr(1, 5, 9, 13)
        qr(2, 6, 10, 14)
        qr(3, 7, 11, 15)
        qr(0, 5, 10, 15)
        qr(1, 6, 11, 12)
        qr(2, 7, 8, 13)
        qr(3, 4, 9, 14)
    return [(x[i] + s[i]) & M32 for i in range(16)]


class DeterministicRng:
    """bg's `DeterministicRng::new(seed)` (Rust rand 0.9 StdRng), dice only."""

    def __init__(self, seed: int) -> None:
        self._key = _pcg32_key(seed & M64)
        self._counter = 0
        self._buf: list[int] = []
        self._pos = 0

    def next_u32(self) -> int:
        if self._pos == len(self._buf):
            self._buf = _chacha12_block(self._key, self._counter)
            self._counter += 1
            self._pos = 0
        v = self._buf[self._pos]
        self._pos += 1
        return v

    def roll_die(self) -> int:
        """rand 0.9 `random_range(1..=6)` for u8."""
        m = self.next_u32() * 6
        hi, lo = m >> 32, m & M32
        if lo > (-6) & M32:
            if lo + ((self.next_u32() * 6) >> 32) > M32:
                hi += 1
        return hi + 1

    def roll_dice(self) -> tuple[int, int]:
        return self.roll_die(), self.roll_die()

    def opening_roll(self) -> tuple[int, int]:
        """The standard opening roll: (first seat's die, other seat's die),
        drawn again while they tie."""
        while True:
            first, other = self.roll_die(), self.roll_die()
            if first != other:
                return first, other


def parse(text: str) -> dict:
    """Tags, match length and, per game, the rolls in play order with their
    columns (0 = left)."""
    tags: dict[str, str] = {}
    length = None
    games: list[list[tuple[int, tuple[int, int]]]] = []
    for raw in text.splitlines():
        line = raw.rstrip()
        t = line.lstrip()
        if not t:
            continue
        if t.startswith(";"):
            m = TAG.match(t)
            if m:
                tags.setdefault(m.group(1), m.group(2))
            continue
        if t.endswith("point match") and length is None:
            length = int(t.split()[0])
            continue
        if t.startswith("Game "):
            games.append([])
            continue
        m = re.match(r"^\d+\)", t)
        if not m or not games:
            continue
        start = len(line) - len(t) + m.end()
        for tok in re.finditer(r"\S+", line[start:]):
            r = ROLL.match(tok.group())
            if r:
                col = int(tok.start() >= SECOND_COLUMN)
                games[-1].append((col, (int(r.group(1)), int(r.group(2)))))
    if length is None:
        raise ValueError("no 'N point match' line")
    return {"tags": tags, "length": length, "games": games}


def check_file(path: Path, base_seed: int) -> tuple[list[str], int, int]:
    """Problems of one file (empty: its dice follow from the seed), and its
    numbers of games and rolls."""
    m = NAME.match(path.name)
    if not m:
        return [f"{path.name}: not a pair_NNNNNN[_a|_b].mat name"], 0, 0
    pair, seat = int(m.group(1)), m.group(2)
    pair_seed = (base_seed + pair * PAIR_SEED_STEP) & M64
    try:
        f = parse(path.read_text())
    except (OSError, ValueError) as e:
        return [f"{path.name}: {e}"], 0, 0
    bad = []
    tags = f["tags"]
    for key, want in (
        ("Base Seed", base_seed),
        ("Pair", pair),
        ("Pair Seed", pair_seed),
    ):
        if key in tags and tags[key] != str(want):
            bad.append(f"{path.name}: tag {key} is {tags[key]}, expected {want}")
    games = f["games"]
    is_match = f["length"] > 0
    if is_match != (seat is not None):
        kind = "match" if seat else "money pair"
        bad.append(f"{path.name}: a {f['length']}-point file named like a {kind}")
        return bad, len(games), 0
    if not is_match and len(games) != 2:
        bad.append(f"{path.name}: a money pair holds 2 games, found {len(games)}")
    if is_match and tags.get("Seat", seat) != seat:
        bad.append(f"{path.name}: tag Seat is {tags.get('Seat')}, the name says {seat}")
    opening = tags.get("Opening Roll", "none")
    if opening not in ("none", "standard"):
        return [*bad, f"{path.name}: unknown Opening Roll {opening!r}"], len(games), 0
    rolls = 0
    for k, game in enumerate(games):
        if is_match:
            seed = (pair_seed + k * MATCH_GAME_SEED_STEP) & M64
            first = (k + (seat == "b")) % 2
        else:
            seed, first = pair_seed, k % 2
        rng = DeterministicRng(seed)
        wants = []
        if opening == "standard":
            wants.append(rng.opening_roll())
            if wants[0][1] > wants[0][0]:
                first = 1 - first  # the other seat's die is higher
        if game and game[0][0] != first:
            side = "player 1 (left)" if first == 0 else "player 2 (right)"
            bad.append(f"{path.name} game {k + 1}: {side} should move first")
        for i, (col, dice) in enumerate(game):
            want = wants.pop(0) if wants else rng.roll_dice()
            rolls += 1
            if dice != want:
                bad.append(
                    f"{path.name} game {k + 1} roll {i + 1}: {dice[0]}{dice[1]}, seed "
                    f"{seed} rolls {want[0]}{want[1]}"
                )
                break
            if i and col == game[i - 1][0]:
                bad.append(f"{path.name} game {k + 1} roll {i + 1}: same side twice")
                break
    return bad, len(games), rolls


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument(
        "--seed",
        required=True,
        help="the run's --seed (or --mat-base-seed): decimal, or hex with 0x",
    )
    ap.add_argument("--games", required=True, type=Path, help="directory of .mat files")
    args = ap.parse_args(argv)
    base = int(args.seed, 0) & M64
    paths = sorted(
        (p for p in args.games.rglob("*.mat") if NAME.match(p.name)),
        key=lambda p: p.name,
    )
    bad_files, problems, games, rolls = [], [], 0, 0
    for p in paths:
        bad, g, r = check_file(p, base)
        games += g
        rolls += r
        if bad:
            bad_files.append(p.name)
            problems += bad
    print(
        f"{len(paths)} files ({games} games, {rolls} rolls) checked, "
        f"{len(bad_files)} with dice that do not follow from seed {args.seed}"
    )
    for msg in problems[:20]:
        print("  " + msg)
    return 1 if bad_files or not paths else 0


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