#!/usr/bin/env python3
"""Q80 part 2 (Money Maker, AI agent): first BNB funder of each recipient (and the treasury) up to a pinned head block H,
plus the funders' own first funders (2nd hop). Stdlib; public BSC archive node."""
import json, sys, time, urllib.request
RPC = sys.argv[1] if len(sys.argv) > 1 else "https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3"
H = int(sys.argv[2]) if len(sys.argv) > 2 else None
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:
            if i == tries - 1: raise
            time.sleep(2 + 2 * i)
if H is None: H = int(rpc("eth_blockNumber", []), 16) - 20
res = json.load(open("q80_result.json"))
TRE = "0x7c34e9e21ee28a49ff0b84b61774119e6633359f"
def state(a, b): return int(rpc("eth_getBalance", [a, hex(b)]), 16), int(rpc("eth_getTransactionCount", [a, hex(b)]), 16)
def first_funding(a):
    # P(b) = balance>0 or nonce>0. Monotone for a plain EOA: its balance can only fall through its own txs (nonce>0).
    P = lambda b: any(state(a, b))
    if not P(H): return None
    lo, hi = 0, H
    while hi - lo > 1:
        m = (lo + hi) // 2
        if P(m): hi = m
        else: lo = m
    blk = rpc("eth_getBlockByNumber", [hex(hi), True])
    direct = [{"tx": t["hash"], "from": t["from"].lower(), "value_wei": str(int(t["value"], 16)), "type": t.get("type")} for t in blk["transactions"] if (t.get("to") or "").lower() == a and int(t["value"], 16) > 0]
    bal, nonce = state(a, hi)
    return {"block": hi, "ts_utc": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(int(blk["timestamp"], 16))), "balance_after_wei": str(bal), "nonce_after": nonce, "direct": direct}
out = {"H": H, "H_ts_utc": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(int(rpc("eth_getBlockByNumber", [hex(H), False])["timestamp"], 16)))}
addrs = sorted({r["to"] for r in res["transfers"]} | {TRE})
for a in addrs:
    code = rpc("eth_getCode", [a, hex(H)]); bal, nonce = state(a, H)
    out[a] = {"code": code if len(code) < 100 else f"len {len(code)//2-1}", "balance_H_wei": str(bal), "nonce_H": nonce, "first": first_funding(a)}
    print(a, json.dumps(out[a]))
hop2 = sorted({d["from"] for a in addrs if out[a]["first"] for d in out[a]["first"]["direct"]} - {TRE})
out["hop2"] = {}
for f in hop2:
    code = rpc("eth_getCode", [f, hex(H)]); bal, nonce = state(f, H)
    out["hop2"][f] = {"code_bytes": len(code)//2 - 1, "nonce_H": nonce, "first": first_funding(f)}
    print("hop2", f, json.dumps(out["hop2"][f]))
json.dump(out, open("funders_result.json", "w"), indent=1)
