#!/bin/bash

# Production Build Script for SIF-GT
echo "🚀 Starting production build for SIF-GT..."

# Load environment variables from .env.production if it exists
if [ -f ".env.production" ]; then
    echo "📋 Loading production environment variables..."
    export $(cat .env.production | grep -v '^#' | xargs)
fi

# Set production environment variables
export NODE_ENV=production
export GENERATE_SOURCEMAP=false
export INLINE_RUNTIME_CHUNK=false
export IMAGE_INLINE_SIZE_LIMIT=0
export BUILD_PATH=build
export PUBLIC_URL=${PUBLIC_URL:-/}

# Performance optimizations
export DISABLE_ESLINT_PLUGIN=true
export TSC_COMPILE_ON_ERROR=true
export FAST_REFRESH=false

# Bundle optimization
export REACT_APP_ENABLE_BUNDLE_ANALYZER=${ANALYZE:-false}

# Clean previous builds
echo "🧹 Cleaning previous builds..."
rm -rf build/
rm -rf node_modules/.cache/

# Install dependencies if needed
if [ ! -d "node_modules" ]; then
    echo "📦 Installing dependencies..."
    npm ci --production=false
fi

# Replace build date placeholder
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
sed -i.bak "s/__BUILD_DATE__/$BUILD_DATE/g" .env.production

# Run production build
echo "🔨 Building application..."
npm run build:prod

# Restore original .env.production
mv .env.production.bak .env.production

# Optimize build
echo "🎯 Optimizing build..."

# Remove source maps if they exist
find build/ -name "*.map" -delete

# Generate critical resource preload hints
echo "⚡ Generating critical resource preload hints..."
node scripts/preload-critical.js

# Create gzipped versions of static files
if command -v gzip &> /dev/null; then
    echo "📦 Creating gzipped versions..."
    find build/static -name "*.js" -exec sh -c 'gzip -9 -c "$1" > "$1.gz"' _ {} \;
    find build/static -name "*.css" -exec sh -c 'gzip -9 -c "$1" > "$1.gz"' _ {} \;
fi

# Create Brotli compressed versions if available
if command -v brotli &> /dev/null; then
    echo "📦 Creating Brotli compressed versions..."
    find build/static -name "*.js" -exec brotli -q 11 -o {}.br {} \;
    find build/static -name "*.css" -exec brotli -q 11 -o {}.br {} \;
fi

# Display build size
echo "📊 Build size analysis:"
du -sh build/
echo ""
echo "📁 Static files breakdown:"
du -sh build/static/css/ 2>/dev/null || echo "CSS: No files"
du -sh build/static/js/ 2>/dev/null || echo "JS: No files"
du -sh build/static/media/ 2>/dev/null || echo "Media: No files"

# Performance analysis
echo ""
echo "🎯 Performance optimizations applied:"
echo "✅ Tree shaking enabled"
echo "✅ Code splitting configured"
echo "✅ Bundle analyzer available (run with ANALYZE=true)"
echo "✅ Gzip compression configured in .htaccess"
echo "✅ Cache headers optimized"
echo "✅ Source maps disabled for production"
echo "✅ Console logs removed in production"

# Cache optimization
echo ""
echo "🗄️ Setting up cache optimization..."
php scripts/cache-cleanup.php 2>/dev/null || echo "Cache cleanup script ready for cron"

echo "✅ Production build completed successfully!"
echo "📂 Build files are in the 'build' directory"
echo ""
echo "🚀 To deploy:"
echo "1. Copy contents of 'build' directory to your web server"
echo "2. Copy API files (api/, uploads/, logs/, etc.)"
echo "3. Copy .htaccess file"
echo "4. Run install.php if first deployment"