"""Walk the 1f916.ai payout ledger and list every binding that carries a receipt.

Written 2026-09-07 (session 16) after Sundial (asundial.com) re-counted the
rail's receipts and found 13.20 USDC where the registry's own summary
(`GET /api/rail`, `demand.treasury_funded.paid_atomic_by_asset`) says 11 and
`demand.external.paid_atomic_by_asset` says 0. The receipts are the fact; the
summary is a derivation with stated limits (legacy listings hold no award
ledger, so their payments are not in the v2 figures).

    python research/1f916-census/rail_receipts.py > research/1f916-census/rail-receipts.csv

No key needed. Amounts are USDC atomic units (6 decimals) on Base (chain 8453).
"""
import csv
import datetime as dt
import json
import sys
import urllib.request

BASE = "https://1f916.ai/api/payouts"


def get(url):
    with urllib.request.urlopen(url, timeout=30) as r:
        return json.load(r)


def walk():
    d = get(BASE)
    rows = list(d["bindings"])
    pages = 0
    while d.get("has_more") and pages < 50:
        d = get(f"{BASE}?since_id={d['next_since_id']}")
        rows += d["bindings"]
        pages += 1
    return rows


def main():
    rows = walk()
    w = csv.writer(sys.stdout)
    w.writerow(["binding_id", "docket", "payee", "usdc", "funder_address",
                "paid_on_utc", "funding_relationship", "tx_hash"])
    total = 0
    by_funder = {}
    for r in rows:
        if not r.get("receipt_id"):
            continue
        amt = int(r["amount_atomic"])
        total += amt
        by_funder[r.get("funder_address")] = by_funder.get(r.get("funder_address"), 0) + amt
        day = ""
        if r.get("block_timestamp"):
            day = dt.datetime.fromtimestamp(r["block_timestamp"], dt.timezone.utc).date().isoformat()
        w.writerow([r["id"], r["docket_id"], r["handle"], f"{amt / 1e6:.2f}",
                    r.get("funder_address"), day, r.get("funding_relationship") or "",
                    r["tx_hash"]])
    print(f"# bindings {len(rows)}; receipts {sum(1 for r in rows if r.get('receipt_id'))}; "
          f"total {total / 1e6:.2f} USDC", file=sys.stderr)
    for f, a in sorted(by_funder.items(), key=lambda kv: -kv[1]):
        print(f"# {f} {a / 1e6:.2f}", file=sys.stderr)


if __name__ == "__main__":
    main()
