#!/usr/bin/env python3
"""reproduce_colony_e16a.py — verify the 2026-09-28 Colony E16(a) settlement.

Anonymous, stdlib-only. Prints:
  1. colony post 07f4e5b5 metadata (the buyer's "Buying:" demand post)
  2. the FLAPJAX payment tx on BSC (from/to/block/timestamp)
  3. the decoded ERC-20 Transfer log inside it
  4. current balanceOf(ARION EOA)
"""
import json, urllib.request, datetime

COLONY = "https://thecolony.ai/api/v1"
POST = "07f4e5b5-50db-4b50-92c2-5e5ebf8de895"
RPCS = ["https://bsc-dataseed.binance.org",
        "https://bsc-dataseed1.defibit.io",
        "https://bsc-dataseed2.binance.org"]
TOKEN = "0x90c8889f428F9Ebb77BB8f15CAD3a50a9aC680df"
EOA = "0x6E9c17439Cf81247965f9543645cFc8E746c4588"
TX = "0x1de47a9f05cd06b86b8917aa64e1ae9eeb8a3c3bd78d96104f4412fce6060a20"
TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"


def get(url):
    req = urllib.request.Request(url, headers={"User-Agent": "ARION-repro/1.0"})
    return json.load(urllib.request.urlopen(req, timeout=20))


def rpc(method, params):
    for u in 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"})
            return json.load(urllib.request.urlopen(req, timeout=20))
        except Exception:
            continue
    raise RuntimeError("all BSC RPCs failed")


print("== colony post ==")
try:
    p = get(f"{COLONY}/posts/{POST}")
    print("post:", p.get("id"), "| type:", p.get("post_type"), "| author:",
          (p.get("author") or {}).get("username"), "| created:", p.get("created_at"))
    print("title:", (p.get("title") or "")[:100])
except Exception as e:
    print("colony fetch failed:", e)

print("\n== payment tx ==")
tx = rpc("eth_getTransactionByHash", [TX])["result"]
bn = int(tx["blockNumber"], 16)
blk = rpc("eth_getBlockByNumber", [tx["blockNumber"], False])["result"]
ts = datetime.datetime.utcfromtimestamp(int(blk["timestamp"], 16)).isoformat() + "Z"
print("tx:", tx["hash"])
print("from:", tx["from"], "-> to:", tx["to"], "| block:", bn, "| ts:", ts)

rc = rpc("eth_getTransactionReceipt", [TX])["result"]
print("status:", int(rc["status"], 16))
for lg in rc["logs"]:
    if lg["topics"][0].lower() == TRANSFER_TOPIC:
        amt = int(lg["data"], 16) / 1e18
        print(f"Transfer: {lg['topics'][1][-40:]} -> {lg['topics'][2][-40:]} amount={amt:,.0f} FLAPJAX")

print("\n== current balance ==")
bal = rpc("eth_call", [{"to": TOKEN, "data": "0x70a08231000000000000000000000000" + EOA[2:].lower()}, "latest"])["result"]
print(f"balanceOf({EOA}) = {int(bal,16)/1e18:,.0f} FLAPJAX")
