#!/usr/bin/env python3
"""FlapJax Q80 (Money Maker, AI agent): treasury FLAPJAX outflows during 10-29 COT + first-BNB-funder grouping.
Stdlib only; needs a public BSC archive node (default: NodeReal public endpoint from docs.nodereal.io)."""
import json, urllib.request, sys, calendar, time
RPC = sys.argv[1] if len(sys.argv) > 1 else "https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3"
TOK = "0x90c8889f428f9ebb77bb8f15cad3a50a9ac680df"; TRE = "0x7c34e9e21ee28a49ff0b84b61774119e6633359f"
TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
def rpc(m, p, tries=6):
    for i in range(tries):
        try:
            r = urllib.request.Request(RPC, json.dumps({"jsonrpc": "2.0", "id": 1, "method": m, "params": p}).encode(), {"Content-Type": "application/json", "User-Agent": "q80-reproduce"})
            j = json.load(urllib.request.urlopen(r, timeout=60))
            if "error" in j: raise RuntimeError(j["error"])
            return j["result"]
        except Exception as e:
            if i == tries - 1: raise
            time.sleep(2 + 2 * i)
ts = lambda b: int(rpc("eth_getBlockByNumber", [hex(b), False])["timestamp"], 16)
def first_at_or_after(T, lo, hi):  # smallest block with ts >= T
    while hi - lo > 1:
        m = (lo + hi) // 2
        if ts(m) >= T: hi = m
        else: lo = m
    return hi
head = int(rpc("eth_blockNumber", []), 16)
T0 = calendar.timegm((2026, 10, 29, 5, 0, 0)); T1 = calendar.timegm((2026, 10, 30, 5, 0, 0))  # 10-29 00:00 COT .. 10-30 00:00 COT
lo = head - 900000
FIRST = first_at_or_after(T0, lo, head); LAST = first_at_or_after(T1, FIRST, head) - 1
print("first block", FIRST, ts(FIRST), "prev", ts(FIRST - 1), "| last block", LAST, ts(LAST), "next", ts(LAST + 1))
logs = []; b = FIRST
while b <= LAST:
    e = min(b + 49999, LAST)
    logs += rpc("eth_getLogs", [{"fromBlock": hex(b), "toBlock": hex(e), "address": TOK, "topics": [TOPIC, "0x" + "0"*24 + TRE[2:]]}]); b = e + 1
fj = lambda v: f"{v//10**18:,}.{v%10**18:018d}"
rows = []; tot = 0
for l in logs:
    bn = int(l["blockNumber"], 16); t = ts(bn); v = int(l["data"], 16); to = "0x" + l["topics"][2][-40:]; tot += v
    rows.append({"tx": l["transactionHash"], "logIndex": int(l["logIndex"], 16), "block": bn, "ts": t,
                 "time_cot": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t - 5*3600)), "to": to, "amount_raw": str(v), "amount": fj(v)})
for r in rows: print(r["tx"], r["block"], r["time_cot"], "COT", r["to"], r["amount"])
print("transfers", len(rows), "total", fj(tot), "distinct recipients", len({r['to'] for r in rows}))
out = {"first_block": FIRST, "last_block": LAST, "transfers": rows, "total_raw": str(tot)}
json.dump(out, open("q80_result.json", "w"), indent=1)
