#!/usr/bin/env bash
set -u
BASE="https://clawpump.tech"

j(){ if command -v jq >/dev/null 2>&1; then jq -r ".$1 // empty"; else python3 -c "import sys,json;print(json.load(sys.stdin).get('$1','') or '')"; fi; }
jl(){ if command -v jq >/dev/null 2>&1; then jq -r ".launch.$1 // empty"; else python3 -c "import sys,json;d=json.load(sys.stdin);print((d.get('launch') or {}).get('$1','') or '')"; fi; }
jz(){ if command -v jq >/dev/null 2>&1; then jq -r ".launches[0].$1 // empty"; else python3 -c "import sys,json;d=json.load(sys.stdin);l=(d.get('launches') or []);print((l[0] if l else {}).get('$1','') or '')"; fi; }

echo "🦀 ClawPump — tokenize on Robinhood Chain"
echo

# ── Sign in with Google (device flow) ──
S=$(curl -s -X POST "$BASE/api/cli/auth/start")
VID=$(printf '%s' "$S" | j verify_id)
SEC=$(printf '%s' "$S" | j poll_secret)
URL=$(printf '%s' "$S" | j verify_url)
if [ -z "$VID" ]; then echo "❌ Login service unavailable. Try again shortly."; exit 1; fi
echo "→ Sign in with Google — a browser will open."
echo "   $URL"
open "$URL" >/dev/null 2>&1 || xdg-open "$URL" >/dev/null 2>&1 || true
printf "→ Waiting for sign-in"
CPK=""
i=0
while [ $i -lt 150 ]; do
  sleep 2
  i=$((i + 1))
  printf "."
  PB=$(printf '{"verify_id":"%s","poll_secret":"%s"}' "$VID" "$SEC")
  P=$(curl -s -X POST "$BASE/api/cli/auth/poll" -H "Content-Type: application/json" -d "$PB")
  ST=$(printf '%s' "$P" | j status)
  if [ "$ST" = "approved" ]; then CPK=$(printf '%s' "$P" | j key); break; fi
  if [ "$ST" = "expired" ]; then echo; echo "❌ Login expired — run it again."; exit 1; fi
done
echo
if [ -z "$CPK" ]; then echo "❌ Timed out waiting for sign-in."; exit 1; fi
echo "✓ Signed in."
echo

# ── Three questions ──
printf "Token name: "
read -r NAME </dev/tty
if [ -z "$NAME" ]; then echo "A name is required."; exit 1; fi

printf "Ticker (max 12, e.g. CLAW): "
read -r SYM </dev/tty
if [ -z "$SYM" ]; then echo "A ticker is required."; exit 1; fi

echo "Your Robinhood Chain payout address — where your creator fees (ETH/WETH) land."
printf "Payout address (0x...): "
read -r PAYOUT </dev/tty
if ! printf '%s' "$PAYOUT" | grep -qiE '^0x[0-9a-f]{40}$'; then
  echo "❌ That is not a valid 0x EVM address (0x + 40 hex chars)."; exit 1
fi

printf "Logo image URL (https, optional): "
read -r LOGO </dev/tty
if [ -z "$LOGO" ]; then LOGO="https://clawpump.tech/claw-token.webp"; fi

DESC="$NAME, launched on Robinhood Chain via ClawPump."
DESC=$(printf '%s' "$DESC" | tr -d '"')
NAME=$(printf '%s' "$NAME" | tr -d '"')

# ── Create launcher + paid RH launch ──
echo
echo "→ Creating your launcher…"
AB=$(printf '{"name":"%s","strategy":"monitor-exit"}' "$NAME")
A=$(curl -s -X POST "$BASE/api/v1/agents" -H "Authorization: Bearer $CPK" -H "Content-Type: application/json" -d "$AB")
AGENT=$(printf '%s' "$A" | j id)
if [ -z "$AGENT" ]; then echo "❌ Could not create launcher:"; printf '%s\n' "$A"; exit 1; fi

echo "→ Launching $SYM on Robinhood Chain (payment required)…"
LB=$(printf '{"agentId":"%s","name":"%s","symbol":"%s","description":"%s","logoUrl":"%s","payoutWallet":"%s"}' "$AGENT" "$NAME" "$SYM" "$DESC" "$LOGO" "$PAYOUT")
IDEM=$(python3 -c "import uuid; print(uuid.uuid4())")
R=$(curl -s -X POST "$BASE/api/v1/launch/pons" -H "Authorization: Bearer $CPK" -H "Content-Type: application/json" -H "Idempotency-Key: $IDEM" -d "$LB")
if [ "$(printf '%s' "$R" | j error)" = "payment_required" ]; then
  printf '%s
' "$R"
  echo "Pay the exact quote from its paying wallet, or use the dashboard to pay from your agent wallet."
  printf "Payment transaction hash (Enter to stop): "
  read -r PAYMENT_TX </dev/tty
  if [ -z "$PAYMENT_TX" ]; then echo "Resume agent $AGENT at https://clawpump.tech/dashboard"; exit 0; fi
  LB=$(printf '%s' "$LB" | python3 -c 'import sys,json; b=json.load(sys.stdin); b["paymentTxHash"]=sys.argv[1]; print(json.dumps(b))' "$PAYMENT_TX")
  R=$(curl -s -X POST "$BASE/api/v1/launch/pons" -H "Authorization: Bearer $CPK" -H "Content-Type: application/json" -H "Idempotency-Key: $IDEM" -d "$LB")
fi


ERR=$(printf '%s' "$R" | j error)
if [ -n "$ERR" ]; then echo "❌ $ERR"; echo; printf '%s\n' "$R"; exit 1; fi

ADDR=$(printf '%s' "$R" | jl tokenAddress)
if [ -z "$ADDR" ]; then ADDR=$(printf '%s' "$R" | jl predictedTokenAddress); fi
ST=$(printf '%s' "$R" | jl status)
TX=$(printf '%s' "$R" | jl txHash)

# The launch is ASYNCHRONOUS: a paid launch answers 202 with status
# "reserved" and no address, then goes reserved -> submitted -> soft_confirmed.
# Reading the address off the POST alone reported a live token as a failure, and
# the obvious reaction to that is to run it again and mint a SECOND token.
if [ -z "$ADDR" ]; then
  echo
  printf "→ Waiting for the mint to confirm on chain"
  i=0
  while [ $i -lt 60 ]; do
    sleep 4
    i=$((i + 1))
    printf "."
    P=$(curl -s "$BASE/api/agents/$AGENT/pons/launches" -H "Authorization: Bearer $CPK")
    A2=$(printf '%s' "$P" | jz tokenAddress)
    if [ -z "$A2" ]; then A2=$(printf '%s' "$P" | jz predictedTokenAddress); fi
    S2=$(printf '%s' "$P" | jz status)
    T2=$(printf '%s' "$P" | jz txHash)
    if [ -n "$S2" ]; then ST="$S2"; fi
    if [ -n "$T2" ]; then TX="$T2"; fi
    if [ -n "$A2" ]; then ADDR="$A2"; break; fi
    case "$ST" in
      failed|error|cancelled|canceled|rejected)
        echo
        echo "❌ The mint failed on chain (status: $ST)."
        if [ -n "$TX" ]; then echo "   Tx: https://robinhoodchain.blockscout.com/tx/$TX"; fi
        echo
        echo "   Your launcher already exists — reuse it instead of making another:"
        echo "   npx clawpump pons --agent-id $AGENT --name \"$NAME\" --ticker $SYM --payout $PAYOUT"
        exit 1
        ;;
    esac
  done
  echo
fi

if [ -z "$ADDR" ]; then
  echo "⏳ $SYM is still confirming on Robinhood Chain — this is NOT a failure."
  if [ -n "$TX" ]; then echo "   Tx: https://robinhoodchain.blockscout.com/tx/$TX"; fi
  echo "   Status: $ST — it will appear at $BASE/dashboard shortly."
  echo "   Do NOT re-run this, or you will mint a second token."
  exit 0
fi

echo
echo "🎉 Live on Robinhood Chain: $SYM"
echo "   ClawPump:   $BASE/tokens/$ADDR"
echo "   Blockscout: https://robinhoodchain.blockscout.com/token/$ADDR"
echo "   Creator fees route to your payout wallet: $PAYOUT"
