#!/bin/bash

# Test Backend-Led Extraction Flow
# Tests the complete flow: create → collect → backend extract → review

set -e

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

BASE_URL="http://localhost:3000"
TOKEN="Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjM4MDI5MzRmZTBlZWM0NmE1ZWQwMDA2ZDE0YTFiYWIwMWUzNDUwODMiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiTWFyayBIZW5kZXJzb24iLCJwaWN0dXJlIjoiaHR0cHM6Ly9hdmF0YXJzLmdpdGh1YnVzZXJjb250ZW50LmNvbS91LzUzOTU0MjEzP3Y9NCIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9nZW4tbGFuZy1jbGllbnQtMDk4MDA3OTQxMCIsImF1ZCI6Imdlbi1sYW5nLWNsaWVudC0wOTgwMDc5NDEwIiwiYXV0aF90aW1lIjoxNzYzMzI1MDEyLCJ1c2VyX2lkIjoiMmhDdmdXQzJaV2RJMGVlTm5SQVM3SWVKcmg1MiIsInN1YiI6IjJoQ3ZnV0MyWldkSTBlZU5uUkFTN0llSnJoNTIiLCJpYXQiOjE3NjM0MjI1NDUsImV4cCI6MTc2MzQyNjE0NSwiZW1haWwiOiJtYXJrQGdldGFjcXVpcmVkLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJnaXRodWIuY29tIjpbIjUzOTU0MjEzIl0sImVtYWlsIjpbIm1hcmtAZ2V0YWNxdWlyZWQuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoiZ2l0aHViLmNvbSJ9fQ.TpMOORDnPUKkbLlg-KtYBmbarEjAijJ3W4vN8tWT6OslOfwaeDJAtPXIahyQk38UvKY4ZGognQG6t-laSATB8yIC8IdkYbD699axfPSGQqC8Lbux1P6YrFKOPLGDD2XemBtJ-Gb5Ql-nK_DbXKAmygLxIwz019XpLJEucGkBPAN_Rj2xC7125DVexkDSIb6ZnbLiDgCpR_IkImyQb08tqlOoBiHVUa-4VGDhraoBPACJfQXwPToJ1W3nhBiVtMvSq7s_Ekd8Otn8AB_1teu5lxC-rhLdgJuNrmlxO-H6xIMBFZ72bwq7wrvdWd_EijqFQCU99oEhphTNoISoJ3wK-g"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Backend Extraction Flow Test${NC}"
echo -e "${BLUE}========================================${NC}\n"

# Step 1: Create Project
echo -e "${YELLOW}[Step 1]${NC} Creating new project..."

RANDOM_ID=$RANDOM
PROJECT_NAME="Backend Extract Test ${RANDOM_ID}"

CREATE_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/projects/create" \
  -H "Authorization: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"projectName\": \"${PROJECT_NAME}\",
    \"projectType\": \"scratch\",
    \"slug\": \"backend-extract-test-${RANDOM_ID}\",
    \"product\": {
      \"name\": \"${PROJECT_NAME}\"
    }
  }")

PROJECT_ID=$(echo "$CREATE_RESPONSE" | jq -r '.projectId // empty')

if [ -z "$PROJECT_ID" ]; then
  echo -e "${RED}✗ Failed to create project${NC}"
  echo "Response: $CREATE_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✓ Project created: ${PROJECT_ID}${NC}\n"

# Step 2: Upload a test document
echo -e "${YELLOW}[Step 2]${NC} Uploading test document..."

TEST_DOC_PATH="/tmp/test-doc-$RANDOM.md"
cat > "$TEST_DOC_PATH" << 'EOF'
# Product Requirements: TaskFlow

## Problem
Freelancers and small agencies struggle to manage multiple client projects simultaneously. They lose track of deadlines, forget client requests, and spend too much time on administrative work instead of billable hours.

## Target Users
- Freelance designers and developers
- Small creative agencies (2-10 people)
- Solo consultants managing multiple clients

## Core Features
1. **Client Dashboard**: One view per client showing all active projects
2. **Smart Task Capture**: Quickly log tasks from emails, calls, or chat
3. **Automated Reminders**: AI suggests when to follow up based on task age
4. **Time Tracking**: Simple timer integrated into task view
5. **Client Portal**: Clients can see progress without asking for updates

## Technical Constraints
- Must work offline (PWA)
- Mobile-first design
- Budget: $10k development budget
- Timeline: Launch MVP in 8 weeks

## Business Model
- $15/month per user
- 14-day free trial
- Annual plans at 20% discount
EOF

UPLOAD_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/projects/${PROJECT_ID}/knowledge/upload-document" \
  -H "Authorization: ${TOKEN}" \
  -F "file=@${TEST_DOC_PATH}")

UPLOAD_SUCCESS=$(echo "$UPLOAD_RESPONSE" | jq -r '.success // false')

if [ "$UPLOAD_SUCCESS" != "true" ]; then
  echo -e "${RED}✗ Document upload failed${NC}"
  echo "Response: $UPLOAD_RESPONSE"
  rm -f "$TEST_DOC_PATH"
  exit 1
fi

echo -e "${GREEN}✓ Document uploaded${NC}"
rm -f "$TEST_DOC_PATH"

# Step 3: Tell AI about docs and confirm ready
echo -e "\n${YELLOW}[Step 3]${NC} Telling AI about documents..."

CHAT1=$(curl -s -X POST "${BASE_URL}/api/ai/chat" \
  -H "Authorization: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"projectId\": \"${PROJECT_ID}\",
    \"message\": \"I uploaded a requirements document\"
  }")

echo -e "${GREEN}✓ AI acknowledged${NC}"

# Step 4: Say "that's everything" to trigger extraction
echo -e "\n${YELLOW}[Step 4]${NC} Confirming ready for extraction..."

CHAT2=$(curl -s -X POST "${BASE_URL}/api/ai/chat" \
  -H "Authorization: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"projectId\": \"${PROJECT_ID}\",
    \"message\": \"Yes, that's everything. Please analyze it.\"
  }")

echo -e "${GREEN}✓ Extraction triggered${NC}"
echo -e "${YELLOW}⏳ Backend extraction running (this takes 10-30 seconds)...${NC}\n"

# Wait for extraction to complete
sleep 15

# Step 5: Check if extraction completed
echo -e "${YELLOW}[Step 5]${NC} Checking extraction results..."

# Send a message to see if AI presents results
CHAT3=$(curl -s -X POST "${BASE_URL}/api/ai/chat" \
  -H "Authorization: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"projectId\": \"${PROJECT_ID}\",
    \"message\": \"What did you find?\"
  }")

AI_REPLY=$(echo "$CHAT3" | jq -r '.reply // empty')

# Check if AI is still saying "processing"
if echo "$AI_REPLY" | grep -qi "processing\|synthesizing\|analyzing"; then
  echo -e "${RED}✗ AI still says 'processing' - extraction may not have completed${NC}"
  echo -e "\nAI Response:"
  echo "$AI_REPLY"
  echo -e "\n${YELLOW}Try waiting a bit longer, then check: ${BASE_URL}/default/project/${PROJECT_ID}/v_ai_chat${NC}"
  exit 1
fi

# Check if AI is presenting results
if echo "$AI_REPLY" | grep -qi "found\|identified\|problems\|features\|users"; then
  echo -e "${GREEN}✓ AI is presenting extraction results!${NC}"
  echo -e "\n${BLUE}AI Response:${NC}"
  echo "$AI_REPLY" | fold -w 80 -s
  echo -e "\n${GREEN}========================================${NC}"
  echo -e "${GREEN}✓ Backend extraction working!${NC}"
  echo -e "${GREEN}========================================${NC}\n"
  echo -e "View full chat: ${BASE_URL}/default/project/${PROJECT_ID}/v_ai_chat"
else
  echo -e "${YELLOW}⚠ Unclear if extraction worked${NC}"
  echo -e "\nAI Response:"
  echo "$AI_REPLY"
  echo -e "\n${YELLOW}Check manually: ${BASE_URL}/default/project/${PROJECT_ID}/v_ai_chat${NC}"
fi

