#!/bin/bash
# Solve reCAPTCHA using Capsolver API
# Usage: ./solve-captcha.sh <page_url> <site_key>

CAPSOLVER_KEY="CAP-B49C48AC60460D3DE18D06CE9012816DE2040A3D21476FF09EA90DB00EC423EA"
PAGE_URL="$1"
SITE_KEY="$2"

if [ -z "$PAGE_URL" ] || [ -z "$SITE_KEY" ]; then
  echo "Usage: $0 <page_url> <site_key>"
  exit 1
fi

echo "Creating CAPTCHA solve task..."

# Create task
RESPONSE=$(curl -s -X POST "https://api.capsolver.com/createTask" \
  -H "Content-Type: application/json" \
  -d "{
    \"clientKey\": \"$CAPSOLVER_KEY\",
    \"task\": {
      \"type\": \"ReCaptchaV2TaskProxyLess\",
      \"websiteURL\": \"$PAGE_URL\",
      \"websiteKey\": \"$SITE_KEY\"
    }
  }")

TASK_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('taskId',''))")

if [ -z "$TASK_ID" ]; then
  echo "Error creating task: $RESPONSE"
  exit 1
fi

echo "Task ID: $TASK_ID"
echo "Waiting for solution..."

# Poll for result
for i in {1..60}; do
  sleep 3
  RESULT=$(curl -s -X POST "https://api.capsolver.com/getTaskResult" \
    -H "Content-Type: application/json" \
    -d "{
      \"clientKey\": \"$CAPSOLVER_KEY\",
      \"taskId\": \"$TASK_ID\"
    }")
  
  STATUS=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))")
  
  if [ "$STATUS" = "ready" ]; then
    SOLUTION=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('solution',{}).get('gRecaptchaResponse',''))")
    echo "CAPTCHA_SOLUTION=$SOLUTION"
    exit 0
  elif [ "$STATUS" = "failed" ]; then
    echo "CAPTCHA solve failed: $RESULT"
    exit 1
  fi
  
  echo "Status: $STATUS (attempt $i/60)"
done

echo "Timeout waiting for CAPTCHA solution"
exit 1
