#!/bin/bash

# Advanced build script to handle Next.js ENOENT errors
# This script monitors the build process and creates missing files as needed

echo "🔧 Starting advanced build process..."

# Function to create missing file structure
create_missing_files() {
    local export_dir=".next/export"
    local server_dir=".next/server/pages"
    
    if [ -d "$export_dir" ]; then
        echo "📁 Export directory found, creating missing files..."
        
        # Create 500.html if it doesn't exist
        if [ ! -f "$export_dir/500.html" ]; then
            echo "Creating $export_dir/500.html"
            cat > "$export_dir/500.html" << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>500 - Server Error</title>
    <meta charset="utf-8">
</head>
<body>
    <h1>500 - Internal Server Error</h1>
    <p>Something went wrong on our end.</p>
</body>
</html>
EOF
        fi
        
        # Create 404.html if it doesn't exist
        if [ ! -f "$export_dir/404.html" ]; then
            echo "Creating $export_dir/404.html"
            cat > "$export_dir/404.html" << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>404 - Page Not Found</title>
    <meta charset="utf-8">
</head>
<body>
    <h1>404 - Page Not Found</h1>
    <p>The page you're looking for doesn't exist.</p>
</body>
</html>
EOF
        fi
    fi
    
    # Ensure server directory exists
    mkdir -p "$server_dir"
}

# Clean any existing build
echo "🧹 Cleaning previous build..."
rm -rf .next

# Start the build process in background
echo "🏗️  Starting Next.js build..."
next build &
BUILD_PID=$!

# Monitor for the export directory creation
echo "👀 Monitoring build process..."
while kill -0 $BUILD_PID 2>/dev/null; do
    if [ -d ".next/export" ]; then
        echo "🎯 Export directory detected, creating missing files..."
        create_missing_files
        break
    fi
    sleep 0.5
done

# Wait for build to complete
wait $BUILD_PID
BUILD_EXIT_CODE=$?

# Check if build was successful
if [ $BUILD_EXIT_CODE -eq 0 ]; then
    echo "🎉 Build completed successfully!"
    
    # Final cleanup - ensure all files are in place
    create_missing_files
    
    echo "✅ All files verified and in place!"
else
    echo "❌ Build failed with exit code $BUILD_EXIT_CODE"
    
    # Try to create files one more time in case the error was due to missing files
    echo "🔄 Attempting recovery..."
    create_missing_files
    
    # Try build one more time
    echo "🔄 Retrying build..."
    next build
    RETRY_EXIT_CODE=$?
    
    if [ $RETRY_EXIT_CODE -eq 0 ]; then
        echo "🎉 Retry successful!"
        exit 0
    else
        echo "❌ Retry failed"
        exit $RETRY_EXIT_CODE
    fi
fi
