"""How often each chess rule actually happens, counted from the Lichess database.

Reads a Lichess monthly PGN dump (https://database.lichess.org, CC0) on stdin,
replays every game and counts castling, en passant, promotions and how games end,
split by time control and average rating. Writes JSON totals to stdout.

    zstd -dc lichess_db_standard_rated_2026-10.pgn.zst | python3 lichess-rule-frequency.py > counts.json
    python3 lichess-rule-frequency.py --selftest

Needs python-chess (pip install chess). WORKERS sets the process count (default 3).
"""

import json
import os
import re
import sys
from collections import Counter
from multiprocessing import Pool

import chess

COMMENT = re.compile(r"\{[^}]*\}")
MOVE_NO = re.compile(r"^\d+\.+$")
SUFFIX = re.compile(r"[?!]+$")
RESULTS = {"1-0", "0-1", "1/2-1/2", "*"}
BANDS = [(1200, "<1200"), (1600, "1200-1599"), (2000, "1600-1999"), (2400, "2000-2399")]


def band(avg):
    for top, name in BANDS:
        if avg < top:
            return name
    return "2400+"


def speed(event):
    for s in ("UltraBullet", "Bullet", "Blitz", "Rapid", "Classical", "Correspondence"):
        if s in event:
            return s.lower()
    return "other"


def ending(board, termination, result):
    if termination == "Abandoned":
        return "abandoned"
    if board.is_checkmate():
        return "checkmate"
    if board.is_stalemate():
        return "stalemate"
    if termination == "Time forfeit":
        # Lichess scores a flag as a draw when the opponent can't possibly mate.
        return "timeout_draw" if result == "1/2-1/2" else "timeout"
    if result == "1/2-1/2":
        if board.is_insufficient_material():
            return "insufficient_material"
        if board.is_repetition(3):
            return "threefold"
        if board.halfmove_clock >= 100:
            return "fifty_move"
        return "draw_agreed"
    if termination == "Normal":
        return "resignation"
    return "other"


def count_game(headers, movetext):
    """Returns a Counter of events for one game, or None if it can't be replayed."""
    if "SetUp" in headers or headers.get("Variant", "Standard") != "Standard":
        return None
    if "BOT" in (headers.get("WhiteTitle"), headers.get("BlackTitle")):
        return Counter(bot_games=1)  # Lichess bot accounts: counted, not studied.
    board = chess.Board()
    c = Counter()
    ep_chance = False
    try:
        for tok in COMMENT.sub(" ", movetext).split():
            if MOVE_NO.match(tok) or tok in RESULTS or tok.startswith("$"):
                continue
            move = board.parse_san(SUFFIX.sub("", tok))
            mover = "w" if board.turn else "b"
            if board.is_en_passant(move):
                c["ep_moves"] += 1
            if board.is_castling(move):
                c["castle_" + ("short" if board.is_kingside_castling(move) else "long")] += 1
                c["castled_" + mover] = 1
            if move.promotion:
                piece = chess.piece_name(move.promotion)
                c["promo_" + piece] += 1
                if move.promotion != chess.QUEEN:
                    # Was the underpromotion forced? Queen stalemates, or knight checks.
                    q = chess.Move(move.from_square, move.to_square, chess.QUEEN)
                    board.push(q)
                    if board.is_stalemate():
                        c["under_avoids_stalemate"] += 1
                    board.pop()
                    if move.promotion == chess.KNIGHT and board.gives_check(move):
                        c["under_knight_check"] += 1
            board.push(move)
            c["plies"] += 1
            if board.ep_square is not None and board.has_legal_en_passant():
                c["ep_chances"] += 1
                ep_chance = True
    except ValueError:
        return None

    c["games"] = 1
    c["end_" + ending(board, headers.get("Termination", ""), headers.get("Result", ""))] = 1
    if ep_chance:
        c["games_ep_chance"] = 1
    if c["ep_moves"]:
        c["games_ep"] = 1
    if any(k.startswith("promo_") for k in c):
        c["games_promo"] = 1
    if any(k.startswith("promo_") and k != "promo_queen" for k in c):
        c["games_underpromo"] = 1
    castled = c.pop("castled_w", 0) + c.pop("castled_b", 0)
    c["games_castled_" + ("both" if castled == 2 else "one" if castled == 1 else "none")] = 1
    return c


HEADER = re.compile(r'^\[(\w+) "(.*)"\]$')


def count_batch(games):
    out = {}
    for header_lines, movetext in games:
        headers = dict(m.groups() for m in map(HEADER.match, header_lines) if m)
        c = count_game(headers, movetext)
        key = speed(headers.get("Event", ""))
        try:
            avg = (int(headers["WhiteElo"]) + int(headers["BlackElo"])) / 2
            key += "|" + band(avg)
        except (KeyError, ValueError):
            key += "|unrated"
        out.setdefault(key, Counter()).update(c if c else {"skipped": 1})
    return out


def read_games(stream):
    """Yields (header_lines, movetext). Drops the last game: a cut-off file ends mid-game."""
    headers, moves, pending = [], [], None
    for line in stream:
        line = line.rstrip("\n")
        if line.startswith("[Event ") and moves:
            if pending:
                yield pending
            pending = (headers, " ".join(moves))
            headers, moves = [], []
        if line.startswith("["):
            headers.append(line)
        elif line:
            moves.append(line)
    if pending:
        yield pending


def batches(games, size=2000):
    batch = []
    for g in games:
        batch.append(g)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch


def main():
    totals = {}
    done = 0
    stream = open(sys.stdin.fileno(), encoding="utf-8", errors="replace")
    with Pool(int(os.environ.get("WORKERS", 3))) as pool:
        for part in pool.imap_unordered(count_batch, batches(read_games(stream))):
            for key, c in part.items():
                totals.setdefault(key, Counter()).update(c)
                done += c["games"] + c["skipped"] + c["bot_games"]
            if done % 500_000 < 2000:
                print(f"{done:,} games", file=sys.stderr, flush=True)
    json.dump({k: dict(v) for k, v in sorted(totals.items())}, sys.stdout, indent=1)


def selftest():
    h = {"Termination": "Normal", "Result": "1-0"}
    # En passant chance taken, both sides castle short.
    c = count_game(h, "1. e4 Nf6 2. e5 d5 3. exd6 exd6 4. Nf3 Be7 5. Bc4 O-O 6. O-O 1-0")
    assert c["ep_moves"] == 1 and c["ep_chances"] == 1 and c["games_castled_both"] == 1, c
    # Chance offered and ignored; clock comments and annotations are stripped.
    c = count_game(h, "1. e4 { [%clk 0:03:00] } Nf6 2. e5?! d5 3. Nf3! 1-0")
    assert c["ep_chances"] == 1 and not c["ep_moves"] and c["plies"] == 5, c
    # Fool's mate.
    c = count_game(h, "1. f3 e5 2. g4 Qh4# 0-1")
    assert c["end_checkmate"] == 1 and c["games_castled_none"] == 1, c
    # Knight underpromotion with check.
    c = count_game(h, "1. e4 d5 2. exd5 c6 3. dxc6 Nf6 4. cxb7 Nbd7 5. bxa8=N Qb6 1-0")
    assert c["promo_knight"] == 1 and c["games_underpromo"] == 1, c
    # Stalemate (Sam Loyd's ten-move stalemate).
    c = count_game({"Termination": "Normal", "Result": "1/2-1/2"},
                   "1. e3 a5 2. Qh5 Ra6 3. Qxa5 h5 4. h4 Rah6 5. Qxc7 f6 6. Qxd7+ Kf7 "
                   "7. Qxb7 Qd3 8. Qxb8 Qh7 9. Qxc8 Kg6 10. Qe6 1/2-1/2")
    assert c["end_stalemate"] == 1, c
    assert count_game({"SetUp": "1"}, "1. e4") is None
    assert count_game({"WhiteTitle": "BOT"}, "1. e4 e5") == {"bot_games": 1}
    assert count_game(h, "1. e4 e4") is None
    print("selftest ok")


if __name__ == "__main__":
    selftest() if "--selftest" in sys.argv else main()
