#!/bin/bash

# Simplified E2E Test - Create Project → AI Chat → Collector Flow
# This tests the new streamlined project creation flow

set -e

# Colors
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}  Simplified Project Creation 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="E2E 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\": \"e2e-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: Send first message to AI (should trigger welcome)
echo -e "${YELLOW}[Step 2]${NC} Sending first message to AI..."

AI_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/ai/chat" \
  -H "Authorization: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"projectId\": \"${PROJECT_ID}\",
    \"message\": \"Hello\"
  }")

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

if [ -z "$AI_REPLY" ]; then
  echo -e "${RED}✗ Failed to get AI response${NC}"
  echo "Response: $AI_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✓ AI responded${NC}"
echo -e "  Reply preview: ${AI_REPLY:0:100}...\n"

# Step 3: Check conversation history
echo -e "${YELLOW}[Step 3]${NC} Checking conversation history..."

HISTORY_RESPONSE=$(curl -s -X GET "${BASE_URL}/api/ai/conversation?projectId=${PROJECT_ID}" \
  -H "Authorization: ${TOKEN}")

MESSAGE_COUNT=$(echo "$HISTORY_RESPONSE" | jq '.messages | length')

if [ "$MESSAGE_COUNT" -lt 2 ]; then
  echo -e "${RED}✗ Conversation history incomplete (found ${MESSAGE_COUNT} messages)${NC}"
  echo "Response: $HISTORY_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✓ Conversation history persisted (${MESSAGE_COUNT} messages)${NC}\n"

# Step 4: Check collector handoff state
echo -e "${YELLOW}[Step 4]${NC} Checking collector handoff state..."

HANDOFF_RESPONSE=$(curl -s -X GET "${BASE_URL}/api/ai/conversation?projectId=${PROJECT_ID}" \
  -H "Authorization: ${TOKEN}")

# The handoff data should be in the project document, let's just verify the conversation loaded
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✓ Collector handoff endpoint accessible${NC}\n"
else
  echo -e "${YELLOW}⚠ Could not verify handoff state directly${NC}\n"
fi

# Step 5: Simulate user saying they'll upload docs
echo -e "${YELLOW}[Step 5]${NC} Simulating user interaction (uploading docs)..."

DOCS_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/ai/chat" \
  -H "Authorization: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"projectId\": \"${PROJECT_ID}\",
    \"message\": \"I am going to upload some docs\"
  }")

DOCS_REPLY=$(echo "$DOCS_RESPONSE" | jq -r '.reply // empty')

if [ -z "$DOCS_REPLY" ]; then
  echo -e "${RED}✗ Failed to get AI response${NC}"
  exit 1
fi

echo -e "${GREEN}✓ AI acknowledged document upload${NC}"
echo -e "  Reply preview: ${DOCS_REPLY:0:100}...\n"

# Step 6: Simulate uploading a document
echo -e "${YELLOW}[Step 6]${NC} Simulating document upload..."

# Create a test file
TEST_DOC_PATH="/tmp/test-document-$RANDOM.md"
cat > "$TEST_DOC_PATH" << 'EOF'
# Test Product Requirements

## Overview
This is a test document for the E2E flow.

## Features
- Feature 1: User authentication
- Feature 2: Dashboard
- Feature 3: Analytics

## Tech Stack
- Next.js
- TypeScript
- Firebase
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 successfully${NC}"
rm -f "$TEST_DOC_PATH"

# Get the knowledge item ID
KNOWLEDGE_ITEM_ID=$(echo "$UPLOAD_RESPONSE" | jq -r '.knowledgeItemId // empty')
echo -e "  Knowledge item: ${KNOWLEDGE_ITEM_ID}\n"

# Step 7: Tell AI about the upload
echo -e "${YELLOW}[Step 7]${NC} Informing AI about uploaded document..."

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

INFORM_REPLY=$(echo "$INFORM_RESPONSE" | jq -r '.reply // empty')

if [ -z "$INFORM_REPLY" ]; then
  echo -e "${RED}✗ Failed to get AI response${NC}"
  exit 1
fi

echo -e "${GREEN}✓ AI acknowledged upload${NC}"
echo -e "  Reply preview: ${INFORM_REPLY:0:100}...\n"

# Step 8: Check final conversation state
echo -e "${YELLOW}[Step 8]${NC} Checking final conversation state..."

FINAL_HISTORY=$(curl -s -X GET "${BASE_URL}/api/ai/conversation?projectId=${PROJECT_ID}" \
  -H "Authorization: ${TOKEN}")

FINAL_MESSAGE_COUNT=$(echo "$FINAL_HISTORY" | jq '.messages | length')

if [ "$FINAL_MESSAGE_COUNT" -lt 6 ]; then
  echo -e "${RED}✗ Final conversation history incomplete (found ${FINAL_MESSAGE_COUNT} messages)${NC}"
  exit 1
fi

echo -e "${GREEN}✓ Final conversation history complete (${FINAL_MESSAGE_COUNT} messages)${NC}\n"

# Summary
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}✓ All tests passed!${NC}"
echo -e "${BLUE}========================================${NC}\n"

echo -e "Test Summary:"
echo -e "  • Project ID: ${PROJECT_ID}"
echo -e "  • Total Messages: ${FINAL_MESSAGE_COUNT}"
echo -e "  • Documents Uploaded: 1"
echo -e "  • Knowledge Items: ${KNOWLEDGE_ITEM_ID}"
echo -e ""
echo -e "Next Steps:"
echo -e "  1. Open ${BASE_URL}/default/project/${PROJECT_ID}/v_ai_chat"
echo -e "  2. Verify the collector checklist shows 1 document"
echo -e "  3. Continue the conversation to test GitHub/extension flow"
echo -e ""

