#!/usr/bin/env bash
set -euo pipefail

# curl cannot create an EIP-712 signature by itself. This script uses the
# published Node/viem helper only for signing; both HTTP requests use curl.

BASE_URL="${BASE_URL:-https://energy.netzhandwerker.de}"
API_URL="${API_URL:-${BASE_URL}/predict/negative-price}"
REQUEST_BODY_JSON="${REQUEST_BODY_JSON:-{}}"
MAX_AMOUNT_UNITS="${MAX_AMOUNT_UNITS:-1000}"

if [[ -z "${PRIVATE_KEY:-}" ]]; then
  echo "MISSING_PRIVATE_KEY: set PRIVATE_KEY to a Base wallet key holding USDC" >&2
  exit 2
fi

workdir="$(mktemp -d "./.energy-x402.XXXXXX")"
trap 'rm -rf "$workdir"' EXIT

helper="${HELPER_PATH:-}"
if [[ -z "$helper" ]]; then
  curl -fsS "${BASE_URL}/examples/sign-eip3009.mjs" -o "$workdir/sign-eip3009.mjs"
  curl -fsS "${BASE_URL}/examples/eip3009-payment.mjs" -o "$workdir/eip3009-payment.mjs"
  helper="$workdir/sign-eip3009.mjs"
fi

status="$({ curl -sS -D "$workdir/first.headers" -o "$workdir/first.body" -w '%{http_code}' \
  -X POST "$API_URL" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: energy-hub-curl-x402-example/1.0' \
  --data "$REQUEST_BODY_JSON"; } || true)"

if [[ "$status" != "402" ]]; then
  echo "EXPECTED_402: first request returned HTTP $status" >&2
  cat "$workdir/first.body" >&2
  exit 1
fi
echo "1/3 HTTP 402 received"

payment_required="$(awk 'BEGIN{IGNORECASE=1} /^Payment-Required:/ {sub(/^[^:]+:[[:space:]]*/, ""); gsub(/\r/, ""); print; exit}' "$workdir/first.headers")"
if [[ -z "$payment_required" ]]; then
  echo "MISSING_HEADER: Payment-Required was not returned" >&2
  exit 1
fi

payment_signature="$(
  PAYMENT_REQUIRED="$payment_required" \
  PRIVATE_KEY="$PRIVATE_KEY" \
  BASE_RPC_URL="${BASE_RPC_URL:-https://mainnet.base.org}" \
  MAX_AMOUNT_UNITS="$MAX_AMOUNT_UNITS" \
  node "$helper"
)"
echo "2/3 EIP-3009 signed; PAYMENT-SIGNATURE is base64 JSON"

status="$({ curl -sS -D "$workdir/paid.headers" -o "$workdir/paid.body" -w '%{http_code}' \
  -X POST "$API_URL" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: energy-hub-curl-x402-example/1.0' \
  -H "PAYMENT-SIGNATURE: $payment_signature" \
  --data "$REQUEST_BODY_JSON"; } || true)"

if [[ "$status" != "200" ]]; then
  echo "PAID_REQUEST_FAILED: retry returned HTTP $status" >&2
  echo "Expired validBefore, a wrong amount, a reused nonce, or insufficient USDC causes rejection and no valid result." >&2
  cat "$workdir/paid.body" >&2
  exit 1
fi

echo "3/3 HTTP 200 received"
payment_response="$(awk 'BEGIN{IGNORECASE=1} /^Payment-Response:|^X-Payment-Response:/ {sub(/^[^:]+:[[:space:]]*/, ""); gsub(/\r/, ""); print; exit}' "$workdir/paid.headers")"
if [[ -n "$payment_response" ]]; then
  PAYMENT_RESPONSE="$payment_response" node -e 'console.log("Payment response:", JSON.parse(Buffer.from(process.env.PAYMENT_RESPONSE, "base64").toString("utf8")))'
fi
cat "$workdir/paid.body"
