#!/usr/bin/env python3
"""
doormat pay client -- pays a Doormat Capital x402 endpoint and retries the call.

One file, one dependency: pip install eth-account

Usage:
    PRIVATE_KEY=0xabc... python3 pay.py https://signals.sebastiaan-ba3.workers.dev/funding
    PRIVATE_KEY=0xabc... python3 pay.py "https://payverify.sebastiaan-ba3.workers.dev/statement?address=0x..."

What it does, in order:
  1. GET the URL with no payment header.
  2. If it's already a 200, print the body and stop -- nothing to pay for.
  3. If it's a 402, read the x402 "accepts[0]" challenge (amount, asset contract,
     payTo address, chain) straight off the response -- no hardcoded price or
     address, so this works unchanged against any Doormat worker's paid route.
  4. Sign and broadcast a plain ERC-20 transfer() of that exact amount, from the
     wallet behind PRIVATE_KEY, to payTo, on the chain the challenge names.
  5. Wait for the transaction to confirm.
  6. Retry the same GET with header 'X-PAYMENT-TX: <tx hash>' and print the result.

This is a thin client for the X-PAYMENT-TX route documented on every Doormat
worker's free info page and 402 response -- it does not implement the x402
X-PAYMENT facilitator flow, because that route is not yet settleable on these
workers (see each worker's /llms.txt). This script performs an ordinary,
visible on-chain USDC transfer; it holds no funds, trusts no third party, and
sends to exactly the address and amount the server's own 402 response names --
read the challenge it prints before confirming you're happy to proceed.

No warranty. Check the amount and payTo address yourself before funding the
wallet whose key you put in PRIVATE_KEY.
"""
import json
import os
import sys
import time
import urllib.request
import urllib.error

try:
    from eth_account import Account
except ImportError:
    sys.exit("Missing dependency. Run: pip install eth-account")

ERC20_TRANSFER_SELECTOR = "a9059cbb"

# Plain Python's urllib default User-Agent ("Python-urllib/3.x") gets a bare
# 403 ("error code: 1010") from Cloudflare on every endpoint this script talks
# to -- both the Doormat workers and the public Base RPC -- found by testing
# this exact script before shipping it, not assumed. requests/curl's own
# default UAs are not blocked; only urllib's literal default string is. Every
# request below sets an explicit UA so this works out of the box.
UA = "doormat-pay-client/1.0 (+https://doormat.sebastiaan-ba3.workers.dev)"


def rpc(url, method, params):
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
    req = urllib.request.Request(
        url, data=body, headers={"content-type": "application/json", "User-Agent": UA}
    )
    with urllib.request.urlopen(req, timeout=20) as resp:
        out = json.load(resp)
    if "error" in out:
        sys.exit(f"RPC error from {url}: {out['error']}")
    return out["result"]


def http_get(url, headers=None):
    all_headers = {"User-Agent": UA}
    all_headers.update(headers or {})
    req = urllib.request.Request(url, headers=all_headers)
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return resp.status, json.load(resp)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e)


def pad32(hexstr):
    return hexstr.lower().replace("0x", "").rjust(64, "0")


def main():
    if len(sys.argv) < 2:
        sys.exit("Usage: PRIVATE_KEY=0x... python3 pay.py <doormat-paid-url>")
    target = sys.argv[1]
    private_key = os.environ.get("PRIVATE_KEY")
    if not private_key:
        sys.exit("Set PRIVATE_KEY in the environment (the wallet that will pay).")
    acct = Account.from_key(private_key)

    status, body = http_get(target)
    if status != 402:
        print(json.dumps(body, indent=2))
        if status == 200:
            print(f"\n(Status {status} -- already paid or free, nothing to send.)")
        else:
            print(f"\n(Status {status} -- not a payment challenge, stopping.)")
        return

    accepts = (body.get("accepts") or [None])[0]
    if not accepts:
        sys.exit(f"402 response had no 'accepts' challenge to pay:\n{json.dumps(body, indent=2)}")

    amount = int(accepts["amount"])
    asset = accepts["asset"]
    pay_to = accepts["payTo"]
    network = accepts.get("network", "eip155:8453")
    if not network.startswith("eip155:"):
        sys.exit(f"This script only pays EVM (eip155) challenges; got network={network!r}")
    chain_id = int(network.split(":")[-1])
    price_display = amount / 1_000_000

    rpc_url = os.environ.get("BASE_RPC", "https://mainnet.base.org")

    print(f"Challenge: pay {price_display} (atomic units of asset {asset}) to {pay_to} on chain {chain_id}.")
    print(f"Paying from {acct.address} via {rpc_url} ...")

    nonce = int(rpc(rpc_url, "eth_getTransactionCount", [acct.address, "pending"]), 16)
    gas_price = int(rpc(rpc_url, "eth_gasPrice", []), 16)
    data = "0x" + ERC20_TRANSFER_SELECTOR + pad32(pay_to) + pad32(hex(amount))

    tx = {
        "nonce": nonce,
        "gasPrice": int(gas_price * 1.2),
        "gas": 90000,
        "to": asset,
        "value": 0,
        "data": data,
        "chainId": chain_id,
    }
    signed = Account.sign_transaction(tx, private_key)
    raw = signed.raw_transaction if hasattr(signed, "raw_transaction") else signed.rawTransaction
    raw_hex = raw.hex()
    if not raw_hex.startswith("0x"):
        raw_hex = "0x" + raw_hex
    tx_hash = rpc(rpc_url, "eth_sendRawTransaction", [raw_hex])
    print(f"Sent: {tx_hash}")

    print("Waiting for confirmation ...")
    receipt = None
    for _ in range(40):
        receipt = rpc(rpc_url, "eth_getTransactionReceipt", [tx_hash])
        if receipt:
            break
        time.sleep(1.5)
    if not receipt:
        sys.exit(
            f"Transaction {tx_hash} did not confirm within ~60s. Check it on a Base explorer "
            f"and retry the call yourself with header X-PAYMENT-TX: {tx_hash}"
        )
    if receipt.get("status") != "0x1":
        sys.exit(f"Transaction {tx_hash} failed on-chain (status {receipt.get('status')}).")

    print(f"Confirmed: {tx_hash}")
    print("Retrying the call with X-PAYMENT-TX ...")

    status2, body2 = http_get(target, headers={"X-PAYMENT-TX": tx_hash})
    print(f"\nFinal response (status {status2}):")
    print(json.dumps(body2, indent=2))


if __name__ == "__main__":
    main()
