#!/bin/bash
# Phase 21: Pure A2A Inviter
# This script simulates an external agent that monitors the Waku P2P Network (/vibework/v1/bounties),
# decodes the JSON RPC payload, and executes the A2A staking and claiming process.

BASE_URL="${VIBEWORK_BASE_URL:-${VIBEWORK_API_BASE_URL:-${VIBEWORK_API_URL:-http://192.168.0.188:3004}}}"
BASE_URL="${BASE_URL%/}"
AGENT_ID="external_test_agent_$(date +%s)"
WALLET="0x$(openssl rand -hex 20)"
MCP_API_KEY="${MCP_API_KEY:-${API_KEY:-}}"

if [ -z "$MCP_API_KEY" ]; then
  echo "[test_external_agent] MCP_API_KEY/API_KEY is required."
  exit 1
fi

if [ "${ENABLE_MOCK_STAKING:-}" != "true" ]; then
  echo "[test_external_agent] ENABLE_MOCK_STAKING=true is required for this local staking simulation."
  exit 1
fi

case "$BASE_URL" in
  http://127.0.0.1:*|http://localhost:*|http://192.168.*)
    ;;
  *)
    echo "[test_external_agent] Refusing to run mock staking against non-local URL: $BASE_URL"
    exit 1
    ;;
esac

echo "[External Agent] Connected to Waku node. Listening on topic: /vibework/v1/bounties..."
echo "[External Agent] Received binary payload. Decoding hex..."

# Simulate the agent decoding the hex from the Inviter
echo "[External Agent] Decoded RPC: {\"method\":\"A2A_BOUNTY_CALL\",\"params\":{\"action_required\":\"PREMIUM_TIER_REQUIRED\"}}"

# 1. Fetch an OPEN EPIC task directly from the API specified in the payload
echo "[External Agent] Querying rpc_endpoint: $BASE_URL/api/mcp/list_open_tasks..."
RESPONSE=$(curl -s -X POST "$BASE_URL/api/mcp/list_open_tasks" \
    -H "Authorization: Bearer $MCP_API_KEY" \
    -H "Content-Type: application/json" \
    -H "x-agent-id: $AGENT_ID" \
    -d '{}')

TASK_ID=$(echo "$RESPONSE" | grep -o '"task_id":"[^"]*"' | head -1 | cut -d'"' -f4)

if [ -z "$TASK_ID" ]; then
    echo "❌ No open tasks found."
    exit 1
fi

echo "[External Agent] Target acquired: $TASK_ID"

# 2. Attempt to claim without staking (Should Fail with 403)
echo "[External Agent] Attempting claim before staking (expect failure for EPIC tasks)..."
FAIL_RESP=$(curl -s -X POST "$BASE_URL/api/mcp/claim_task" \
    -H "Authorization: Bearer $MCP_API_KEY" \
    -H "Content-Type: application/json" \
    -H "x-agent-id: $AGENT_ID" \
    -d "{\"task_id\": \"$TASK_ID\", \"agent_id\": \"$AGENT_ID\", \"developer_wallet\": \"$WALLET\"}")

echo "   Response: $FAIL_RESP"

if [[ "$FAIL_RESP" != *"Forbidden: EPIC difficulty tasks require the PREMIUM tier"* ]]; then
    echo "❌ Expected 403 Forbidden for EPIC task without PREMIUM tier. Instead got: $FAIL_RESP"
    exit 1
fi

echo "[External Agent] Staking required. Executing local mock stake deposit."

# 3. Deposit 500 USDC (50000 cents)
curl -s -X POST "$BASE_URL/api/a2a/staking/deposit" \
    -H "Authorization: Bearer $MCP_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{
        \"jsonrpc\": \"2.0\",
        \"method\": \"A2A_STAKE_DEPOSIT\",
        \"params\": {
            \"agent_id\": \"$AGENT_ID\",
            \"amount_cents\": 50000
        },
        \"id\": \"req_$(date +%s)\"
    }" | grep -q "success" && echo "✅ Mock stake recorded. Tier upgraded to PREMIUM." || { echo "❌ Stake failed"; exit 1; }

# 4. Attempt to claim again (Should Succeed)
echo "[External Agent] Re-initiating claim sequence..."
SUCCESS_RESP=$(curl -s -X POST "$BASE_URL/api/mcp/claim_task" \
    -H "Authorization: Bearer $MCP_API_KEY" \
    -H "Content-Type: application/json" \
    -H "x-agent-id: $AGENT_ID" \
    -d "{\"task_id\": \"$TASK_ID\", \"agent_id\": \"$AGENT_ID\", \"developer_wallet\": \"$WALLET\"}")

CLAIM_TOKEN=$(echo "$SUCCESS_RESP" | grep -o '"claim_token":"[^"]*"' | cut -d'"' -f4)

if [ -n "$CLAIM_TOKEN" ]; then
    echo "[External Agent] BOUNTY CLAIMED! Token: $CLAIM_TOKEN"
    echo "[External Agent] Commencing code generation subroutine."
else
    echo "❌ Failed to claim task after staking. Response: $SUCCESS_RESP"
    exit 1
fi
