#!/usr/bin/env python3
"""reproduce_cohorts_drop.py — verify that pursekeeper's /cohorts drops the
confirmed 0.0003 XNO inbound from nano_3gmd94... (NanoGPT deposit account).

Stdlib only. Fetches three public documents + one public node call and
checks the three claims in the report:
  A. cohorts.json row for nano_3gmd94 shows received_raw == 0 / count == 0.
  B. log.json ledger contains a payment_in of 300113048570000000000000000
     raw from that address.
  C. chain block_info confirms the send from nano_3gmd94 to the hot wallet.
  D. reconciliation: log sums - cohorts sums = own-x402-account + this drop.
"""
import json, urllib.request

COHORTS = "https://pursekeeper.dev/cohorts.json"
LOG = "https://pursekeeper.dev/log.json"
RPC = "https://rpc.nano.to"
TARGET = "nano_3gmd94aey5nxrntgjrznnbssh3s7htyubeq91x8qgjpbe8qk59xiarf1homu"
OWN = "nano_1i3y944esngqw6wb6ia68dotj4yuqctch9kx8ct65twt8ewi4rdcfgax7ggf"
BLOCK = "8FA6B1646ADBD14B4DAD7C724643AA8C38813DF7D765AA09B3E3D58A7A702BAD"
HOT = "nano_1xug1q5t7nxoj3ywwzokiea9jz8fq8qfgzp8pbyfr3co3e5xgj755uofu8ue"


def get(url):
    req = urllib.request.Request(url, headers={"User-Agent": "ARION-docQA/1.0"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read())


def post(url, payload):
    req = urllib.request.Request(
        url, data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json",
                 "User-Agent": "ARION-docQA/1.0"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read())


def main():
    coh, log = get(COHORTS), get(LOG)

    row = next(r for r in coh["rows"] if r["address"] == TARGET)
    a_ok = row["received_raw"] == "0" and row["received_count"] == 0
    print(f"A. cohorts received for nano_3gmd94: raw={row['received_raw']} "
          f"count={row['received_count']} paid_us={row['funding']['paid_us']} "
          f"-> {'SHOWS ZERO (bug present)' if a_ok else 'NON-ZERO (fixed?)'}")

    ent = [e for e in log["ledger"]
           if e["counterparty"] == TARGET and e["kind"] == "payment_in"]
    b_ok = any(int(e["amount_raw"]) == 300113048570000000000000000
               for e in ent)
    print(f"B. ledger payment_in rows for nano_3gmd94: {len(ent)}, "
          f"0.0003 entry present: {b_ok}")

    bi = post(RPC, {"action": "block_info", "json_block": "true",
                    "hash": BLOCK})
    c_ok = (bi.get("subtype") == "send"
            and bi.get("block_account") == TARGET
            and int(bi.get("amount", 0)) == 300113048570000000000000000
            and bi["contents"].get("link_as_account") == HOT)
    print(f"C. block {BLOCK[:16]}…: subtype={bi.get('subtype')} "
          f"from={bi.get('block_account','')[:16]}… "
          f"amount_nano={bi.get('amount_nano')} -> "
          f"{'CONFIRMED send nano_3gmd94->hot' if c_ok else 'UNEXPECTED'}")

    coh_recv = sum(int(r["received_raw"]) for r in coh["rows"])
    log_recv = int(log["numbers"]["received"]["nano"])
    print(f"D. received totals: log={log_recv/1e30:.5f} "
          f"cohorts={coh_recv/1e30:.5f} delta={(log_recv-coh_recv)/1e30:.5f} "
          f"(expect 0.0054 = 0.0051 own-acct + 0.0003 this drop)")

    print("VERDICT:", "BUG CONFIRMED" if (a_ok and b_ok and c_ok)
          else "needs re-check")


if __name__ == "__main__":
    main()
