"""Pays one call to a running starter (used for the Base Sepolia proof, acceptance A5).

Usage: PAYER_KEY=0x... URL=http://localhost:8403/paid python pay.py
"""
from __future__ import annotations

import json
import os
import sys

import httpx
from eth_account import Account

from evm_pay import exact_payment_header
from x402 import decode_header


def main() -> int:
    key = os.environ.get("PAYER_KEY")
    if not key:
        print("Set PAYER_KEY in the environment.", file=sys.stderr)
        return 1
    url = os.environ.get("URL", "http://localhost:8403/paid")
    account = Account.from_key(key)
    with httpx.Client(timeout=60) as client:
        first = client.get(url)
        if first.status_code != 402:
            print(f"expected 402, got {first.status_code}", file=sys.stderr)
            return 1
        header = exact_payment_header(first.json(), account, max_atomic=int(os.environ.get("MAX_ATOMIC", "100000")))
        paid = client.get(url, headers={"X-PAYMENT": header})
    print(f"status {paid.status_code}\n{paid.text}")
    receipt = paid.headers.get("x-payment-response")
    if receipt:
        print("settlement " + json.dumps(decode_header(receipt)))
    return 0 if paid.status_code == 200 else 1


if __name__ == "__main__":
    raise SystemExit(main())
