#!/usr/bin/env python3
"""抽奖结果独立验证脚本（仅依赖 Python 3 标准库）。

用法：
    python3 verify.py participants_g1.json
    python3 verify.py participants_g1.json --seed <区块哈希>      # 手动指定种子
    python3 verify.py participants_g1.json --fetch               # 按 JSON 中的区块高度联网获取区块哈希
    python3 verify.py participants_g1.json --n 10                # 额外列出前 10 名（含候补）

验证内容：
1. 重新计算参与名单哈希，与开奖前公布的 list_hash 比对；
2. 用区块哈希作为种子，按 sha256-weighted-v1 算法重算中奖结果。
"""
import argparse
import bisect
import hashlib
import json
import sys
import urllib.request

ALGORITHM = "sha256-weighted-v1"
APIS = ["https://mempool.space/api", "https://blockstream.info/api"]


def canonical_entries(entries):
    out = []
    for e in entries:
        t = int(e["tickets"])
        if t > 0:
            out.append({"id": str(e["id"]), "tickets": t})
    out.sort(key=lambda x: x["id"])
    ids = [e["id"] for e in out]
    if len(ids) != len(set(ids)):
        raise ValueError("duplicate id in entries")
    return out


def list_hash(entries):
    data = json.dumps(canonical_entries(entries), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(data.encode("utf-8")).hexdigest()


def pick_sequence(entries, seed, n):
    ents = canonical_entries(entries)
    if not ents or n <= 0:
        return []
    seed = str(seed).strip().lower()
    cum, total = [], 0
    for e in ents:
        total += e["tickets"]
        cum.append(total)
    n = min(n, len(ents))
    picked, seen, counter = [], set(), 0
    while len(picked) < n:
        digest = hashlib.sha256(f"{seed}:{counter}".encode("utf-8")).digest()
        r = int.from_bytes(digest, "big") % total
        eid = ents[bisect.bisect_right(cum, r)]["id"]
        if eid not in seen:
            seen.add(eid)
            picked.append({"id": eid, "counter": counter, "ticket": r})
        counter += 1
    return picked


def fetch_block_hash(height):
    for base in APIS:
        try:
            with urllib.request.urlopen(f"{base}/block-height/{int(height)}", timeout=15) as resp:
                h = resp.read().decode().strip().lower()
                if len(h) == 64:
                    return h
        except Exception as exc:  # noqa: BLE001
            print(f"[warn] {base} 获取失败: {exc}", file=sys.stderr)
    raise SystemExit("无法获取区块哈希，请用 --seed 手动指定")


def main():
    ap = argparse.ArgumentParser(description="验证抽奖结果")
    ap.add_argument("file", help="机器人公布的 participants_g<ID>.json")
    ap.add_argument("--seed", help="种子（比特币区块哈希）")
    ap.add_argument("--fetch", action="store_true", help="按区块高度联网获取区块哈希")
    ap.add_argument("--n", type=int, help="列出的名次数量（默认=中奖名额+已重抽数，含候补）")
    args = ap.parse_args()

    with open(args.file, encoding="utf-8") as f:
        doc = json.load(f)
    if doc.get("algorithm", ALGORITHM) != ALGORITHM:
        raise SystemExit(f"不支持的算法: {doc.get('algorithm')}")
    entries = doc["entries"]
    names = {str(e["id"]): e.get("name", "") for e in entries}

    lh = list_hash(entries)
    print(f"参与人数: {len(canonical_entries(entries))}  总抽奖码: {sum(int(e['tickets']) for e in entries)}")
    print(f"名单哈希(重算): {lh}")
    if doc.get("list_hash"):
        ok = lh == doc["list_hash"]
        print(f"名单哈希(公布): {doc['list_hash']}  -> {'一致 ✅' if ok else '不一致 ❌'}")

    seed = args.seed
    if not seed and args.fetch:
        seed = fetch_block_hash(doc["btc_block_height"])
        print(f"区块 #{doc['btc_block_height']} 哈希(联网获取): {seed}")
        if doc.get("seed") and doc["seed"].lower() != seed:
            print("⚠️ 与 JSON 中记录的种子不一致！")
    seed = seed or doc.get("seed")
    if not seed:
        raise SystemExit("尚未开奖：JSON 中没有种子，请用 --seed 或 --fetch")
    print(f"种子: {seed}")

    n = args.n or int(doc.get("picks_total") or doc.get("winners_count") or 1)
    seq = pick_sequence(entries, seed, n)
    k = int(doc.get("winners_count") or 0)
    print("\n序号  公示编号            名称            counter")
    for i, p in enumerate(seq, 1):
        tag = "中奖" if i <= k else "候补"
        print(f"{i:>3} {tag}  {p['id']:<18}  {names.get(p['id'], ''):<14}  {p['counter']}")
    if doc.get("picks"):
        expected = [p["id"] for p in doc["picks"]]
        got = [p["id"] for p in seq[: len(expected)]]
        print("\n与公布结果比对:", "一致 ✅" if got == expected else "不一致 ❌")


if __name__ == "__main__":
    main()
