#!/bin/bash

################################################################################
# World-Class Load Test Environment Setup Script
# 
# This script sets up everything needed for load testing on a fresh system.
# It checks all prerequisites, installs dependencies, and validates the setup.
#
# Usage: ./setup_load_test_environment.sh
################################################################################

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

# Script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$SCRIPT_DIR"

echo -e "${BLUE}================================================================================${NC}"
echo -e "${BLUE}🚀 World-Class Load Test Environment Setup${NC}"
echo -e "${BLUE}================================================================================${NC}"
echo ""

# Function to print status
print_status() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# Step 1: Check Python version
echo -e "${BLUE}Step 1: Checking Python version...${NC}"
if command -v python3 &> /dev/null; then
    PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
    PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1)
    PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d. -f2)
    
    if [ "$PYTHON_MAJOR" -ge 3 ] && [ "$PYTHON_MINOR" -ge 8 ]; then
        print_status "Python $PYTHON_VERSION found (>= 3.8 required)"
    else
        print_error "Python $PYTHON_VERSION found, but 3.8+ is required"
        exit 1
    fi
else
    print_error "Python 3 not found. Please install Python 3.8 or higher."
    exit 1
fi

# Step 2: Check pip
echo ""
echo -e "${BLUE}Step 2: Checking pip...${NC}"
if command -v pip3 &> /dev/null; then
    print_status "pip3 found"
else
    print_error "pip3 not found. Please install pip."
    exit 1
fi

# Step 3: Check/create virtual environment
echo ""
echo -e "${BLUE}Step 3: Setting up virtual environment...${NC}"
if [ -d "$PROJECT_ROOT/venv" ]; then
    print_warning "Virtual environment already exists"
    read -p "Do you want to recreate it? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_info "Removing existing virtual environment..."
        rm -rf "$PROJECT_ROOT/venv"
        python3 -m venv "$PROJECT_ROOT/venv"
        print_status "Virtual environment created"
    else
        print_status "Using existing virtual environment"
    fi
else
    python3 -m venv "$PROJECT_ROOT/venv"
    print_status "Virtual environment created"
fi

# Step 4: Activate virtual environment
echo ""
echo -e "${BLUE}Step 4: Activating virtual environment...${NC}"
source "$PROJECT_ROOT/venv/bin/activate"
print_status "Virtual environment activated"

# Step 5: Upgrade pip
echo ""
echo -e "${BLUE}Step 5: Upgrading pip...${NC}"
pip install --upgrade pip --quiet
print_status "pip upgraded to latest version"

# Step 6: Install requirements
echo ""
echo -e "${BLUE}Step 6: Installing Python dependencies...${NC}"
if [ -f "$PROJECT_ROOT/requirements.txt" ]; then
    pip install -r "$PROJECT_ROOT/requirements.txt" --quiet
    print_status "All Python dependencies installed"
else
    print_error "requirements.txt not found at $PROJECT_ROOT/requirements.txt"
    exit 1
fi

# Step 7: Check Chrome browser
echo ""
echo -e "${BLUE}Step 7: Checking Chrome browser...${NC}"
if command -v google-chrome &> /dev/null || command -v chromium-browser &> /dev/null || command -v chrome &> /dev/null; then
    CHROME_CMD=$(command -v google-chrome || command -v chromium-browser || command -v chrome)
    CHROME_VERSION=$($CHROME_CMD --version 2>&1 | head -n1)
    print_status "Chrome found: $CHROME_VERSION"
else
    print_warning "Chrome browser not found in PATH"
    print_info "Chrome will be installed automatically by webdriver-manager if needed"
    print_info "Or install manually: sudo apt-get install google-chrome-stable (Ubuntu/Debian)"
fi

# Step 8: Check ChromeDriver
echo ""
echo -e "${BLUE}Step 8: Checking ChromeDriver...${NC}"
if command -v chromedriver &> /dev/null; then
    CHROMEDRIVER_VERSION=$(chromedriver --version 2>&1 | head -n1)
    print_status "ChromeDriver found: $CHROMEDRIVER_VERSION"
    print_info "Note: webdriver-manager will handle ChromeDriver automatically if needed"
else
    print_warning "ChromeDriver not found in PATH"
    print_info "webdriver-manager will automatically download and manage ChromeDriver"
    print_status "ChromeDriver will be handled automatically"
fi

# Step 9: Validate function signature
echo ""
echo -e "${BLUE}Step 9: Validating load test function signature...${NC}"
if [ -f "$PROJECT_ROOT/tests/load_tests/validate_function_signature.py" ]; then
    if python3 "$PROJECT_ROOT/tests/load_tests/validate_function_signature.py" 2>/dev/null; then
        print_status "Function signature validation passed"
    else
        print_warning "Function signature validation had issues (this is okay if dependencies aren't fully set up yet)"
    fi
else
    print_warning "Validation script not found (this is okay)"
fi

# Step 10: Check project structure
echo ""
echo -e "${BLUE}Step 10: Validating project structure...${NC}"
REQUIRED_DIRS=("pages" "utils" "tests/load_tests" "config")
REQUIRED_FILES=("tests/load_tests/test_generic_load_assessments.py" "config/config.py")

ALL_GOOD=true
for dir in "${REQUIRED_DIRS[@]}"; do
    if [ -d "$PROJECT_ROOT/$dir" ]; then
        print_status "Directory exists: $dir"
    else
        print_error "Required directory missing: $dir"
        ALL_GOOD=false
    fi
done

for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "$PROJECT_ROOT/$file" ]; then
        print_status "File exists: $file"
    else
        print_error "Required file missing: $file"
        ALL_GOOD=false
    fi
done

if [ "$ALL_GOOD" = false ]; then
    print_error "Project structure validation failed"
    exit 1
fi

# Step 11: Create reports directory
echo ""
echo -e "${BLUE}Step 11: Creating reports directory...${NC}"
mkdir -p "$PROJECT_ROOT/reports/load_tests"
print_status "Reports directory created: reports/load_tests"

# Step 12: Final verification
echo ""
echo -e "${BLUE}Step 12: Final verification...${NC}"

# Test Python imports
python3 -c "
import sys
try:
    import selenium
    import pytest
    print('✅ Core dependencies imported successfully')
except ImportError as e:
    print(f'❌ Import error: {e}')
    sys.exit(1)
" 2>/dev/null

if [ $? -eq 0 ]; then
    print_status "Python imports working correctly"
else
    print_error "Python imports failed"
    exit 1
fi

# Summary
echo ""
echo -e "${GREEN}================================================================================${NC}"
echo -e "${GREEN}✅ Setup Complete!${NC}"
echo -e "${GREEN}================================================================================${NC}"
echo ""
echo -e "${BLUE}📋 Next Steps:${NC}"
echo ""
echo "1. Activate virtual environment:"
echo -e "   ${YELLOW}source venv/bin/activate${NC}"
echo ""
echo "2. Validate function signature:"
echo -e "   ${YELLOW}python3 tests/load_tests/validate_function_signature.py${NC}"
echo ""
echo "3. Run your first load test (1 student):"
echo -e "   ${YELLOW}python3 tests/load_tests/test_generic_load_assessments.py \\${NC}"
echo -e "   ${YELLOW}    --csv your_students.csv \\${NC}"
echo -e "   ${YELLOW}    --start 0 --end 1 \\${NC}"
echo -e "   ${YELLOW}    --workers 1 --headless${NC}"
echo ""
echo -e "${BLUE}📚 Documentation:${NC}"
echo "   - Full guide: tests/load_tests/README.md"
echo "   - Quick reference: tests/load_tests/LOAD_TEST_USAGE.md"
echo "   - Issue resolution: tests/load_tests/VERIFICATION_SUMMARY.md"
echo ""
echo -e "${GREEN}🎉 You're ready to run load tests!${NC}"
echo ""

