#!/bin/bash

echo "⚡ Quick Asset Optimization Test"
echo "==============================="
echo "🧪 Testing Laravel Mix asset optimization in running container..."

# Check before sizes
echo ""
echo "📊 BEFORE Optimization:"
echo "======================="

# Function to get file size in MB
get_file_size_mb() {
    if [ -f "$1" ]; then
        size=$(docker-compose exec app stat --format="%s" "$1" 2>/dev/null | tr -d '\r\n')
        if [ "$size" -gt 0 ] 2>/dev/null; then
            echo "scale=2; $size/1024/1024" | bc 2>/dev/null
        else
            echo "0"
        fi
    else
        echo "NOT_FOUND"
    fi
}

vendor_before=$(get_file_size_mb "public/js/vendor.js")
app_before=$(get_file_size_mb "public/js/app.js")

echo "📄 vendor.js: ${vendor_before}MB"
echo "📄 app.js: ${app_before}MB"

# Run optimization
echo ""
echo "🔨 Running Laravel Mix optimization..."
echo "===================================="

# Check if Laravel Mix is available
echo "📦 Checking Laravel Mix setup..."
docker-compose exec app bash -c "cd /var/www/html && npm install --no-audit --no-fund" > /dev/null 2>&1

echo "🧹 Cleaning previous builds..."
docker-compose exec app bash -c "cd /var/www/html && rm -f public/js/vendor.js public/js/app.js public/css/main.css public/css/all.css"

echo "🔨 Building with NODE_ENV=production..."
docker-compose exec app bash -c "cd /var/www/html && NODE_ENV=production npm run production"

echo "🗜️ Creating gzip versions..."
docker-compose exec app bash -c "cd /var/www/html && find public/js public/css -name '*.js' -o -name '*.css' | while read file; do gzip -k -9 \"\$file\" 2>/dev/null || true; done"

echo "✅ Optimization complete!"

# Check after sizes
echo ""
echo "📊 AFTER Optimization:"
echo "======================"

vendor_after=$(get_file_size_mb "public/js/vendor.js")
app_after=$(get_file_size_mb "public/js/app.js")

echo "📄 vendor.js: ${vendor_after}MB"
echo "📄 app.js: ${app_after}MB"

# Calculate reduction
echo ""
echo "💰 Optimization Results:"
echo "======================="

calculate_reduction() {
    local before=$1
    local after=$2
    
    if [ "$before" != "NOT_FOUND" ] && [ "$after" != "NOT_FOUND" ] && [ "$before" != "0" ] && [ "$after" != "0" ]; then
        reduction=$(echo "scale=1; ($before - $after) / $before * 100" | bc 2>/dev/null)
        savings=$(echo "scale=2; $before - $after" | bc 2>/dev/null)
        echo "${before}MB → ${after}MB (${reduction}% reduction, ${savings}MB saved)"
    else
        echo "Unable to calculate reduction"
    fi
}

echo "📄 vendor.js: $(calculate_reduction $vendor_before $vendor_after)"
echo "📄 app.js: $(calculate_reduction $app_before $app_after)"

# Check if files are minified
echo ""
echo "🔍 Minification Check:"
echo "===================="

if docker-compose exec app test -f "public/js/vendor.js" > /dev/null 2>&1; then
    # Check if file contains typical minified indicators
    minified_check=$(docker-compose exec app bash -c "head -c 200 public/js/vendor.js | grep -o '[a-zA-Z]' | wc -l" 2>/dev/null | tr -d '\r\n')
    if [ "$minified_check" -lt 100 ] 2>/dev/null; then
        echo "✅ vendor.js appears to be minified"
    else
        echo "⚠️ vendor.js may not be fully minified"
    fi
else
    echo "❌ vendor.js not found"
fi

# Check gzip files
echo ""
echo "🗜️ Compression Check:"
echo "==================="

if docker-compose exec app test -f "public/js/vendor.js.gz" > /dev/null 2>&1; then
    gz_size=$(get_file_size_mb "public/js/vendor.js.gz")
    echo "✅ vendor.js.gz: ${gz_size}MB"
else
    echo "⚠️ Gzip files not found"
fi

# Final assessment
echo ""
echo "🎯 FINAL ASSESSMENT:"
echo "==================="

total_before=$(echo "$vendor_before + $app_before" | bc 2>/dev/null)
total_after=$(echo "$vendor_after + $app_after" | bc 2>/dev/null)

if [ "$vendor_after" != "NOT_FOUND" ] && [ "$app_after" != "NOT_FOUND" ]; then
    if (( $(echo "$total_after < $total_before" | bc -l) )); then
        echo "🎉 SUCCESS! Asset optimization is working!"
        echo "   ✅ Assets are properly minified"
        echo "   ✅ File sizes are optimized"
        echo "   ✅ Ready for production deployment"
        echo ""
        echo "   Test your dashboard: http://localhost:8000/dashboard"
        echo "   Should load much faster now!"
    else
        echo "⚠️ Optimization may not be working optimally"
        echo "   Check Laravel Mix configuration"
    fi
else
    echo "❌ Build failed - asset files not created"
    echo "   Check Laravel Mix logs above for errors"
fi

echo ""
echo "🔗 Quick Commands:"
echo "=================="
echo "   View build logs: docker-compose logs app"
echo "   Rebuild containers: docker-compose up --build"
echo "   Manual Mix test: docker-compose exec app bash -c 'NODE_ENV=production npm run production'" 