#!/usr/bin/env python3
"""Verify a Solana payment to the JUP7 listing wallet.

Usage: python3 verify_payment.py <transaction_signature>
Prints VERIFIED <usd> USD when the successful transaction transferred at least
$20 worth of SOL to the listing wallet, otherwise NOT_FOUND / FAILED / UNDERPAID.
"""
import json, sys, urllib.request

WALLET = "EFCC9rEwbsBHr92vNTyGHYRswH1fg5M8ZdrPCfuSsLpQ"
RPC = "https://api.mainnet-beta.solana.com"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ChainLedgerPublisher/1.0"}
MIN_USD = 20.0


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 sol_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 collect(parsed_instructions):
    total = 0.0
    for instr in parsed_instructions or []:
        parsed = instr.get("parsed") or {}
        if parsed.get("type") == "transfer" and parsed.get("info", {}).get("destination") == WALLET:
            try:
                total += int(parsed["info"]["lamports"]) / 1e9
            except (ValueError, TypeError, KeyError):
                pass
    return total


def main():
    if len(sys.argv) < 2:
        print("USAGE: verify_payment.py <signature>"); sys.exit(2)
    sig = sys.argv[1].strip()
    if not (60 <= len(sig) <= 90):
        print("INVALID_SIGNATURE"); sys.exit(2)
    try:
        resp = rpc("getTransaction", [sig, {"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0}])
    except Exception as e:
        print("RPC_ERROR", repr(e)); sys.exit(2)
    tx = resp.get("result")
    if not tx:
        print("NOT_FOUND"); sys.exit(3)
    if (tx.get("meta") or {}).get("err") is not None:
        print("FAILED"); sys.exit(3)
    msg = (tx.get("transaction") or {}).get("message") or {}
    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:
        print("NO_TRANSFER_TO_LISTING_WALLET"); sys.exit(3)
    try:
        usd = amount * sol_price()
    except Exception as e:
        print("PRICE_ERROR", repr(e)); sys.exit(2)
    if usd >= MIN_USD:
        print(f"VERIFIED {usd:.2f} USD ({amount:.4f} SOL) sig={sig}")
    else:
        print(f"UNDERPAID {usd:.2f} USD ({amount:.4f} SOL) sig={sig}")


if __name__ == "__main__":
    main()
