#!/bin/bash

# E2E Test Runner Script
set -e

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

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
E2E_DIR="$(dirname "$SCRIPT_DIR")"
ROOT_DIR="$(dirname "$E2E_DIR")"

# Default values
RUN_PERFORMANCE=false
HEADLESS=true
BROWSER="chromium"
WORKERS=1
RETRIES=0

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --performance)
      RUN_PERFORMANCE=true
      shift
      ;;
    --headed)
      HEADLESS=false
      shift
      ;;
    --browser)
      BROWSER="$2"
      shift 2
      ;;
    --workers)
      WORKERS="$2"
      shift 2
      ;;
    --retries)
      RETRIES="$2"
      shift 2
      ;;
    --help)
      echo "Usage: $0 [OPTIONS]"
      echo "Options:"
      echo "  --performance    Run performance tests after E2E tests"
      echo "  --headed         Run tests in headed mode (visible browser)"
      echo "  --browser        Browser to use (chromium, firefox, webkit)"
      echo "  --workers        Number of parallel workers"
      echo "  --retries        Number of retries for failed tests"
      echo "  --help           Show this help message"
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      exit 1
      ;;
  esac
done

echo -e "${BLUE}🚀 Starting E2E Test Suite${NC}"
echo "Configuration:"
echo "  - Performance tests: $RUN_PERFORMANCE"
echo "  - Headless mode: $HEADLESS"
echo "  - Browser: $BROWSER"
echo "  - Workers: $WORKERS"
echo "  - Retries: $RETRIES"
echo ""

# Function to check if a service is running
check_service() {
  local url=$1
  local service_name=$2
  local max_attempts=30
  local attempt=1

  echo -e "${YELLOW}Checking $service_name...${NC}"
  
  while [ $attempt -le $max_attempts ]; do
    if curl -s "$url" > /dev/null 2>&1; then
      echo -e "${GREEN}✅ $service_name is ready${NC}"
      return 0
    fi
    
    echo "Attempt $attempt/$max_attempts: Waiting for $service_name..."
    sleep 2
    ((attempt++))
  done
  
  echo -e "${RED}❌ $service_name failed to start${NC}"
  return 1
}

# Function to start services
start_services() {
  echo -e "${BLUE}🔧 Starting services...${NC}"
  
  cd "$ROOT_DIR"
  
  # Start backend services
  echo "Starting backend services..."
  npm run dev:backend > /dev/null 2>&1 &
  BACKEND_PID=$!
  
  # Start frontend
  echo "Starting frontend..."
  npm run dev:frontend > /dev/null 2>&1 &
  FRONTEND_PID=$!
  
  # Wait for services to be ready
  check_service "http://localhost:3001/health" "Backend API"
  check_service "http://localhost:3000" "Frontend"
  
  echo -e "${GREEN}✅ All services are running${NC}"
}

# Function to stop services
stop_services() {
  echo -e "${YELLOW}🛑 Stopping services...${NC}"
  
  if [ ! -z "$BACKEND_PID" ]; then
    kill $BACKEND_PID 2>/dev/null || true
  fi
  
  if [ ! -z "$FRONTEND_PID" ]; then
    kill $FRONTEND_PID 2>/dev/null || true
  fi
  
  # Kill any remaining processes
  pkill -f "npm run dev" 2>/dev/null || true
  pkill -f "vite" 2>/dev/null || true
  pkill -f "ts-node" 2>/dev/null || true
  
  echo -e "${GREEN}✅ Services stopped${NC}"
}

# Function to run E2E tests
run_e2e_tests() {
  echo -e "${BLUE}🧪 Running E2E tests...${NC}"
  
  cd "$E2E_DIR"
  
  # Build Playwright command
  local cmd="npx playwright test"
  
  if [ "$HEADLESS" = false ]; then
    cmd="$cmd --headed"
  fi
  
  cmd="$cmd --project=$BROWSER"
  cmd="$cmd --workers=$WORKERS"
  cmd="$cmd --retries=$RETRIES"
  
  echo "Running: $cmd"
  
  if $cmd; then
    echo -e "${GREEN}✅ E2E tests passed${NC}"
    return 0
  else
    echo -e "${RED}❌ E2E tests failed${NC}"
    return 1
  fi
}

# Function to run performance tests
run_performance_tests() {
  echo -e "${BLUE}⚡ Running performance tests...${NC}"
  
  cd "$E2E_DIR"
  
  # Check if k6 is installed
  if ! command -v k6 &> /dev/null; then
    echo -e "${RED}❌ k6 is not installed. Please install k6 to run performance tests.${NC}"
    echo "Installation instructions: https://k6.io/docs/getting-started/installation/"
    return 1
  fi
  
  echo "Running API performance tests..."
  if k6 run performance/api-performance.js; then
    echo -e "${GREEN}✅ API performance tests passed${NC}"
  else
    echo -e "${RED}❌ API performance tests failed${NC}"
    return 1
  fi
  
  echo "Running load tests..."
  if k6 run performance/load-test.js; then
    echo -e "${GREEN}✅ Load tests passed${NC}"
  else
    echo -e "${RED}❌ Load tests failed${NC}"
    return 1
  fi
  
  return 0
}

# Function to generate test report
generate_report() {
  echo -e "${BLUE}📊 Generating test report...${NC}"
  
  cd "$E2E_DIR"
  
  if [ -d "playwright-report" ]; then
    echo "Playwright HTML report available at: $E2E_DIR/playwright-report/index.html"
    
    # Try to open the report in the default browser (if not in CI)
    if [ -z "$CI" ] && command -v open &> /dev/null; then
      open playwright-report/index.html
    elif [ -z "$CI" ] && command -v xdg-open &> /dev/null; then
      xdg-open playwright-report/index.html
    fi
  fi
}

# Trap to ensure services are stopped on exit
trap stop_services EXIT

# Main execution
main() {
  # Check if we're in the right directory
  if [ ! -f "$ROOT_DIR/package.json" ]; then
    echo -e "${RED}❌ Please run this script from the project root or e2e directory${NC}"
    exit 1
  fi
  
  # Install dependencies if needed
  if [ ! -d "$E2E_DIR/node_modules" ]; then
    echo -e "${YELLOW}📦 Installing E2E test dependencies...${NC}"
    cd "$E2E_DIR"
    npm install
  fi
  
  # Install Playwright browsers if needed
  if [ ! -d "$HOME/.cache/ms-playwright" ]; then
    echo -e "${YELLOW}🌐 Installing Playwright browsers...${NC}"
    cd "$E2E_DIR"
    npx playwright install
  fi
  
  # Start services
  start_services
  
  # Run E2E tests
  local e2e_result=0
  run_e2e_tests || e2e_result=$?
  
  # Run performance tests if requested
  local perf_result=0
  if [ "$RUN_PERFORMANCE" = true ]; then
    run_performance_tests || perf_result=$?
  fi
  
  # Generate report
  generate_report
  
  # Summary
  echo ""
  echo -e "${BLUE}📋 Test Summary${NC}"
  if [ $e2e_result -eq 0 ]; then
    echo -e "${GREEN}✅ E2E Tests: PASSED${NC}"
  else
    echo -e "${RED}❌ E2E Tests: FAILED${NC}"
  fi
  
  if [ "$RUN_PERFORMANCE" = true ]; then
    if [ $perf_result -eq 0 ]; then
      echo -e "${GREEN}✅ Performance Tests: PASSED${NC}"
    else
      echo -e "${RED}❌ Performance Tests: FAILED${NC}"
    fi
  fi
  
  # Exit with appropriate code
  if [ $e2e_result -ne 0 ] || [ $perf_result -ne 0 ]; then
    exit 1
  fi
  
  echo -e "${GREEN}🎉 All tests completed successfully!${NC}"
}

# Run main function
main "$@"