#!/usr/bin/env bash
# AgentPad x Bankr: buy APBUILD / APAD on its AgentPad bonding curve from your Bankr wallet (Base, chainId 8453).
# Usage:  BANKR_API_KEY=bk_... ./agentpad-bankr.sh [TOKEN=APBUILD] [ETH=0.01] [AGENT_ID]
#   TOKEN    APBUILD (default), APAD, or a 0x AgentPad token address
#   ETH      ETH to spend on the buy (default 0.01)
#   AGENT_ID an ERC-8004 agentId your Bankr wallet already owns (optional; skips the identity mint)
#   YES=1    skip the confirmation prompt
# Needs: curl, jq. Your Bankr key needs walletApiEnabled (read-write) and "Enable arbitrary contract calls" ON.
# Raw submits are not gas-sponsored: keep ~0.0001 ETH on Base for gas on top of the buy.
# Curve tokens are tiny and illiquid and can go to zero. No profit is promised.
set -euo pipefail
TOKEN=${1:-APBUILD}; ETH=${2:-0.01}; AGENT_ID=${3:-}
: "${BANKR_API_KEY:?set BANKR_API_KEY}"
BANKR=${BANKR_API_URL:-https://api.bankr.bot}; API=${AGENTPAD_API:-https://api.agentpadbase.com}; RPC=${BASE_RPC_URL:-https://mainnet.base.org}
REG=0x8004a169fb4a3325136eb29fa0ceb6d2e539a432
TRANSFER=0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef

WALLET=$(curl -sf "$BANKR/wallet/me" -H "X-API-Key: $BANKR_API_KEY" | jq -r '.wallets[] | select(.chain=="evm") | .address' | head -1)
[ -n "$WALLET" ] || { echo "could not read your Bankr EVM wallet (GET /wallet/me)"; exit 1; }
plan() { local q="wallet=$WALLET&buy=$TOKEN&eth=$ETH"; [ -n "$AGENT_ID" ] && q="$q&agentId=$AGENT_ID"; curl -sf "$API/v1/onboard?$q"; }
PLAN=$(plan)
echo "$PLAN" | jq '{wallet, token: .token.symbol, txCount, summary, expectedTokens: .buy.expectedTokens, minTokensOut: .buy.minTokensOut, walletBalanceEth, enoughEth, risk}'
if [ "${YES:-}" != 1 ]; then read -r -p "Send these txs from your Bankr wallet $WALLET? [y/N] " a; [ "$a" = y ] || exit 0; fi

submit() { # $1 = one bankr body (JSON). Prints the tx hash; exits on failure.
  local r; r=$(curl -s -X POST "$BANKR/wallet/submit" -H "X-API-Key: $BANKR_API_KEY" -H 'content-type: application/json' -d "$1")
  if [ "$(echo "$r" | jq -r '.success')" != true ] || [ "$(echo "$r" | jq -r '.status')" != success ]; then echo "submit failed: $(echo "$r" | jq -c '{status,error,errorCode,transactionHash}')" >&2; exit 1; fi
  echo "$r" | jq -r '.transactionHash'
}

if [ "$(echo "$PLAN" | jq -r '.calls[0].step')" = identity ]; then
  H=$(submit "$(echo "$PLAN" | jq -c '.bankr.bodies[0]')"); echo "identity: $H"
  # read the real agentId from the Transfer event (no guessing), then rebuild the remaining calls
  AGENT_ID=$(curl -s -X POST $RPC -H 'content-type: application/json' -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_getTransactionReceipt\",\"params\":[\"$H\"]}" \
    | jq -r --arg reg $REG --arg t $TRANSFER '.result.logs[] | select((.address|ascii_downcase)==$reg and .topics[0]==$t) | .topics[3]' | head -1)
  AGENT_ID=$(printf '%d' "$AGENT_ID"); echo "agentId: $AGENT_ID"
  PLAN=$(plan)
fi
n=$(echo "$PLAN" | jq '.bankr.bodies | length')
for i in $(seq 0 $((n - 1))); do
  step=$(echo "$PLAN" | jq -r ".calls[$i].step"); H=$(submit "$(echo "$PLAN" | jq -c ".bankr.bodies[$i]")"); echo "$step: $H"
done
echo "done. Your agent page: $API/v1/agents/$WALLET . Sell any time (no pass needed): POST $API/v1/tx/sell"
