#!/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="${MCP_API_KEY:-vw_beta_promo_2026}"
AGENT_ID="${MCP_AGENT_ID:-test_agent_$(date +%s)}"
DEVELOPER_WALLET="${MCP_DEVELOPER_WALLET:-acct_demoagent001}"
SUBMIT="${MCP_DO_SUBMIT:-0}"
SUBMIT_DELAY_MS="${MCP_SUBMIT_DELAY_MS:-1500}"

echo "🚀 Simulating External AI Agent connecting to $API_URL"
echo "🔑 Using Public Beta Token: $API_KEY"
echo "🤖 Agent ID: $AGENT_ID"
echo "💳 Wallet: $DEVELOPER_WALLET"
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": "'"$DEVELOPER_WALLET"'"
  }')

CLAIM_TOKEN=$(echo $CLAIM_RESPONSE | grep -o '"claim_token":"[^"]*"' | cut -d'"' -f4)
CLAIM_STATUS=$(echo $CLAIM_RESPONSE | grep -o '"status":"[^"]*"' | head -n 1 | cut -d'"' -f4)
TASK_LOCK_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

  if [ -n "$ERROR_MSG" ] || [ -z "$CLAIM_TOKEN" ]; then
    echo "❌ Claim failed. Status=$CLAIM_STATUS Error=$ERROR_MSG"
    echo "📄 Response: $CLAIM_RESPONSE"
    if [ "$SUBMIT" = "1" ]; then
      exit 1
    fi
    exit 0
  fi

  echo "✅ Task claimed successfully! Status: $CLAIM_STATUS, token=$CLAIM_TOKEN"

if [ "$SUBMIT" = "1" ]; then
  if [ -z "$CLAIM_TOKEN" ]; then
    echo "❌ Skip submit: claim_token missing."
    exit 1
  fi

  echo "👉 3. Submitting Solution (submit_solution)..."
  if [ "$SUBMIT_DELAY_MS" -gt 0 ]; then
    sleep_time=$(echo "$SUBMIT_DELAY_MS" | awk 'BEGIN{FS=1} {printf "%f", $1/1000}')
    sleep "$sleep_time"
  fi
  SUBMIT_RESPONSE=$(curl -s -X POST "$API_URL/api/mcp/submit_solution" \
    -H "Authorization: Bearer $API_KEY" \
    -H "Content-Type: application/json" \
    -H "x-agent-id: $AGENT_ID" \
    -d '{
      "task_id": "'"$TASK_ID"'",
      "claim_token": "'"$CLAIM_TOKEN"'",
      "deliverables": {
        "README.md": "Automated verification from external test agent."
      },
      "github_pr_url": "https://github.com/example/agent-task-demo/pull/999"
    }')

  SUBMIT_STATUS=$(echo $SUBMIT_RESPONSE | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
  SUBMIT_ERROR=$(echo $SUBMIT_RESPONSE | grep -o '"error":"[^"]*"' | cut -d'"' -f4)

  if [ -n "$SUBMIT_ERROR" ]; then
    echo "❌ Failed to submit solution: $SUBMIT_ERROR"
    echo $SUBMIT_RESPONSE
    exit 1
  fi

  echo "✅ Solution submitted successfully. Status: $SUBMIT_STATUS"
fi

echo "🎉 Test pipeline passed!"
