"""
fairdice - provably fair, seed-based randomness (FairDice protocol v1).

Python reference implementation, standard library only. Produces exactly the
same results as the JavaScript and C# SDKs (see spec/test-vectors.json), so
proofs made here verify on https://fairdice.ir and vice versa.

    from fairdice import FairDice

    fd = FairDice(dice="2d6", game="Backgammon")
    print(fd.commitment)      # show players before the game
    fd.roll()                 # [3, 5]  - offline, no API calls
    ...
    print(fd.url())           # https://fairdice.ir/v/<token>  (reveals the seed)
"""

from __future__ import annotations

import base64
import hashlib
import hmac
import json
import re
import secrets
import time
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union

__all__ = [
    "FairDice", "ByteStream", "commitment_of", "compute_draw", "build_deck",
    "encode_token", "decode_token", "verify", "replay", "PRESETS",
]
__version__ = "1.0.0"

DEFAULT_BASE_URL = "https://fairdice.ir"
TWO_32 = 4294967296
MAX_COUNT = 10000
MAX_DECK = 100000
MAX_PICK = 100000
SEED_RE = re.compile(r"^[0-9a-f]{64}$")

Item = Union[str, int]


# --------------------------------------------------------------------- stream

class ByteStream:
    """HMAC-SHA256(key=serverSeed, msg=f"{clientSeed}:{nonce}:{block}") for block = 0, 1, 2..."""

    def __init__(self, server_seed: str, client_seed: str, nonce: int):
        self._key = server_seed.encode("utf-8")
        self._prefix = f"{client_seed}:{nonce}:"
        self._block = 0
        self._buf = b""
        self._pos = 0

    def byte(self) -> int:
        if self._pos >= len(self._buf):
            self._buf = hmac.new(self._key, (self._prefix + str(self._block)).encode("utf-8"), hashlib.sha256).digest()
            self._block += 1
            self._pos = 0
        b = self._buf[self._pos]
        self._pos += 1
        return b

    def uint32(self) -> int:
        return (self.byte() << 24) | (self.byte() << 16) | (self.byte() << 8) | self.byte()

    def int(self, n: int) -> int:
        """Uniform integer in [0, n) by rejection sampling (no modulo bias)."""
        if not isinstance(n, int) or n < 1 or n > TWO_32:
            raise ValueError("n must be an integer in [1, 2^32]")
        if n == 1:
            return 0
        limit = TWO_32 - (TWO_32 % n)
        while True:
            x = self.uint32()
            if x < limit:
                return x % n

    def float(self) -> float:
        a = self.uint32() >> 5
        b = self.uint32() >> 6
        return (a * 67108864 + b) / 9007199254740992


# --------------------------------------------------------------------- decks

SUITS = ["S", "H", "D", "C"]
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"]


def _cards(ranks: Sequence[str]) -> List[str]:
    return [r + s for s in SUITS for r in ranks]


def _dominoes(mx: int) -> List[str]:
    return [f"{a}-{b}" for a in range(mx + 1) for b in range(a, mx + 1)]


def build_deck(spec: str) -> List[Item]:
    fixed = {
        "std52": lambda: _cards(RANKS),
        "std54": lambda: _cards(RANKS) + ["XR", "XB"],
        "std36": lambda: _cards(["A", "6", "7", "8", "9", "T", "J", "Q", "K"]),
        "std32": lambda: _cards(["A", "7", "8", "9", "T", "J", "Q", "K"]),
        "dom6": lambda: _dominoes(6),
        "dom9": lambda: _dominoes(9),
        "dom12": lambda: _dominoes(12),
    }
    if spec in fixed:
        return list(fixed[spec]())
    m = re.fullmatch(r"shoe:(\d{1,2})", spec)
    if m:
        k = int(m.group(1))
        if not 1 <= k <= 16:
            raise ValueError("shoe:N supports 1..16 decks")
        return _cards(RANKS) * k
    m = re.fullmatch(r"n:(\d{1,6})", spec)
    if m:
        n = int(m.group(1))
        if not 1 <= n <= MAX_DECK:
            raise ValueError(f"n:N supports 1..{MAX_DECK}")
        return list(range(1, n + 1))
    raise ValueError(f'Unknown deck spec "{spec}"')


# --------------------------------------------------------------------- ops

def _is_int(x: Any) -> bool:
    return isinstance(x, int) and not isinstance(x, bool) and abs(x) <= 9007199254740991


def _int_in(x: Any, lo: int, hi: int, name: str) -> int:
    if not _is_int(x) or x < lo or x > hi:
        raise ValueError(f"{name} must be an integer in [{lo}, {hi}]")
    return x


def validate_op(code: str, params: list) -> None:
    def arity(n: int) -> None:
        if not isinstance(params, list) or len(params) != n:
            raise ValueError(f'op "{code}" expects {n} params')

    if code == "d":
        arity(2); _int_in(params[0], 2, 1_000_000_000, "sides"); _int_in(params[1], 1, MAX_COUNT, "count")
    elif code in ("c", "f"):
        arity(1); _int_in(params[0], 1, MAX_COUNT, "count")
    elif code == "i":
        arity(3)
        mn, mx = params[0], params[1]
        if not _is_int(mn) or not _is_int(mx) or mx < mn:
            raise ValueError("min/max must be integers with min <= max")
        if mx - mn + 1 > TWO_32:
            raise ValueError("range must be <= 2^32")
        _int_in(params[2], 1, MAX_COUNT, "count")
    elif code == "s":
        arity(1); build_deck(params[0])
    elif code == "dl":
        arity(3)
        size = len(build_deck(params[0]))
        hands = _int_in(params[1], 1, 1000, "hands")
        per = _int_in(params[2], 1, MAX_DECK, "perHand")
        if hands * per > size:
            raise ValueError(f"cannot deal {hands}x{per} from a deck of {size}")
    elif code == "p":
        arity(3)
        n = _int_in(params[0], 1, TWO_32, "n")
        _int_in(params[1], 1, min(n, MAX_PICK), "k")
        _int_in(params[2], -9007199254740991 + TWO_32, 9007199254740991 - TWO_32, "offset")
    elif code == "w":
        arity(2)
        ws = params[0]
        if not isinstance(ws, list) or not 1 <= len(ws) <= 10000:
            raise ValueError("weights must be a list of 1..10000 integers")
        total = sum(_int_in(w, 0, TWO_32, "weight") for w in ws)
        if not 1 <= total <= TWO_32:
            raise ValueError("sum of weights must be in [1, 2^32]")
        _int_in(params[1], 1, MAX_COUNT, "count")
    elif code == "r":
        arity(2)
        if params[0] not in ("eu", "us"):
            raise ValueError('roulette variant must be "eu" or "us"')
        _int_in(params[1], 1, MAX_COUNT, "count")
    elif code == "b":
        arity(1); _int_in(params[0], 1, 4096, "length")
    else:
        raise ValueError(f'Unknown op code "{code}"')


def pick_indices(stream: ByteStream, n: int, k: int) -> List[int]:
    """Sparse forward Fisher-Yates: step i swaps i with j = i + int(n - i)."""
    moved: Dict[int, int] = {}
    out = []
    for i in range(k):
        j = i + stream.int(n - i)
        at_i = moved.get(i, i)
        at_j = moved.get(j, j)
        moved[j] = at_i
        moved.pop(i, None)
        out.append(at_j)
    return out


def execute_op(stream: ByteStream, code: str, params: list) -> Any:
    if code == "d":
        sides, count = params
        return [1 + stream.int(sides) for _ in range(count)]
    if code == "c":
        return ["H" if stream.int(2) == 0 else "T" for _ in range(params[0])]
    if code == "i":
        mn, mx, count = params
        return [mn + stream.int(mx - mn + 1) for _ in range(count)]
    if code == "f":
        return [stream.float() for _ in range(params[0])]
    if code == "s":
        deck = build_deck(params[0])
        return [deck[i] for i in pick_indices(stream, len(deck), len(deck))]
    if code == "dl":
        deck = build_deck(params[0])
        hands, per = params[1], params[2]
        sh = [deck[i] for i in pick_indices(stream, len(deck), len(deck))]
        return {"hands": [sh[h * per:(h + 1) * per] for h in range(hands)], "rest": sh[hands * per:]}
    if code == "p":
        n, k, offset = params
        return [i + offset for i in pick_indices(stream, n, k)]
    if code == "w":
        ws, count = params
        total = sum(ws)
        out = []
        for _ in range(count):
            r = stream.int(total)
            idx = 0
            while r >= ws[idx]:
                r -= ws[idx]
                idx += 1
            out.append(idx)
        return out
    if code == "r":
        us = params[0] == "us"
        out: List[Item] = []
        for _ in range(params[1]):
            x = stream.int(38 if us else 37)
            out.append("00" if x == 37 else x)
        return out
    if code == "b":
        return "".join(f"{stream.byte():02x}" for _ in range(params[0]))
    raise ValueError(f'Unknown op code "{code}"')


def parse_dice(notation: str) -> Tuple[int, int]:
    m = re.fullmatch(r"\s*(\d*)\s*[dD]\s*(\d+)\s*", notation)
    if not m:
        raise ValueError(f'Invalid dice notation "{notation}"')
    count = int(m.group(1)) if m.group(1) else 1
    sides = int(m.group(2))
    validate_op("d", [sides, count])
    return sides, count


# --------------------------------------------------------------------- proof

def commitment_of(server_seed: str) -> str:
    return hashlib.sha256(server_seed.encode("utf-8")).hexdigest()


def compute_draw(server_seed: str, client_seed: str, nonce: int, code: str, params: list) -> Any:
    validate_op(code, params)
    return execute_op(ByteStream(server_seed, client_seed, nonce), code, params)


def _b64url(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).decode("ascii").rstrip("=")


def _unb64url(s: str) -> bytes:
    s = s.strip().replace("+", "-").replace("/", "_").rstrip("=")
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def encode_token(proof: dict) -> str:
    return _b64url(json.dumps(proof, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))


def decode_token(token_or_url: str) -> dict:
    s = token_or_url.strip()
    m = re.search(r"/v/([A-Za-z0-9_\-+/=]+)", s) or re.search(r"#([A-Za-z0-9_\-+/=]+)$", s)
    if m:
        s = m.group(1)
    proof = json.loads(_unb64url(s).decode("utf-8"))
    validate_proof(proof)
    return proof


def validate_proof(p: dict) -> None:
    if not isinstance(p, dict) or p.get("v") != 1:
        raise ValueError("unsupported proof version")
    if not isinstance(p.get("s"), str) or not SEED_RE.match(p["s"]):
        raise ValueError("s must be 64 lowercase hex chars")
    if not isinstance(p.get("c"), str) or not 1 <= len(p["c"]) <= 256:
        raise ValueError("c must be a 1..256 char string")
    if not _is_int(p.get("n")) or p["n"] < 0:
        raise ValueError("n must be a non-negative integer")
    if not isinstance(p.get("o"), list):
        raise ValueError("o must be a list")
    for e in p["o"]:
        if not isinstance(e, list) or len(e) != 3 or not _is_int(e[2]) or e[2] < 1:
            raise ValueError("op log entries must be [code, params, times]")
        validate_op(e[0], e[1])


def replay(proof: dict) -> Iterator[dict]:
    index = 0
    for code, params, times in proof["o"]:
        for _ in range(times):
            nonce = proof["n"] + index
            yield {"index": index, "nonce": nonce, "code": code, "params": params,
                   "result": execute_op(ByteStream(proof["s"], proof["c"], nonce), code, params)}
            index += 1


def verify(token_or_proof: Union[str, dict], expected_commitment: Optional[str] = None) -> dict:
    proof = decode_token(token_or_proof) if isinstance(token_or_proof, str) else token_or_proof
    validate_proof(proof)
    commitment = commitment_of(proof["s"])
    draws = list(replay(proof))
    return {
        "proof": proof,
        "commitment": commitment,
        "commitment_matches": None if expected_commitment is None else expected_commitment.strip().lower() == commitment,
        "count": len(draws),
        "draws": draws,
    }


PRESETS: Dict[str, Tuple[str, list]] = {
    "backgammon": ("d", [6, 2]), "yatzy": ("d", [6, 5]), "ludo": ("d", [6, 1]),
    "d20": ("d", [20, 1]), "coin": ("c", [1]), "hokm": ("dl", ["std52", 4, 13]),
    "poker": ("s", ["std52"]), "blackjack": ("s", ["shoe:6"]), "roulette": ("r", ["eu", 1]),
    "lotto649": ("p", [49, 6, 1]), "bingo75": ("p", [75, 75, 1]), "mapseed": ("b", [32]),
}


# --------------------------------------------------------------------- session

class FairDice:
    """One provably fair session (a match, a table, a round of a game)."""

    def __init__(self, server_seed: Optional[str] = None, client_seed: Optional[str] = None, nonce: int = 0,
                 dice: Optional[str] = None, preset: Optional[str] = None, game: Optional[str] = None,
                 meta: Optional[dict] = None, base_url: str = DEFAULT_BASE_URL):
        self.server_seed = (server_seed or secrets.token_hex(32)).lower()
        if not SEED_RE.match(self.server_seed):
            raise ValueError("server_seed must be 64 hex chars")
        self._client_seed = client_seed if client_seed is not None else secrets.token_hex(8)
        if not 1 <= len(self._client_seed) <= 256:
            raise ValueError("client_seed must be 1..256 chars")
        self.first_nonce = nonce
        self.commitment = commitment_of(self.server_seed)
        self.game = game
        self.meta = meta
        self.base_url = base_url.rstrip("/")
        self.created_at = int(time.time())
        self.history: List[dict] = []
        self._log: List[list] = []
        self._count = 0
        self._revealed = False
        self._default: Optional[Tuple[str, list]] = None
        if dice:
            self._default = ("d", list(parse_dice(dice)))
        elif preset:
            self._default = PRESETS[preset]
            self.game = self.game or preset.capitalize()

    @property
    def client_seed(self) -> str:
        return self._client_seed

    @property
    def count(self) -> int:
        return self._count

    @property
    def nonce(self) -> int:
        return self.first_nonce + self._count

    def set_client_seed(self, seed: str) -> "FairDice":
        if self._count:
            raise RuntimeError("set_client_seed() must be called before the first draw")
        if not 1 <= len(seed) <= 256:
            raise ValueError("client_seed must be 1..256 chars")
        self._client_seed = seed
        return self

    def set_player_seeds(self, seeds: Sequence[str]) -> "FairDice":
        return self.set_client_seed("|".join(sorted(str(s) for s in seeds))[:256])

    def draw(self, code: str, params: list) -> Any:
        if self._revealed:
            raise RuntimeError("session was revealed; start a new FairDice")
        validate_op(code, params)
        nonce = self.nonce
        result = execute_op(ByteStream(self.server_seed, self._client_seed, nonce), code, params)
        if self._log and self._log[-1][0] == code and self._log[-1][1] == params:
            self._log[-1][2] += 1
        else:
            self._log.append([code, json.loads(json.dumps(params)), 1])
        self.history.append({"index": self._count, "nonce": nonce, "code": code, "params": params, "result": result})
        self._count += 1
        return result

    def roll(self) -> Any:
        if not self._default:
            raise RuntimeError('no default op; pass dice="2d6" or preset=...')
        return self.draw(self._default[0], list(self._default[1]))

    def dice(self, sides: int = 6, count: int = 1) -> List[int]:
        return self.draw("d", [sides, count])

    def coin(self) -> str:
        return self.draw("c", [1])[0]

    def int(self, mn: int, mx: int) -> int:
        return self.draw("i", [mn, mx, 1])[0]

    def float(self) -> float:
        return self.draw("f", [1])[0]

    def shuffle(self, deck: str = "std52") -> List[Item]:
        return self.draw("s", [deck])

    def deal(self, deck: str, hands: int, per_hand: int) -> dict:
        return self.draw("dl", [deck, hands, per_hand])

    def sample(self, n: int, k: int, offset: int = 1) -> List[int]:
        return self.draw("p", [n, k, offset])

    def lotto(self, k: int, n: int) -> List[int]:
        return self.sample(n, k, 1)

    def pick(self, items: Sequence[Any]) -> Any:
        return items[self.sample(len(items), 1, 0)[0]]

    def weighted(self, weights: List[int]) -> int:
        return self.draw("w", [weights, 1])[0]

    def roulette(self, variant: str = "eu") -> Item:
        return self.draw("r", [variant, 1])[0]

    def bytes(self, length: int = 32) -> str:
        return self.draw("b", [length])

    def state(self) -> dict:
        p: Dict[str, Any] = {"v": 1, "s": self.server_seed, "c": self._client_seed, "n": self.first_nonce,
                             "o": [[c, prm, t] for c, prm, t in self._log]}
        if self.game:
            p["g"] = self.game
        if self.meta:
            p["m"] = self.meta
        p["t"] = self.created_at
        return p

    def reveal(self) -> dict:
        proof = self.state()
        token = encode_token(proof)
        self._revealed = True
        return {"proof": proof, "token": token, "url": f"{self.base_url}/v/{token}",
                "commitment": self.commitment, "count": self._count}

    def token(self) -> str:
        return self.reveal()["token"]

    def url(self) -> str:
        return self.reveal()["url"]

    def commit_url(self) -> str:
        return f"{self.base_url}/c/{self.commitment}"
