#!/usr/bin/env python3
"""Independently verify a Twirlseed auditable-draw receipt offline."""

from __future__ import annotations

import hashlib
import json
import sys
import unicodedata
from pathlib import Path
from typing import Any

from py_ecc.bls import G2Basic

PROTOCOL = "twirlseed-audit-v1"
ALGORITHM = "sha256-stream-v1"
FORMAT = "twirlseed-auditable-draw-receipt"
CHAIN_HASH = "8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce"
PUBLIC_KEY = bytes.fromhex("868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31")
STREAM_DOMAIN = b"TWIRLSEED-AUDIT-STREAM\x00v1\x00"
BLOCK_DOMAIN = b"TWIRLSEED-AUDIT-BLOCK\x00v1\x00"
WORD_SPACE = 2**32
MAX_SAFE_INTEGER = 2**53 - 1
CARD_DECK_COUNTS = {1, 2, 4, 6, 8}


def field(name: str, value: Any) -> bytes:
    raw = str(value).encode("utf-8")
    return name.encode("ascii") + b":" + str(len(raw)).encode("ascii") + b":" + raw + b"\n"


def validate_manifest(manifest: dict[str, Any]) -> None:
    if set(manifest) != {"protocol", "algorithm", "tool", "chainHash", "round", "settings"}:
        raise ValueError("manifest fields are missing or unexpected")
    if manifest["protocol"] != PROTOCOL or manifest["algorithm"] != ALGORITHM:
        raise ValueError("unsupported protocol or algorithm")
    if manifest["chainHash"] != CHAIN_HASH:
        raise ValueError("unsupported drand chain")
    if type(manifest["round"]) is not int or not (1 <= manifest["round"] <= 2**53 - 1):
        raise ValueError("invalid beacon round")
    tool = manifest["tool"]
    settings = manifest["settings"]
    if not isinstance(settings, dict):
        raise ValueError("settings must be an object")
    if tool == "coin":
        if set(settings) != {"count"} or type(settings["count"]) is not int or not (1 <= settings["count"] <= 100):
            raise ValueError("invalid coin settings")
    elif tool == "number":
        if set(settings) != {"from", "to", "count", "unique", "order"}:
            raise ValueError("invalid number settings")
        low, high, count = settings["from"], settings["to"], settings["count"]
        if (
            type(low) is not int
            or type(high) is not int
            or not (-MAX_SAFE_INTEGER <= low <= MAX_SAFE_INTEGER)
            or not (-MAX_SAFE_INTEGER <= high <= MAX_SAFE_INTEGER)
            or high < low
            or high - low + 1 > WORD_SPACE
        ):
            raise ValueError("invalid number bounds")
        if type(count) is not int or not (1 <= count <= 1000) or type(settings["unique"]) is not bool or settings["order"] not in ("draw", "sorted"):
            raise ValueError("invalid number options")
        if settings["unique"] and count > high - low + 1:
            raise ValueError("unique draw exceeds the number range")
    elif tool == "dice":
        if set(settings) != {"count", "sides"} or type(settings["count"]) is not int or type(settings["sides"]) is not int or not (1 <= settings["count"] <= 20 and 2 <= settings["sides"] <= 1000):
            raise ValueError("invalid dice settings")
    elif tool == "choice":
        choices = settings.get("choices")
        if set(settings) != {"choices"} or not isinstance(choices, list) or not (2 <= len(choices) <= 100):
            raise ValueError("choice draw needs 2 to 100 entries")
        for choice in choices:
            if not isinstance(choice, str) or not choice or choice != unicodedata.normalize("NFC", choice) or len(choice.encode("utf-8")) > 256:
                raise ValueError("invalid choice entry")
            if any(0xD800 <= ord(char) <= 0xDFFF for char in choice):
                raise ValueError("choice contains an unpaired surrogate")
    elif tool == "cards":
        legacy = set(settings) == {"count", "deck"} and type(settings.get("count")) is int and 1 <= settings["count"] <= 52
        previous_hands = (
            set(settings) == {"players", "each", "deck"}
            and type(settings.get("players")) is int
            and type(settings.get("each")) is int
            and 1 <= settings["players"] <= 8
            and 1 <= settings["each"] <= 13
            and settings["players"] * settings["each"] <= 52
        )
        hands = (
            set(settings) == {"players", "each", "decks", "deck"}
            and type(settings.get("players")) is int
            and type(settings.get("each")) is int
            and type(settings.get("decks")) is int
            and 1 <= settings["players"] <= 8
            and 1 <= settings["each"] <= 13
            and settings["decks"] in CARD_DECK_COUNTS
            and settings["players"] * settings["each"] <= 52 * settings["decks"]
        )
        if not (legacy or previous_hands or hands) or settings["deck"] != "standard-52-v1":
            raise ValueError("invalid card settings")
    else:
        raise ValueError("unsupported draw type")


def canonical_manifest(manifest: dict[str, Any]) -> bytes:
    validate_manifest(manifest)
    chunks = [b"TWIRLSEED-AUDIT-MANIFEST\n1\n"]
    chunks.extend([
        field("protocol", manifest["protocol"]),
        field("algorithm", manifest["algorithm"]),
        field("tool", manifest["tool"]),
        field("chain-hash", manifest["chainHash"]),
        field("round", manifest["round"]),
    ])
    settings = manifest["settings"]
    if manifest["tool"] == "coin":
        chunks.append(field("count", settings["count"]))
    elif manifest["tool"] == "number":
        chunks.extend([
            field("from", settings["from"]),
            field("to", settings["to"]),
            field("count", settings["count"]),
            field("unique", "true" if settings["unique"] else "false"),
            field("order", settings["order"]),
        ])
    elif manifest["tool"] == "dice":
        chunks.extend([field("count", settings["count"]), field("sides", settings["sides"])])
    elif manifest["tool"] == "choice":
        chunks.append(field("choice-count", len(settings["choices"])))
        chunks.extend(field("choice", choice) for choice in settings["choices"])
    elif manifest["tool"] == "cards" and "players" in settings:
        chunks.extend([field("players", settings["players"]), field("each", settings["each"])])
        if "decks" in settings:
            chunks.append(field("decks", settings["decks"]))
        chunks.append(field("deck", settings["deck"]))
    else:
        chunks.extend([field("count", settings["count"]), field("deck", settings["deck"])])
    return b"".join(chunks)


class ByteStream:
    def __init__(self, seed: bytes) -> None:
        self.seed = seed
        self.counter = 0
        self.block = b""
        self.offset = 0

    def next_u32(self) -> int:
        if self.offset + 4 > len(self.block):
            if self.counter > 0xFFFFFFFF:
                raise ValueError("audit stream exhausted")
            self.block = hashlib.sha256(BLOCK_DOMAIN + self.seed + self.counter.to_bytes(4, "big")).digest()
            self.counter += 1
            self.offset = 0
        value = int.from_bytes(self.block[self.offset:self.offset + 4], "big")
        self.offset += 4
        return value

    def below(self, bound: int) -> int:
        if type(bound) is not int or not (1 <= bound <= WORD_SPACE):
            raise ValueError("invalid bounded random choice")
        limit = WORD_SPACE - WORD_SPACE % bound
        value = self.next_u32()
        while value >= limit:
            value = self.next_u32()
        return value % bound


def derive_result(manifest: dict[str, Any], signature: bytes, commitment: bytes) -> dict[str, Any]:
    seed = hashlib.sha256(
        STREAM_DOMAIN
        + bytes.fromhex(manifest["chainHash"])
        + manifest["round"].to_bytes(8, "big")
        + signature
        + commitment
    ).digest()
    stream = ByteStream(seed)
    settings = manifest["settings"]
    tool = manifest["tool"]
    if tool == "coin":
        return {"type": "coin", "values": ["heads" if stream.below(2) == 0 else "tails" for _ in range(settings["count"])]}
    if tool == "number":
        values: list[int] = []
        seen: set[int] = set()
        while len(values) < settings["count"]:
            value = settings["from"] + stream.below(settings["to"] - settings["from"] + 1)
            if not settings["unique"] or value not in seen:
                values.append(value)
                seen.add(value)
        if settings["order"] == "sorted":
            values.sort()
        return {"type": "number", "values": values}
    if tool == "dice":
        return {"type": "dice", "sides": settings["sides"], "values": [1 + stream.below(settings["sides"]) for _ in range(settings["count"])]}
    if tool == "choice":
        index = stream.below(len(settings["choices"]))
        return {"type": "choice", "index": index, "value": settings["choices"][index]}
    ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    deck_count = settings.get("decks", 1)
    deck = [rank + suit for _ in range(deck_count) for suit in "SHDC" for rank in ranks]
    for index in range(len(deck) - 1, 0, -1):
        other = stream.below(index + 1)
        deck[index], deck[other] = deck[other], deck[index]
    if "players" in settings:
        hands = [
            {"player": index + 1, "cards": deck[index * settings["each"]:(index + 1) * settings["each"]]}
            for index in range(settings["players"])
        ]
        result = {"type": "cards", "deck": settings["deck"], "players": settings["players"], "each": settings["each"], "hands": hands, "shuffledOrder": deck}
        if "decks" in settings:
            result["decks"] = settings["decks"]
        return result
    return {"type": "cards", "deck": settings["deck"], "dealt": deck[:settings["count"]], "shuffledOrder": deck}


def same_json(left: Any, right: Any) -> bool:
    if type(left) is not type(right):
        return False
    if isinstance(left, dict):
        return left.keys() == right.keys() and all(same_json(left[key], right[key]) for key in left)
    if isinstance(left, list):
        return len(left) == len(right) and all(same_json(a, b) for a, b in zip(left, right))
    return left == right


def verify_receipt(receipt: dict[str, Any]) -> dict[str, Any]:
    if not isinstance(receipt, dict) or set(receipt) != {"format", "version", "commitment", "manifest", "beacon", "result"}:
        raise ValueError("receipt fields are missing or unexpected")
    if receipt["format"] != FORMAT or receipt["version"] != 1:
        raise ValueError("unsupported receipt format")
    manifest = receipt["manifest"]
    manifest_bytes = canonical_manifest(manifest)
    commitment = hashlib.sha256(manifest_bytes).digest()
    if receipt["commitment"] != commitment.hex():
        raise ValueError("committed settings do not match the receipt hash")

    beacon = receipt["beacon"]
    if not isinstance(beacon, dict) or set(beacon) != {"chainHash", "round", "signature", "previousSignature", "randomness"}:
        raise ValueError("beacon fields are missing or unexpected")
    if beacon["chainHash"] != CHAIN_HASH or beacon["round"] != manifest["round"]:
        raise ValueError("beacon chain or round does not match the commitment")
    signature = bytes.fromhex(beacon["signature"])
    previous_signature = bytes.fromhex(beacon["previousSignature"])
    if len(signature) != 96 or len(previous_signature) != 96:
        raise ValueError("beacon signatures have the wrong length")
    if hashlib.sha256(signature).hexdigest() != beacon["randomness"]:
        raise ValueError("beacon randomness does not match its signature")
    message = hashlib.sha256(previous_signature + beacon["round"].to_bytes(8, "big")).digest()
    try:
        valid_signature = G2Basic.Verify(PUBLIC_KEY, message, signature)
    except Exception as error:  # malformed points are invalid evidence
        raise ValueError("beacon signature could not be decoded") from error
    if not valid_signature:
        raise ValueError("drand BLS signature is invalid")

    result = derive_result(manifest, signature, commitment)
    if not same_json(result, receipt["result"]):
        raise ValueError("receipt result does not match the committed draw")
    return {"valid": True, "commitment": commitment.hex(), "chainHash": CHAIN_HASH, "round": beacon["round"], "result": result}


def main() -> int:
    if len(sys.argv) != 2 or sys.argv[1] in ("-h", "--help"):
        print("Usage: python verify-auditable-draw.py RECEIPT.json", file=sys.stderr)
        return 2
    try:
        receipt = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
        report = verify_receipt(receipt)
    except Exception as error:
        print(f"INVALID: {error}", file=sys.stderr)
        return 1
    print(json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
