#!/bin/bash

# audit-local.sh
# Runs a high-fidelity Lighthouse audit locally using the Docker production stack.

set -e

echo "🚀 Starting High-Fidelity Local Audit..."

# 1. Environment and Infrastructure
export DOCKER_HOST="unix:///Users/marcmintel/.docker/run/docker.sock"
export IMGPROXY_URL="http://klz-imgproxy:8080"
export NEXT_URL="http://klz.localhost"
export NEXT_PUBLIC_CI=true
export CI=true

docker network create infra 2>/dev/null || true
docker volume create klz_db_data 2>/dev/null || true

# 2. Start infra services (DB, CMS, Gatekeeper)
echo "📦 Starting infrastructure services..."
# Using --remove-orphans to ensure a clean state
docker-compose up -d --remove-orphans klz-db klz-gatekeeper

# 3. Build and Start klz-app in Production Mode
echo "🏗️  Building and starting klz-app (Production)..."
# We bypass the dev override by explicitly using the base compose file
NEXT_PUBLIC_BASE_URL=$NEXT_URL \
NEXT_PUBLIC_CI=true \
docker-compose -f docker-compose.yml up -d --build klz-app

# 4. Wait for application to be ready
echo "⏳ Waiting for application to be healthy..."
MAX_RETRIES=30
RETRY_COUNT=0

until $(curl -s -f -o /dev/null "$NEXT_URL/health"); do
    if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
      echo "❌ Error: App did not become healthy in time."
      exit 1
    fi
    echo "   ...waiting for $NEXT_URL/health"
    sleep 2
    RETRY_COUNT=$((RETRY_COUNT+1))
done

echo "✅ App is healthy at $NEXT_URL"

# 5. Run Lighthouse Audit
echo "⚡ Executing Lighthouse CI..."
NEXT_PUBLIC_BASE_URL=$NEXT_URL PAGESPEED_LIMIT=5 pnpm run pagespeed:test "$NEXT_URL"

echo "♿ Executing WCAG Audit..."
NEXT_PUBLIC_BASE_URL=$NEXT_URL PAGESPEED_LIMIT=10 pnpm run check:wcag "$NEXT_URL"

echo "✨ Audit completed! Summary above."
echo "💡 You can stop the production app with: docker-compose stop klz-app"
