#!/usr/bin/env bash

# Run Flutter web with production configuration for smoke testing on localhost.
# Builds CanvasKit bundle and serves it from build/web on :8080 (no CORS bypass).

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORT="${PORT:-8080}"

cd "${PROJECT_ROOT}"

kill_port() {
  local port="$1"
  lsof -i ":${port}" | awk 'NR>1 {print $2}' | xargs kill -9 2>/dev/null || true
}

set_env_prod() {
  cat > "${PROJECT_ROOT}/assets/config/env.json" <<'EOF'
{
  "flavor":"pro",
  "baseUrl":"https://api.mypoint.com.vn/8854/gup2start/rest",
  "t3Token":"runner-env-flavor-pro",
  "enableLogging":false
}
EOF
  echo "📋 Current production config written to ${PROJECT_ROOT}/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."
}

build_web() {
  echo "📦 Getting Flutter packages..."
  flutter pub get

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

start_server() {
  python3 - "${PROJECT_ROOT}/build/web" "${PORT}" <<'PY' &
import http.server
import socketserver
import os
import sys

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

class SPAHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        path = self.translate_path(self.path)
        if os.path.isdir(path):
            path = os.path.join(path, 'index.html')
        if not os.path.exists(path):
            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"🚀 Production preview running at http://localhost:{PORT}")
    print(f"📁 Serving from: {os.getcwd()}")
    print("✅ Press Ctrl+C to stop.")
    httpd.serve_forever()
PY
  SERVER_PID=$!
}

open_browser() {
  local url="http://localhost:${PORT}"
  echo "🌐 Opening default browser at ${url}..."
  if command -v open >/dev/null 2>&1; then
    open "${url}"
  elif command -v xdg-open >/dev/null 2>&1; then
    xdg-open "${url}"
  else
    echo "⚠️ Please open ${url} manually."
  fi
}

cleanup() {
  if [[ -n "${SERVER_PID:-}" ]] && ps -p "${SERVER_PID}" >/dev/null 2>&1; then
    kill "${SERVER_PID}" || true
  fi
}

echo "🚀 Running Production preview..."
kill_port "${PORT}"
set_env_prod
build_web
copy_x_app_sdk
start_server
trap cleanup EXIT INT TERM
sleep 2
open_browser
wait "${SERVER_PID}"
