#!/bin/bash
# E2E Test Environment Setup Script
# Sets up the local environment for running Playwright E2E tests
#
# Usage: ./scripts/setup-e2e-env.sh
#
# This script:
#   1. Checks prerequisites (docker, node, npx)
#   2. Installs npm dependencies
#   3. Installs Playwright browsers (firefox only for CI alignment)
#   4. Creates .env.test if not exists
#   5. Starts the Docker test environment
#   6. Waits for health check
#   7. Outputs success message with URLs
#
# Rebuild note:
#   For CI-aligned E2E container rebuilds, prefer:
#   .github/skills/scripts/skill-runner.sh docker-rebuild-e2e

set -euo pipefail

# 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
COMPOSE_FILE=".docker/compose/docker-compose.test.yml"
HEALTH_URL="http://localhost:8080/api/v1/health"
HEALTH_TIMEOUT=60

# Get script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Change to project root
cd "${PROJECT_ROOT}"

echo -e "${BLUE}🚀 Setting up E2E test environment...${NC}"
echo ""

# Function to check if a command exists
check_command() {
    local cmd="$1"
    local name="${2:-$1}"
    if command -v "${cmd}" >/dev/null 2>&1; then
        echo -e "  ${GREEN}✓${NC} ${name} found: $(command -v "${cmd}")"
        return 0
    else
        echo -e "  ${RED}✗${NC} ${name} not found"
        return 1
    fi
}

# Function to wait for health check
wait_for_health() {
    local url="$1"
    local timeout="$2"
    local start_time
    start_time=$(date +%s)

    echo -e "${BLUE}⏳ Waiting for service to be healthy (timeout: ${timeout}s)...${NC}"

    while true; do
        local current_time
        current_time=$(date +%s)
        local elapsed=$((current_time - start_time))

        if [[ ${elapsed} -ge ${timeout} ]]; then
            echo -e "${RED}❌ Health check timed out after ${timeout}s${NC}"
            echo ""
            echo "Container logs:"
            docker compose -f "${COMPOSE_FILE}" logs --tail=50
            return 1
        fi

        if curl -sf "${url}" >/dev/null 2>&1; then
            echo -e "${GREEN}✅ Service is healthy!${NC}"
            return 0
        fi

        printf "  Checking... (%ds elapsed)\r" "${elapsed}"
        sleep 2
    done
}

# Step 1: Check prerequisites
echo -e "${BLUE}📋 Step 1: Checking prerequisites...${NC}"
PREREQS_OK=true

if ! check_command "docker" "Docker"; then
    PREREQS_OK=false
fi

if ! check_command "node" "Node.js"; then
    PREREQS_OK=false
else
    NODE_VERSION=$(node --version)
    echo -e "     Version: ${NODE_VERSION}"
fi

if ! check_command "npx" "npx"; then
    PREREQS_OK=false
fi

if ! check_command "npm" "npm"; then
    PREREQS_OK=false
fi

if [[ "${PREREQS_OK}" != "true" ]]; then
    echo ""
    echo -e "${RED}❌ Prerequisites check failed. Please install missing dependencies.${NC}"
    exit 1
fi

# Check Docker daemon is running
if ! docker info >/dev/null 2>&1; then
    echo -e "${RED}❌ Docker daemon is not running. Please start Docker.${NC}"
    exit 1
fi
echo -e "  ${GREEN}✓${NC} Docker daemon is running"

echo ""

# Step 2: Install npm dependencies
echo -e "${BLUE}📦 Step 2: Installing npm dependencies...${NC}"
npm ci --silent
echo -e "${GREEN}✅ Dependencies installed${NC}"
echo ""

# Step 3: Install Playwright browsers
echo -e "${BLUE}🎭 Step 3: Installing Playwright browsers (firefox only)...${NC}"
npx playwright install firefox --with-deps
echo -e "${GREEN}✅ Playwright browsers installed${NC}"
echo ""

# Step 4: Create .env.test if not exists
echo -e "${BLUE}📝 Step 4: Setting up environment configuration...${NC}"
ENV_TEST_FILE=".env.test"

if [[ ! -f "${ENV_TEST_FILE}" ]]; then
    if [[ -f ".env.test.example" ]]; then
        cp ".env.test.example" "${ENV_TEST_FILE}"
        echo -e "  ${GREEN}✓${NC} Created ${ENV_TEST_FILE} from .env.test.example"
    else
        # Create minimal .env.test
        cat > "${ENV_TEST_FILE}" <<EOF
# E2E Test Environment Configuration
# Generated by setup-e2e-env.sh

NODE_ENV=test
DATABASE_URL=sqlite:./data/charon_test.db
BASE_URL=http://localhost:8080
PLAYWRIGHT_BASE_URL=http://localhost:8080
TEST_USER_EMAIL=test-admin@charon.local
TEST_USER_PASSWORD=TestPassword123!
DOCKER_HOST=unix:///var/run/docker.sock
ENABLE_CROWDSEC=false
ENABLE_WAF=false
LOG_LEVEL=warn
EOF
        echo -e "  ${GREEN}✓${NC} Created ${ENV_TEST_FILE} with default values"
    fi
else
    echo -e "  ${YELLOW}ℹ${NC} ${ENV_TEST_FILE} already exists, skipping"
fi

# Check for encryption key
if [[ -z "${CHARON_ENCRYPTION_KEY:-}" ]]; then
    if ! grep -q "CHARON_ENCRYPTION_KEY" "${ENV_TEST_FILE}" 2>/dev/null; then
        # Generate a random encryption key for testing
        RANDOM_KEY=$(openssl rand -base64 32 2>/dev/null || head -c 32 /dev/urandom | base64)
        echo "CHARON_ENCRYPTION_KEY=${RANDOM_KEY}" >> "${ENV_TEST_FILE}"
        echo -e "  ${GREEN}✓${NC} Generated test encryption key"
    fi
fi

echo ""

# Step 5: Start Docker test environment
echo -e "${BLUE}🐳 Step 5: Starting Docker test environment...${NC}"

# Stop any existing containers first
if docker compose -f "${COMPOSE_FILE}" ps -q 2>/dev/null | grep -q .; then
    echo "  Stopping existing containers..."
    docker compose -f "${COMPOSE_FILE}" down --volumes --remove-orphans 2>/dev/null || true
fi

# Build and start
echo "  Building and starting containers..."
if [[ -f "${ENV_TEST_FILE}" ]]; then
    # shellcheck source=/dev/null
    set -a
    source "${ENV_TEST_FILE}"
    set +a
fi

docker compose -f "${COMPOSE_FILE}" up -d --build

echo -e "${GREEN}✅ Docker containers started${NC}"
echo ""

# Step 6: Wait for health check
wait_for_health "${HEALTH_URL}" "${HEALTH_TIMEOUT}"
echo ""

# Step 7: Success message
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✅ E2E test environment is ready!${NC}"
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${BLUE}📍 Application:${NC}     http://localhost:8080"
echo -e "  ${BLUE}📍 Health Check:${NC}    http://localhost:8080/api/v1/health"
echo ""
echo -e "  ${BLUE}🧪 Run tests:${NC}"
echo "     npm run test:e2e                    # All tests"
echo "     cd /projects/Charon npx playwright test --project=firefox   # Firefox only"
echo "     npx playwright test --ui            # Interactive UI mode"
echo ""
echo -e "  ${BLUE}🛑 Stop environment:${NC}"
echo "     docker compose -f ${COMPOSE_FILE} down"
echo ""
echo -e "  ${BLUE}📋 View logs:${NC}"
echo "     docker compose -f ${COMPOSE_FILE} logs -f"
echo ""
