#!/usr/bin/env python3
"""Независимая проверка розыгрыша bro9i. Нужен только Python 3, без зависимостей.

    python3 verify.py tickets.txt spins.json

tickets.txt — список билетов «код:вес», опубликован до первого кручения. Его SHA-256 = отпечаток (commit).
spins.json  — кручения по порядку: место и номер раунда drand, названный ДО появления числа.

Для каждого кручения: h = SHA256(commit:число_drand:место), r = h mod сумма весов оставшихся,
веса выкладываются подряд в порядке списка → победитель, он выбывает из следующих кручений.
Число drand скачивается напрямую из сети League of Entropy — его никто из нас не контролирует.
"""
import hashlib
import json
import sys
import urllib.request

CHAIN = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"
HOSTS = ["https://api.drand.sh", "https://drand.cloudflare.com", "https://api2.drand.sh"]


def drand(rnd):
    for h in HOSTS:
        try:
            with urllib.request.urlopen(f"{h}/{CHAIN}/public/{rnd}", timeout=10) as r:
                return json.loads(r.read())["randomness"]
        except Exception:
            continue
    raise SystemExit("drand недоступен")


def main():
    if len(sys.argv) < 3:
        raise SystemExit(__doc__)
    text = open(sys.argv[1], encoding="utf-8", newline="").read()
    spins = json.load(open(sys.argv[2], encoding="utf-8"))
    commit = hashlib.sha256(text.encode()).hexdigest()
    pool = [(c, int(w)) for c, w in (ln.split(":") for ln in text.splitlines() if ln and not ln.startswith("PARAMS"))]
    print("отпечаток (commit):", commit)
    print("участников:", len(pool))
    bad = 0
    for s in spins:
        rnd = drand(s["round"])
        total = sum(w for _, w in pool)
        x = int(hashlib.sha256(f"{commit}:{rnd}:{s['place']}".encode()).hexdigest(), 16) % total
        acc = 0
        for i, (code, w) in enumerate(pool):
            acc += w
            if x < acc:
                ok = code == s.get("code")
                bad += not ok
                print(f"место {s['place']:>2}: drand #{s['round']} → #{code}  [{'OK' if ok else 'РАСХОЖДЕНИЕ, на сайте #' + str(s.get('code'))}]")
                pool.pop(i)
                break
    print("Всё сходится" if not bad else f"Расхождений: {bad}")


if __name__ == "__main__":
    main()
