#!/bin/bash

# Simple Vision Flow Test
# Usage: ./test-vision-simple.sh <projectId>

if [ -z "$1" ]; then
  echo "❌ Usage: ./test-vision-simple.sh <projectId>"
  echo ""
  echo "1. Create a new project in the browser"
  echo "2. Copy its project ID from the URL"
  echo "3. Run: ./test-vision-simple.sh YOUR_PROJECT_ID"
  exit 1
fi

PROJECT_ID="$1"
WORKSPACE="marks-account"
API_URL="http://localhost:3000/api/ai/chat"

# Load test questions
Q1=$(grep "^q1=" .test-questions | cut -d'=' -f2-)
Q2=$(grep "^q2=" .test-questions | cut -d'=' -f2-)
Q3=$(grep "^q3=" .test-questions | cut -d'=' -f2-)

echo "🧪 Vision Flow Test"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Project: $PROJECT_ID"
echo ""

# Function to send message and check response
send_and_check() {
  local msg="$1"
  local step="$2"
  
  echo "[$step] Sending..."
  
  response=$(curl -s -X POST "$API_URL" \
    -H "Content-Type: application/json" \
    -d @- <<EOF
{
  "message": $(echo "$msg" | jq -Rs .),
  "projectId": "$PROJECT_ID",
  "workspaceId": "$WORKSPACE"
}
EOF
  )
  
  if echo "$response" | jq -e '.error' > /dev/null 2>&1; then
    echo "❌ Error: $(echo "$response" | jq -r '.error')"
    exit 1
  fi
  
  echo "✅ [$step] Sent"
  sleep 3
}

echo "Sending Q1..."
send_and_check "$Q1" "Q1"

echo "Sending Q2..."
send_and_check "$Q2" "Q2"

echo "Sending Q3..."
send_and_check "$Q3" "Q3"

echo ""
echo "🔍 Checking logs..."
sleep 2

TERMINAL_LOG="$HOME/.cursor/projects/Users-markhenderson-ai-proxy/terminals/13.txt"

if tail -100 "$TERMINAL_LOG" | grep -q "All 3 vision answers complete"; then
  echo "✅ SUCCESS: All 3 vision answers stored!"
  echo "✅ SUCCESS: MVP generation triggered!"
else
  echo "❌ FAILED: Did not find success marker"
  echo ""
  echo "Last vision-related logs:"
  tail -50 "$TERMINAL_LOG" | grep -E "vision|Q1|Q2|Q3|allAnswered"
  exit 1
fi

echo ""
echo "🎉 Test PASSED!"

