#!/bin/bash

# Performance Baseline Audit Script
# Runs comprehensive performance testing and generates report

set -e

echo "🚀 Starting Performance Baseline Audit..."
echo "=========================================="
echo ""

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

# Step 1: Build the application
echo "📦 Step 1: Building application..."
npm run build
echo ""

# Step 2: Start the server
echo "🌐 Step 2: Starting production server..."
npm run start &
SERVER_PID=$!

# Wait for server to be ready
echo "⏳ Waiting for server to start..."
sleep 10

# Check if server is running
if curl -s http://localhost:9000/en > /dev/null; then
    echo -e "${GREEN}✅ Server is ready${NC}"
else
    echo -e "${RED}❌ Server failed to start${NC}"
    kill $SERVER_PID 2>/dev/null || true
    exit 1
fi

echo ""

# Step 3: Run Lighthouse CI
echo "🔍 Step 3: Running Lighthouse CI audit..."
npm run perf:lighthouse || echo -e "${YELLOW}⚠️  Lighthouse CI completed with warnings${NC}"
echo ""

# Step 4: Run Playwright performance tests
echo "🎭 Step 4: Running Playwright performance tests..."
npm run test:performance || echo -e "${YELLOW}⚠️  Some performance tests may have warnings${NC}"
echo ""

# Step 5: Analyze bundle size
echo "📊 Step 5: Analyzing bundle size..."
echo "Run 'ANALYZE=true npm run build' to open interactive bundle analyzer"
echo ""

# Cleanup
echo "🧹 Cleaning up..."
kill $SERVER_PID 2>/dev/null || true

echo ""
echo "=========================================="
echo -e "${GREEN}✅ Performance baseline audit complete!${NC}"
echo ""
echo "📁 Reports generated:"
echo "   - Lighthouse: .lighthouseci/ directory"
echo "   - Playwright: playwright-report/ directory"
echo ""
echo "📊 Next steps:"
echo "   1. Review Lighthouse report: npm run perf:lighthouse"
echo "   2. View Playwright report: npm run test:e2e:report"
echo "   3. Analyze bundle: ANALYZE=true npm run build"
echo ""
