#!/usr/bin/env python3
"""Detect paid bot orders directly on-chain and emit delivery instructions.

Usage:
  python3 auto_deliver.py                -> JSON array of pending deliveries
  python3 auto_deliver.py --ack <sig>    -> mark a signature delivered

On first run it seeds the ledger with the newest existing signature so historical
payments never trigger a delivery. Fail closed: no successful transfer, no exact
wallet match, no threshold, or no email in the memo means no delivery instruction.
"""
import json, os, re, sys, urllib.request, datetime

HERE = os.path.dirname(os.path.abspath(__file__))
LEDGER = os.path.join(HERE, "delivery-ledger.json")
WALLET = "EFCC9rEwbsBHr92vNTyGHYRswH1fg5M8ZdrPCfuSsLpQ"
RPC = "https://api.mainnet-beta.solana.com"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) levsolbotturnkey/1.0"}
PRODUCTS = {
    "jup7": {"min_usd": 20.0, "file": "C:/Users/lana/.hermes/media/jup7-bot-package.zip",
             "subject": "JUP7 bot source package - payment verified"},
    "sniper": {"min_usd": 25.0, "file": "C:/Users/lana/.hermes/media/sol-sniper-package.zip",
               "subject": "SOL Sniper paper decision engine - payment verified"},
}
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")


def rpc(method, params):
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
    req = urllib.request.Request(RPC, data=body, headers={**UA, "Content-Type": "application/json"}, method="POST")
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)


def price():
    req = urllib.request.Request("https://api.exchange.coinbase.com/products/SOL-USD/ticker", headers=UA)
    with urllib.request.urlopen(req, timeout=20) as r:
        return float(json.load(r)["price"])


def load_ledger():
    if os.path.exists(LEDGER):
        return json.load(open(LEDGER, encoding="utf-8"))
    return {"processed": [], "pending": [], "first_run": True}


def save_ledger(d):
    with open(LEDGER, "w", encoding="utf-8") as f:
        json.dump(d, f, indent=2)


def memos(tx):
    out = []
    for instr in (tx.get("transaction", {}).get("message", {}).get("instructions") or []):
        p = instr.get("parsed") or {}
        if p.get("type") == "memo" and isinstance(p.get("info"), str):
            out.append(p["info"])
    for inner in (tx.get("meta") or {}).get("innerInstructions") or []:
        for instr in inner.get("instructions") or []:
            p = instr.get("parsed") or {}
            if p.get("type") == "memo" and isinstance(p.get("info"), str):
                out.append(p["info"])
    return " ".join(out)


def main():
    args = sys.argv[1:]
    led = load_ledger()
    if args[:1] == ["--ack"]:
        sig = args[1] if len(args) > 1 else ""
        if sig and sig not in led["processed"]:
            led["processed"].append(sig)
        led["pending"] = [p for p in led.get("pending", []) if p["sig"] != sig]
        led["first_run"] = False
        save_ledger(led)
        print("ACKED", sig)
        return
    try:
        resp = rpc("getSignaturesForAddress", [WALLET, {"limit": 25}])
    except Exception as e:
        print("RPC_ERROR", repr(e)); sys.exit(2)
    sigs = [x["signature"] for x in (resp.get("result") or [])]
    if led.get("first_run"):
        led["processed"] = sigs[:1]
        led["first_run"] = False
        led["pending"] = []
        save_ledger(led)
        print("[]")
        return
    try:
        px = price()
    except Exception as e:
        print("PRICE_ERROR", repr(e)); sys.exit(2)
    pending = []
    for sig in reversed(sigs):
        if sig in led["processed"]:
            continue
        led["processed"].append(sig)
        try:
            r = rpc("getTransaction", [sig, {"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0}])
        except Exception:
            continue
        tx = r.get("result")
        if not tx or (tx.get("meta") or {}).get("err") is not None:
            continue
        amount = 0.0
        def collect(instrs):
            total = 0.0
            for i in instrs or []:
                p = i.get("parsed") or {}
                if p.get("type") == "transfer" and p.get("info", {}).get("destination") == WALLET:
                    try: total += int(p["info"]["lamports"]) / 1e9
                    except Exception: pass
            return total
        msg = tx.get("transaction", {}).get("message", {})
        amount += collect(msg.get("instructions") or [])
        for inner in (tx.get("meta") or {}).get("innerInstructions") or []:
            amount += collect(inner.get("instructions") or [])
        if amount <= 0:
            continue
        usd = amount * px
        memo = memos(tx)
        em = EMAIL_RE.search(memo)
        product = None
        low = memo.lower()
        if "sniper" in low: product = "sniper"
        elif "jup7" in low: product = "jup7"
        entry = {"sig": sig, "sol": round(amount, 4), "usd": round(usd, 2), "date": datetime.datetime.now(datetime.timezone.utc).isoformat()}
        if em and product and usd >= PRODUCTS[product]["min_usd"]:
            p = PRODUCTS[product]
            entry.update({"product": product, "email": em.group(0), "file": p["file"], "subject": p["subject"]})
            pending.append(entry)
        else:
            entry["needs_manual_review"] = True
            entry["memo_seen"] = memo[:200]
            pending.append(entry)
    led["pending"] = pending
    save_ledger(led)
    print(json.dumps(pending, indent=2))


if __name__ == "__main__":
    main()
