#!/usr/bin/env bash

# Build and package the Flutter web app for the DEV environment with aggressive optimizations.
# Produces a timestamped folder + zip in the project root, with precompressed assets.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
OUT_DIR="web_dev_export_${TIMESTAMP}"
ZIP_FILE="${OUT_DIR}.zip"

cd "${PROJECT_ROOT}"

set_env_dev() {
  echo "🔧 Switching to DEVELOPMENT environment..."
  local src="assets/config/env_dev.json"
  if [ ! -f "${src}" ]; then
    echo "❌ ${src} not found" >&2
    exit 1
  fi
  cp "${src}" assets/config/env.json
  echo "📋 Current config:"
  cat assets/config/env.json
}

copy_x_app_sdk() {
  local src="node_modules/x-app-sdk/dist/index.es.js"
  local dest="build/web/js/x_app_sdk_bundle.js"
  if [ ! -f "${src}" ]; then
    echo "❌ x-app-sdk bundle not found at ${src}" >&2
    exit 1
  fi
  mkdir -p "$(dirname "${dest}")"
  cp "${src}" "${dest}"
  echo "✅ Copied x-app-sdk bundle."
}

compress_assets() {
  local dir="$1"
  if command -v gzip >/dev/null 2>&1; then
    find "${dir}" -type f \( -name '*.js' -o -name '*.css' -o -name '*.json' -o -name '*.wasm' -o -name '*.svg' -o -name '*.html' \) -exec gzip -9 -kf {} \;
  else
    echo "⚠️ gzip not available, skipping .gz artifacts"
  fi
  if command -v brotli >/dev/null 2>&1; then
    find "${dir}" -type f \( -name '*.js' -o -name '*.css' -o -name '*.json' -o -name '*.wasm' -o -name '*.svg' -o -name '*.html' \) -exec brotli -f -k -q 11 {} \;
  else
    echo "⚠️ brotli not available, skipping .br artifacts"
  fi
}

echo "🚀 Building DEV export (optimized)..."
set_env_dev

echo "🧹 Cleaning previous artifacts..."
flutter clean || true
rm -rf .dart_tool build || true

echo "📦 Getting Flutter packages..."
flutter pub get

echo "🔨 Flutter build web (release, CanvasKit, no source maps)..."
flutter build web \
  --release \
  --no-source-maps \
  --pwa-strategy=none \
  --dart-define=FLUTTER_WEB_USE_SKIA=true \
  --dart-define=FLUTTER_WEB_USE_SKWASM=false \
  --no-wasm-dry-run

copy_x_app_sdk

echo "📁 Preparing export directory: ${OUT_DIR}"
mkdir -p "${OUT_DIR}"
cp -r build/web/* "${OUT_DIR}/"

if [ -f "web/firebase-messaging-sw.js" ] && [ ! -f "${OUT_DIR}/firebase-messaging-sw.js" ]; then
  cp web/firebase-messaging-sw.js "${OUT_DIR}/"
fi

# Helper script for local preview with SPA fallback
cat > "${OUT_DIR}/serve_local.sh" <<'EOF'
#!/usr/bin/env bash

PORT="${1:-8080}"

python3 - "$PORT" <<'PY'
import http.server
import socketserver
import os
import sys

ROOT = os.getcwd()
PORT = int(sys.argv[1])

class SPAHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        resolved = self.translate_path(self.path)
        if not os.path.exists(resolved):
            self.path = '/index.html'
        return super().do_GET()

    def log_message(self, fmt, *args):
        print(f"🌐 {fmt % args}")

with socketserver.TCPServer(('', PORT), SPAHandler) as httpd:
    print(f"🚀 Serving {ROOT} at http://localhost:{PORT}")
    print("💡 SPA fallback enabled. Ctrl+C to stop.")
    httpd.serve_forever()
PY
EOF
chmod +x "${OUT_DIR}/serve_local.sh"

if [ "${KEEP_CANVASKIT:-0}" != "1" ]; then
  echo "🧹 Removing CanvasKit bundle to shrink export (set KEEP_CANVASKIT=1 to keep)..."
  rm -rf "${OUT_DIR}/canvaskit"
else
  echo "ℹ️ KEEP_CANVASKIT=1 → giữ nguyên thư mục canvaskit."
fi

echo "🗜️ Precompressing assets..."
compress_assets "${OUT_DIR}"

echo "📦 Creating zip archive ${ZIP_FILE}..."
zip -rq "${ZIP_FILE}" "${OUT_DIR}"

echo ""
echo "🎉 DEV export ready!"
echo "   Folder : ${OUT_DIR}"
echo "   Zip    : ${ZIP_FILE}"
echo ""
echo "📌 Upload suggestion: serve files with Content-Encoding gzip/brotli where available."
echo ""
echo "▶️ Quick preview command:"
echo "   cd ${OUT_DIR} && ./serve_local.sh 8080"
echo "⚠️  Avoid using 'python3 -m http.server' directly; it does not handle SPA routes and will 404 on deep links."
