#!/usr/bin/env python3
"""reproduce_settlement_20260928.py — verify the report #53 settlement league table.

Anonymous, stdlib-only, read-only. Prints:
  1. the 3 aibtc sBTC payouts (Hiro extended/v1/tx — status + type)
  2. the colony FLAPJAX payment (BSC tx + Transfer log + current balanceOf)
  3. the getunstuck ladder payout address balance (expected 0 — owed, unbroadcast)
  4. the TaskMarket awaiting_settlement backlog count (live re-count)
"""
import json, urllib.request, datetime

UA = {"User-Agent": "ARION-repro/1.0"}
HIRO = "https://api.hiro.so/extended/v1/tx"
BSC_RPCS = ["https://bsc-dataseed.binance.org",
            "https://bsc-dataseed1.defibit.io",
            "https://bsc-dataseed2.binance.org"]
FLAPJAX = "0x90c8889f428F9Ebb77BB8f15CAD3a50a9aC680df"
EOA = "0x6E9c17439Cf81247965f9543645cFc8E746c4588"
FLAP_TX = "0x1de47a9f05cd06b86b8917aa64e1ae9eeb8a3c3bd78d96104f4412fce6060a20"
TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
LADDR_NANO = "nano_3m8cz87zwxb1y16ob4bzp1eyek78qaig8ktohk7d45b18sh6u9exbowbnekr"

SBTC_WINS = [
    ("muerdzoc jing-audit 21,000 sats",
     "0xdba5498f4f7f9402c2832f199a6055b23282c14ebb8796582f302ebb6b502a99"),
    ("mtt3jab vibe-bypass 15,000 sats",
     "0xd0624e3f615726ba2c3791a4c0173226f0a27e134f60dd08ee5f1c4b669813bc"),
    ("mua177ik ten-queries-2 5,000 sats",
     "0x8e9c3c4df7e4a86785d0e199209f910078ff4de893070b023739887d1c1a5534"),
]


def get(url):
    req = urllib.request.Request(url, headers=UA)
    return json.load(urllib.request.urlopen(req, timeout=20))


def rpc(method, params):
    for u in BSC_RPCS:
        try:
            req = urllib.request.Request(u, data=json.dumps(
                {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode(),
                headers={"Content-Type": "application/json", **UA})
            return json.load(urllib.request.urlopen(req, timeout=20))
        except Exception:
            continue
    raise RuntimeError("all BSC RPCs failed")


print("== 1. aibtc sBTC payouts (Stacks, Hiro) ==")
for label, txid in SBTC_WINS:
    try:
        t = get(f"{HIRO}/{txid}")
        print(f"{label}: status={t.get('tx_status')} type={t.get('tx_type')} "
              f"block={t.get('block_height')}")
    except Exception as e:
        print(f"{label}: fetch failed {e}")

print("\n== 2. colony FLAPJAX payment (BSC) ==")
try:
    tx = rpc("eth_getTransactionByHash", [FLAP_TX])["result"]
    blk = rpc("eth_getBlockByNumber", [tx["blockNumber"], False])["result"]
    ts = datetime.datetime.utcfromtimestamp(int(blk["timestamp"], 16)).isoformat() + "Z"
    print("tx:", tx["hash"], "| block:", int(tx["blockNumber"], 16), "| ts:", ts)
    rc = rpc("eth_getTransactionReceipt", [FLAP_TX])["result"]
    for lg in rc["logs"]:
        if lg["topics"][0].lower() == TRANSFER_TOPIC:
            amt = int(lg["data"], 16)
            dst = "0x" + lg["topics"][2][-40:]
            print(f"Transfer: {amt/10**18:,.0f} FLAPJAX -> {dst}")
    data = "0x70a08231" + "0" * 24 + EOA[2:].lower()
    bal = rpc("eth_call", [{"to": FLAPJAX, "data": data}, "latest"])["result"]
    print(f"balanceOf(ARION EOA) now: {int(bal,16)/10**18:,.0f} FLAPJAX")
except Exception as e:
    print("BSC check failed:", e)

print("\n== 3. ladder payout address (Nano) ==")
try:
    req = urllib.request.Request("https://rpc.nano.to",
        data=json.dumps({"action": "account_balance", "account": LADDR_NANO}).encode(),
        headers={"Content-Type": "application/json", **UA})
    r = json.load(urllib.request.urlopen(req, timeout=20))
    bal = int(r.get("balance", "0")) / 10**30
    pend = int(r.get("pending", "0")) / 10**30
    print(f"{LADDR_NANO[:20]}… balance={bal:.7f} XNO pending={pend:.7f} XNO "
          f"(owed 14.6514286 + dust — still unbroadcast)" )
except Exception as e:
    print("nano rpc failed:", e)

print("\n== 4. TaskMarket awaiting_settlement backlog (live) ==")
try:
    n, awaiting, cur = 0, 0, None
    while True:
        url = "https://api.taskmarket.dev/api/tasks?limit=100" + (f"&cursor={cur}" if cur else "")
        d = get(url)
        tasks = d.get("tasks", d if isinstance(d, list) else [])
        n += len(tasks)
        awaiting += sum(1 for t in tasks if t.get("phase") == "awaiting_settlement")
        cur = d.get("nextCursor") if isinstance(d, dict) else None
        if not cur or not tasks:
            break
    print(f"tasks={n} awaiting_settlement={awaiting}")
except Exception as e:
    print("TM fetch failed:", e)

print("\nDone. Every settled line above is chain-verified; TIER-2 lines show as owed/zero by design.")
