#!/usr/bin/env python3
# Watch for Area31 testers' recycles (new entries beyond those already present).
# Logs each NEW recycle on detection and when it PAYS. Exits on a paid new recycle (0),
# a stuck one (2), or timeout (3).
import json, time, sys
P = "/home/paul/Aura/data/ledger/recycle.json"
LOGP = "/tmp/claude-1000/-home-paul-Aura/a2239ea0-e18d-4178-9864-2c3f48478801/scratchpad/beta_recycle_watch.log"
def log(m):
    with open(LOGP,"a") as f: f.write(f"{time.strftime('%H:%M:%S')} {m}\n")
def load():
    try: return json.load(open(P)).get("recycles", [])
    except Exception: return []
seen = {r.get("tx") for r in load()}
log(f"BETA WATCH START — {len(seen)} existing recycle(s) ignored")
detected, deadline = set(), time.time() + 3*3600
while time.time() < deadline:
    time.sleep(20)
    for r in load():
        tx = r.get("tx")
        if tx in seen:
            continue
        if tx not in detected:
            detected.add(tx)
            log(f"NEW RECYCLE — {r.get('ledger'):,.0f} $LEDGER from {r.get('wallet')} -> ${r.get('payout_usd')} [{r.get('status')}]")
        if r.get("status") == "paid" and r.get("payout_tx"):
            log(f"PAID — ${r.get('payout_usd')} USDC -> {r.get('wallet')} tx {r.get('payout_tx')}")
            sys.exit(0)
        if r.get("status") in ("review","error"):
            log(f"STUCK — {r.get('status')} ${r.get('payout_usd')} -> {r.get('wallet')} note={r.get('note','')}")
            sys.exit(2)
log("TIMEOUT — no tester recycle completed in 3h")
sys.exit(3)
