#!/bin/bash

# VibeWork External Agent MCP API Test Script
# This script simulates an external AI agent discovering the network via the Beta Promo token.

API_URL=${1:-"https://agent.wooo.work"}
API_KEY="vw_beta_promo_2026"
AGENT_ID="test_agent_$(date +%s)"

echo "🚀 Simulating External AI Agent connecting to $API_URL"
echo "🔑 Using Public Beta Token: $API_KEY"
echo "🤖 Agent ID: $AGENT_ID"
echo "---------------------------------------------------"

# 1. Fetch Open Tasks
echo "👉 1. Fetching Open Tasks (list_open_tasks)..."
TASKS_RESPONSE=$(curl -s -X POST "$API_URL/api/mcp/list_open_tasks" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -H "x-agent-id: $AGENT_ID" \
  -d '{"skills": []}')

TOTAL_OPEN=$(echo $TASKS_RESPONSE | grep -o '"total_open":[0-9]*' | cut -d':' -f2)

if [ -z "$TOTAL_OPEN" ]; then
  echo "❌ Error parsing list_open_tasks response:"
  echo $TASKS_RESPONSE
  exit 1
fi

echo "✅ Found $TOTAL_OPEN open tasks."

if [ "$TOTAL_OPEN" -eq "0" ]; then
  echo "⚠️ No open tasks available to claim. Stopping test."
  exit 0
fi

# 2. Extract first task ID
TASK_ID=$(echo $TASKS_RESPONSE | grep -o '"task_id":"[^"]*"' | head -n 1 | cut -d'"' -f4)
echo "🎯 Selecting Task ID: $TASK_ID"

# 3. Claim the task
echo "👉 2. Claiming Task (claim_task)..."
CLAIM_RESPONSE=$(curl -s -X POST "$API_URL/api/mcp/claim_task" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -H "x-agent-id: $AGENT_ID" \
  -d '{
    "task_id": "'"$TASK_ID"'",
    "agent_id": "'"$AGENT_ID"'",
    "developer_wallet": "0xTestWalletExternalAgent999"
  }')

CLAIM_STATUS=$(echo $CLAIM_RESPONSE | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
ERROR_MSG=$(echo $CLAIM_RESPONSE | grep -o '"error":"[^"]*"' | cut -d'"' -f4)

if [ -n "$ERROR_MSG" ]; then
  echo "❌ Failed to claim task: $ERROR_MSG"
  exit 1
fi

echo "✅ Task claimed successfully! Status: $CLAIM_STATUS"

# We won't submit solution because we don't have the real sandbox context.
echo "🎉 Test pipeline passed!"
