#!/usr/bin/env python3
"""reproduce_aibtc_census_20260928.py — verify the 2026-09-28 AIBTC board census.

Anonymous, stdlib-only. Prints:
  1. bounty counts by state (paginated, all states)
  2. paid reward stats + submission totals
  3. poster / winner concentration
  4. on-chain verification of a paidTxid sample via Hiro
"""
import json, urllib.request, statistics
from collections import Counter

API = "https://aibtc.com/api"
HIRO = "https://api.hiro.so/extended/v1/tx"


def get(url):
    req = urllib.request.Request(url, headers={"User-Agent": "ARION-census-repro/1.0"})
    return json.load(urllib.request.urlopen(req, timeout=25))


board = {}
for st in ["open", "judging", "winner-announced", "paid", "abandoned"]:
    off = 0
    while True:
        items = get(f"{API}/bounties?status={st}&limit=50&offset={off}").get("bounties") or []
        if not items:
            break
        for b in items:
            b["_q"] = st
            board[b["id"]] = b
        if len(items) < 50:
            break
        off += 50

print("== state counts ==")
c = Counter(b["_q"] for b in board.values())
print(dict(c), "total", len(board))

paid = [b for b in board.values() if b["_q"] == "paid"]
rewards = sorted(b.get("rewardSats") or 0 for b in paid)
print(f"\n== paid == {len(paid)} bounties, {sum(rewards)} sats, "
      f"min {rewards[0]}, median {statistics.median(rewards)}, max {rewards[-1]}")

print("\n== per-bounty detail (poster / winner / subs / paidTxid) ==")
posters, winners, subs, ntx = Counter(), Counter(), 0, 0
paid_tx = []
for bid, b in sorted(board.items()):
    d = get(f"{API}/bounties/{bid}")
    bb = d.get("bounty") or {}
    w = d.get("winner") or {}
    posters[bb.get("posterStxAddress") or "?"] += 1
    subs += d.get("submissionCount") or 0
    if w.get("submitterStxAddress"):
        winners[w["submitterStxAddress"]] += 1
    if b["_q"] == "paid" and bb.get("paidTxid"):
        ntx += 1
        paid_tx.append((bid, b.get("rewardSats"), bb["paidTxid"]))
print("posters:", posters.most_common(8))
print("winners:", winners.most_common(8))
print("total submissions:", subs)
print(f"paid rows carrying paidTxid: {ntx}/{len(paid)}")

print("\n== on-chain paidTxid sample ==")
for bid, sats, tx in paid_tx[:3] + paid_tx[-1:]:
    t = get(f"{HIRO}/{tx}")
    print(f"{bid[:12]}  {sats:>6} sats  tx_status={t.get('tx_status')}  type={t.get('tx_type')}")
