#!/bin/bash

# Gemini FAQ App Setup Script
# This script automates the complete setup process for the Laravel + React + Python RAG application

set -e  # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to check if DDEV is running
check_ddev_status() {
    if ddev status >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# Function to wait for user input
wait_for_input() {
    echo -e "${YELLOW}Press Enter to continue...${NC}"
    read -r
}

print_status "Starting Gemini FAQ App Setup..."
echo "=================================="

# Step 1: Check prerequisites
print_status "Step 1: Checking prerequisites..."

if ! command_exists ddev; then
    print_error "DDEV is not installed. Please install DDEV first."
    exit 1
fi

if ! command_exists node; then
    print_error "Node.js is not installed. Please install Node.js (v18 or higher)."
    exit 1
fi

if ! command_exists npm; then
    print_error "npm is not installed. Please install npm."
    exit 1
fi

if ! command_exists python3; then
    print_error "Python 3 is not installed. Please install Python 3.10 or higher."
    exit 1
fi

if ! command_exists composer; then
    print_error "Composer is not installed. Please install Composer."
    exit 1
fi

print_success "All prerequisites are installed!"

# Step 2: Setup DDEV
print_status "Step 2: Setting up DDEV environment..."

if ! check_ddev_status; then
    print_status "Starting DDEV..."
    ddev start
else
    print_success "DDEV is already running!"
fi

# Install PHP dependencies
print_status "Installing PHP dependencies..."
ddev composer install

print_success "PHP dependencies installed!"

# Step 3: Environment Configuration
print_status "Step 3: Configuring environment..."

if [ ! -f .env ]; then
    print_status "Creating .env file from .env.example..."
    cp .env.example .env
    print_success ".env file created!"
else
    print_warning ".env file already exists, skipping creation."
fi

# Generate Laravel application key
print_status "Generating Laravel application key..."
ddev artisan key:generate

# Check for Google API key
if ! grep -q "^GOOGLE_API_KEY=" .env || grep -q "^GOOGLE_API_KEY=$" .env; then
    print_warning "Google API key not found in .env file."
    echo -e "${YELLOW}Please enter your Google API key (get one from https://aistudio.google.com/app/apikey):${NC}"
    read -r api_key
    if [ -n "$api_key" ]; then
        if grep -q "^GOOGLE_API_KEY=" .env; then
            sed -i "s/^GOOGLE_API_KEY=.*/GOOGLE_API_KEY=$api_key/" .env
        else
            echo "GOOGLE_API_KEY=$api_key" >> .env
        fi
        print_success "Google API key added to .env file!"
    else
        print_warning "No API key provided. You'll need to add it manually to .env file later."
    fi
fi

print_success "Environment configuration completed!"

# Step 4: Frontend Setup
print_status "Step 4: Setting up React frontend..."

print_status "Installing Node.js dependencies..."
ddev exec "npm install"

print_success "Frontend dependencies installed!"

# Step 5: Python RAG Service Setup
print_status "Step 5: Setting up Python RAG service..."

cd services/rag-service

print_status "Installing Python dependencies..."
pip3 install -r requirements.txt

# Create local environment configuration for DDEV
print_status "Creating Python service environment configuration..."

# Get DDEV database connection details
DDEV_DB_HOST="127.0.0.1"
DDEV_DB_PORT=$(ddev describe | grep "db:3306" | awk -F'->' '{print $2}' | awk -F':' '{print $2}' | tr -d ' ')
DDEV_DB_USER="db"
DDEV_DB_PASSWORD="db"
DDEV_DB_DATABASE="db"

# Get Google API key from main .env file
GOOGLE_API_KEY=$(grep "^GOOGLE_API_KEY=" ../.env | cut -d'=' -f2- | tr -d '"' | tr -d "'")

cat > .env.local << EOF
RAG_DB_HOST=$DDEV_DB_HOST
RAG_DB_PORT=$DDEV_DB_PORT
RAG_DB_USER=$DDEV_DB_USER
RAG_DB_PASSWORD=$DDEV_DB_PASSWORD
RAG_DB_DATABASE=$DDEV_DB_DATABASE
GOOGLE_API_KEY=$GOOGLE_API_KEY
EOF

print_success "Python service environment configured!"

cd ..

# Step 6: Database Setup
print_status "Step 6: Setting up database..."

print_status "Running database migrations..."
ddev artisan migrate

print_success "Database setup completed!"

# Step 7: Test Installation
print_status "Step 7: Testing installation..."

# Start Python service temporarily for testing
print_status "Starting Python RAG service for testing..."
cd services/rag-service
python3 app.py &
PYTHON_PID=$!
cd ../..

# Wait a moment for the service to start
sleep 3

# Test Python service health
print_status "Testing Python service health..."
if curl -s http://127.0.0.1:5002/rag-service/health >/dev/null; then
    print_success "Python service is healthy!"
else
    print_warning "Python service health check failed. It may still be starting up."
fi

# Test Laravel API
print_status "Testing Laravel API..."
DDEV_URL=$(ddev describe | grep "https://" | head -1 | awk '{print $2}')
if curl -s "${DDEV_URL}/api/content/status" >/dev/null; then
    print_success "Laravel API is responding!"
else
    print_warning "Laravel API test failed. Check your DDEV configuration."
fi

# Test Gemini API connection
print_status "Testing Gemini API connection..."
if curl -s http://127.0.0.1:5002/test-gemini >/dev/null; then
    print_success "Gemini API connection is working!"
else
    print_warning "Gemini API test failed. Check your API key configuration."
fi

# Stop the test Python service
kill $PYTHON_PID 2>/dev/null || true

print_success "Installation testing completed!"

# Step 8: Final Instructions
echo ""
echo "=================================="
print_success "🎉 Setup completed successfully!"
echo "=================================="
echo ""
print_status "To start your application:"
echo ""
echo "1. Start the frontend development server:"
echo "   ddev exec 'npm run dev'"
echo ""
echo "2. Start the Python RAG service:"
echo "   cd services/rag-service && ./start.sh"
echo ""
echo "3. Access your application:"
DDEV_URL=$(ddev describe | grep "https://" | head -1 | awk '{print $2}')
echo "   • Chatbot Interface: ${DDEV_URL}"
echo "   • Content Management: ${DDEV_URL}/content-management"
echo "   • Laravel API: ${DDEV_URL}/api/content/"
echo "   • Python RAG Service: http://localhost:5002/rag-service/"
echo ""
print_status "You can also use the provided start_python_service.sh script to start the Python service."
echo ""
print_warning "Note: Make sure your Google API key is correctly set in the .env file before starting the services."
echo ""
print_success "Happy coding! 🚀"
