import urllib.request
import json
import eth_abi
import datetime
from collections import defaultdict

BASE_RPC = "https://base-rpc.publicnode.com"
POIDH = "0x5555fa783936c260f77385b4e153b9725fef1719"
MULTICALL3 = "0xcA11bde05977b3631167028862bE2a173976CA11"
ERC8004 = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"

def rpc_call(method, params):
    req = urllib.request.Request(
        BASE_RPC,
        data=json.dumps({"jsonrpc":"2.0","id":1,"method":method,"params":params}).encode(),
        headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"}
    )
    return json.loads(urllib.request.urlopen(req, timeout=15).read())["result"]

def multicall(calls):
    encoded_args = eth_abi.encode(["(address,bool,bytes)[]"], [calls])
    res = rpc_call("eth_call", [{"to": MULTICALL3, "data": "0x82ad56cb" + encoded_args.hex()}, "latest"])
    return eth_abi.decode(["(bool,bytes)[]"], bytes.fromhex(res[2:]))[0]

# 1. Fetch all 567 bounties on Base POIDH v3
bounties = {}
for start in range(1, 568, 200):
    end = min(567, start + 199)
    calls = [(POIDH, True, bytes.fromhex("dc2f8744" + hex(bid)[2:].zfill(64))) for bid in range(start, end + 1)]
    out = multicall(calls)
    for ok, raw in out:
        if ok and len(raw) >= 64:
            try:
                b = eth_abi.decode(["uint256","address","string","string","uint256","address","uint256","uint256"], raw)
                if b[0] > 0:
                    bounties[b[0]] = {
                        "id": b[0], "issuer": b[1].lower(), "name": b[2], "desc": b[3],
                        "amount": b[4]/1e18, "claimer": b[5].lower(), "createdAt": b[6], "claimId": b[7]
                    }
            except Exception:
                pass

print(f"Loaded {len(bounties)} Base bounties.")

# 2. Fetch all 4316 claims on Base POIDH v3
claims = []
for start in range(1, 4317, 250):
    end = min(4316, start + 249)
    calls = [(POIDH, True, bytes.fromhex("a888c2cd" + hex(cid)[2:].zfill(64))) for cid in range(start, end + 1)]
    out = multicall(calls)
    for ok, raw in out:
        if ok and len(raw) >= 64:
            try:
                c = eth_abi.decode(["uint256","address","uint256","address","string","string","uint256","bool"], raw)
                if c[0] > 0 and c[1] != "0x0000000000000000000000000000000000000000":
                    claims.append({
                        "id": c[0], "issuer": c[1].lower(), "bountyId": c[2],
                        "bountyIssuer": c[3].lower(), "name": c[4], "desc": c[5],
                        "createdAt": c[6], "accepted": c[7]
                    })
            except Exception:
                pass

print(f"Loaded {len(claims)} valid Base claims.")

all_wallets = sorted(list(set([c["issuer"] for c in claims] + [b["issuer"] for b in bounties.values()])))
print(f"Total unique wallets (claimers + issuers) on Base POIDH v3: {len(all_wallets)}")

erc8004_map = {}
for i in range(0, len(all_wallets), 250):
    wbatch = all_wallets[i:i+250]
    calls = [(ERC8004, True, bytes.fromhex("70a08231" + w[2:].zfill(64))) for w in wbatch]
    out = multicall(calls)
    for w, (ok, raw) in zip(wbatch, out):
        if ok and len(raw) == 32:
            bal = int.from_bytes(raw, "big")
            if bal > 0:
                erc8004_map[w] = bal

print(f"Total ERC-8004 Registered Agent Wallets on Base POIDH v3: {len(erc8004_map)}")

# Self-disclosed or rapid-cadence agent wallets
import re
AGENT_REGEX = re.compile(r"\b(i am an? (ai |autonomous )?agent|submitted by [a-z0-9_-]+, an (ai|autonomous) agent|authored by [a-z0-9_-]+, an? (ai|autonomous) agent|autonomous ai agent|erc-?8004|x402|openclaw|clawdbot|vireo|aegis|muse agent)\b", re.I)

self_disclosed_wallets = set()
for c in claims:
    if AGENT_REGEX.search(c["name"] + " " + c["desc"]):
        self_disclosed_wallets.add(c["issuer"])

# Rapid cross-bounty cadence (<120s between claims on different bounties)
by_wallet = defaultdict(list)
for c in claims:
    by_wallet[c["issuer"]].append(c)

rapid_wallets = set()
for w, clist in by_wallet.items():
    clist.sort(key=lambda x: x["createdAt"])
    for idx in range(1, len(clist)):
        dt = clist[idx]["createdAt"] - clist[idx-1]["createdAt"]
        if 0 <= dt <= 120 and clist[idx]["bountyId"] != clist[idx-1]["bountyId"]:
            rapid_wallets.add(w)

verified_agent_union = set(erc8004_map.keys()) | self_disclosed_wallets | rapid_wallets

# Monthly breakdown across 2026
monthly = defaultdict(lambda: {"total_claims": 0, "erc8004_claims": 0, "union_agent_claims": 0, "erc8004_wallets": set(), "union_wallets": set(), "erc8004_wins": 0, "union_wins": 0})
for c in claims:
    dt = datetime.datetime.fromtimestamp(c["createdAt"], datetime.timezone.utc)
    ym = dt.strftime("%Y-%m")
    m = monthly[ym]
    m["total_claims"] += 1
    w = c["issuer"]
    if w in erc8004_map:
        m["erc8004_claims"] += 1
        m["erc8004_wallets"].add(w)
        if c["accepted"]:
            m["erc8004_wins"] += 1
    if w in verified_agent_union:
        m["union_agent_claims"] += 1
        m["union_wallets"].add(w)
        if c["accepted"]:
            m["union_wins"] += 1

print("\n=== MONTHLY BREAKDOWN (BASE POIDH v3) ===")
summary_rows = []
for ym in sorted(monthly.keys()):
    m = monthly[ym]
    tot = m["total_claims"]
    e_c = m["erc8004_claims"]
    u_c = m["union_agent_claims"]
    row = {
        "month": ym,
        "total_claims": tot,
        "erc8004_claims": e_c,
        "erc8004_pct": round(100.0 * e_c / tot, 2) if tot else 0,
        "erc8004_wallets": len(m["erc8004_wallets"]),
        "erc8004_wins": m["erc8004_wins"],
        "union_agent_claims": u_c,
        "union_pct": round(100.0 * u_c / tot, 2) if tot else 0,
        "union_wallets": len(m["union_wallets"]),
        "union_wins": m["union_wins"]
    }
    summary_rows.append(row)
    print(row)

# Top ERC-8004 wallets on POIDH
erc8004_details = []
for w, bal in erc8004_map.items():
    w_claims = by_wallet[w]
    w_wins = [c for c in w_claims if c["accepted"]]
    w_bounties = [b for b in bounties.values() if b["issuer"] == w]
    erc8004_details.append({
        "wallet": w,
        "erc8004_nfts": bal,
        "claims_count": len(w_claims),
        "wins_count": len(w_wins),
        "bounties_issued": len(w_bounties),
        "first_claim_ts": min(c["createdAt"] for c in w_claims) if w_claims else None,
        "sample_claim_id": w_claims[-1]["id"] if w_claims else None,
        "sample_title": w_claims[-1]["name"][:60] if w_claims else None
    })
erc8004_details.sort(key=lambda x: (-x["claims_count"], -x["wins_count"]))
print("\n=== ERC-8004 REGISTERED AGENT WALLETS ON POIDH ===")
for d in erc8004_details:
    print(d)

with open(r"C:\Users\User\.gemini\antigravity\brain\47990048-6784-4694-bf3b-09922490a525\scratch\census_564_results.json", "w") as f:
    json.dump({
        "total_bounties": len(bounties),
        "total_claims": len(claims),
        "unique_wallets": len(all_wallets),
        "erc8004_wallet_count": len(erc8004_map),
        "self_disclosed_wallet_count": len(self_disclosed_wallets),
        "rapid_wallet_count": len(rapid_wallets),
        "union_wallet_count": len(verified_agent_union),
        "monthly": summary_rows,
        "erc8004_wallets": erc8004_details
    }, f, indent=2)
