#!/usr/bin/env bash

# Script to build, export, update Nginx config, and start/reload Nginx
# One command to rule them all! 🚀

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NGINX_CONF="${HOME}/nginx-gzip.conf"

update_nginx_config() {
  echo "🔧 Step 2: Updating Nginx config..."

  local latest_export
  latest_export=$(ls -td "${PROJECT_ROOT}"/web_dev_export_*/ 2>/dev/null | head -1 || true)

  if [ -z "${latest_export}" ]; then
    echo "❌ No export directory found. Please run ./export_dev.sh first." >&2
    exit 1
  fi

  latest_export="${latest_export%/}"
  echo "📁 Latest export directory: ${latest_export}"

  local mime_types_file=""
  for candidate in \
    "/opt/homebrew/etc/nginx/mime.types" \
    "/usr/local/etc/nginx/mime.types" \
    "/etc/nginx/mime.types"
  do
    if [ -f "${candidate}" ]; then
      mime_types_file="${candidate}"
      break
    fi
  done

  local mime_include_directive
  if [ -n "${mime_types_file}" ]; then
    echo "🗂  Using mime types file: ${mime_types_file}"
    mime_include_directive="    include       ${mime_types_file};"
  else
    echo "⚠️  mime.types not found; falling back to default types."
    mime_include_directive="    # mime.types not found; relying on default types"
  fi

  cat > "${NGINX_CONF}" <<EOF
events {}

http {
${mime_include_directive}
    default_type  application/octet-stream;

    gzip on;
    gzip_static on;
    gzip_types application/javascript text/css application/json application/wasm font/woff2 image/svg+xml;
    gzip_min_length 1024;

    server {
        listen 8080;
        server_name localhost;
        root ${latest_export};
        index index.html;

        location / {
            try_files \$uri \$uri/ /index.html;
        }

        location ~* \.(?:js|css|json|wasm|svg|woff2)$ {
            add_header Cache-Control "public, max-age=31536000, immutable";
            try_files \$uri \$uri/ /index.html;
        }
    }
}
EOF

  echo "✅ Nginx config updated!"
}

echo "🚀 Starting DEV build and Nginx setup..."
echo ""

# Step 1: Build and export
echo "📦 Step 1: Building and exporting..."
# Pass through KEEP_CANVASKIT environment variable if set
if [ -n "${KEEP_CANVASKIT:-}" ]; then
  echo "   ℹ️  KEEP_CANVASKIT=${KEEP_CANVASKIT} will be passed to export_dev.sh"
  KEEP_CANVASKIT="${KEEP_CANVASKIT}" ./export_dev.sh
else
  ./export_dev.sh
fi

echo ""
update_nginx_config

echo ""
echo "🔄 Step 3: Starting/Reloading Nginx..."

# Check if Nginx is already running
if pgrep -f "nginx.*nginx-gzip.conf" > /dev/null; then
  echo "   Nginx is running, reloading..."
  nginx -s reload -c "${NGINX_CONF}" || {
    echo "   ⚠️  Reload failed, restarting..."
    nginx -s stop -c "${NGINX_CONF}" 2>/dev/null || true
    nginx -c "${NGINX_CONF}"
  }
else
  echo "   Starting Nginx..."
  nginx -c "${NGINX_CONF}"
fi

echo ""
echo "✅ Done! 🎉"
echo ""
echo "🌐 Your app is available at: http://localhost:8080"
echo ""
echo "📊 To check if gzip is working:"
echo "   1. Open DevTools (F12) → Network tab"
echo "   2. Reload the page"
echo "   3. Click on main.dart.js"
echo "   4. Check Response Headers for 'Content-Encoding: gzip'"
echo ""
echo "🛑 To stop Nginx:"
echo "   nginx -s stop -c ${NGINX_CONF}"
