"""Buy energy for a TRON address with the Python x402 SDK (requests).

    pip install "x402[requests,evm]" eth-account
    TRON_X402_API_URL=https://api.awesomefee.com EVM_PRIVATE_KEY=0x... python x402_requests.py TReceiverAddress... 65000
"""
import base64
import json
import os
import sys

from eth_account import Account
from x402 import x402ClientSync
from x402.http.clients.requests import x402_requests
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact import ExactEvmScheme

API = os.environ.get("TRON_X402_API_URL", "https://api.awesomefee.com")
address, energy = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 65000

client = x402ClientSync()
client.register(os.environ.get("X402_NETWORK", "eip155:8453"), ExactEvmScheme(signer=EthAccountSigner(Account.from_key(os.environ["EVM_PRIVATE_KEY"]))))
session = x402_requests(client)

# free: find the product (search-v1)
product = session.get(f"{API}/v1/search", params={"q": "buy energy", "limit": 1}).json()["results"][0]
print("found:", product["id"], product["method"], product["url"])

# free
print("quote:", session.get(f"{API}/x402/v1/quote", params={"product": "energy", "amount": energy}).json())

# paid: 402 -> sign -> 200
r = session.request(product["method"], product["url"], json={"address": address, "amount": energy, "duration_blocks": 1000})
print(r.status_code, r.json())
if "PAYMENT-RESPONSE" in r.headers:
    print("payment:", json.loads(base64.b64decode(r.headers["PAYMENT-RESPONSE"])))
