#!/usr/bin/env python3
"""Replay both published fixtures with the independently pinned PokerKit path."""

from __future__ import annotations

from importlib.metadata import version
from pathlib import Path
import sys
import warnings

try:
    from pokerkit import HandHistory
except ImportError:
    print("Install the pinned dependency first: python -m pip install pokerkit==0.7.5", file=sys.stderr)
    raise SystemExit(2)

HERE = Path(__file__).resolve().parent
FILES = (
    HERE / "phh-privacy-example-original.phh",
    HERE / "phh-privacy-example-minimized.phh",
)
EXPECTED_POKERKIT_VERSION = "0.7.5"


def card_groups(groups):
    return tuple(tuple(map(str, group)) for group in groups)


def snapshot(state):
    """Record public game-state values that identity metadata cannot affect."""
    pots = tuple(
        (pot.raked_amount, pot.unraked_amount, tuple(pot.player_indices))
        for pot in state.pots
    )
    return (
        tuple(state.stacks),
        tuple(state.bets),
        tuple(state.statuses),
        card_groups(state.hole_cards),
        card_groups(state.board_cards),
        state.street_index,
        tuple(state.actor_indices),
        tuple(state.payoffs),
        pots,
        state.total_pot_amount,
        state.status,
    )


def action_core(value: str) -> str:
    for index, character in enumerate(value):
        if (character == "#"
                and (index == 0 or value[index - 1].isspace())
                and (index == len(value) - 1 or value[index + 1].isspace())):
            value = value[:index]
            break
    return " ".join(value.split())


def replay(path: Path):
    with warnings.catch_warnings(record=True) as captured:
        warnings.simplefilter("always")
        with path.open("rb") as source:
            history = HandHistory.load(source)
        states = [snapshot(state) for state in history]
    return history, states, captured


def main() -> int:
    installed_version = version("pokerkit")
    if installed_version != EXPECTED_POKERKIT_VERSION:
        raise AssertionError(
            f"Expected PokerKit {EXPECTED_POKERKIT_VERSION}; found {installed_version}."
        )
    original, original_states, original_warnings = replay(FILES[0])
    minimized, minimized_states, minimized_warnings = replay(FILES[1])

    original_cores = [action_core(action) for action in original.actions]
    minimized_cores = [action_core(action) for action in minimized.actions]
    if original_cores != minimized_cores:
        raise AssertionError("PokerKit decoded different standardized action cores.")
    if original_states != minimized_states:
        raise AssertionError("A replay snapshot differs after minimization.")
    if len(original.actions) != 18 or len(original_states) != 19:
        raise AssertionError("Unexpected fixture action or state count.")
    if list(original_states[-1][0]) != [86, 98, 116]:
        raise AssertionError("Unexpected final stack vector.")
    if len(original_warnings) != 1 or minimized_warnings:
        raise AssertionError("Unexpected PokerKit warning count for the rich or minimized fixture.")

    print(
        f"PokerKit {installed_version} replay matched: "
        f"{len(original.actions)} actions, {len(original_states)} states, "
        f"final stacks {list(original_states[-1][0])}."
    )
    if original_warnings:
        print(f"PokerKit emitted {len(original_warnings)} warning(s) for the rich source fixture:")
        for item in original_warnings:
            print(f"- {item.message}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (AssertionError, OSError, ValueError) as error:
        print(f"Replay verification failed: {error}", file=sys.stderr)
        raise SystemExit(1)
