#!/usr/bin/env bash

# Run Flutter web (dev environment) with CORS-friendly local server.
# Builds the app using CanvasKit renderer and serves it from build/web on :8080.

set -euo pipefail

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

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() {
  local env="$1"
  case "${env}" in
    dev)
      echo "🔧 Switching to DEVELOPMENT environment..."
      local src="${PROJECT_ROOT}/assets/config/env_dev.json"
      local dest="${PROJECT_ROOT}/assets/config/env.json"
      if [ ! -f "${src}" ]; then
        echo "❌ ${src} not found" >&2
        exit 1
      fi
      cp "${src}" "${dest}"
      ;;
    prod)
      echo "🚀 Switching to PRODUCTION environment..."
      cat > 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 "❌ Invalid environment: ${env}" >&2
      exit 1
      ;;
  esac
  echo "📋 Current config:"
  cat assets/config/env.json
  echo ""
}

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 (release, CanvasKit)..."
  flutter build web \
    --release \
    --pwa-strategy=none \
    --dart-define=FLUTTER_WEB_USE_SKIA=true \
    --dart-define=FLUTTER_WEB_USE_SKWASM=false \
    --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 CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    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), CORSRequestHandler) as httpd:
    print(f"🚀 Dev server running at http://localhost:{PORT}")
    print(f"📁 Serving from: {os.getcwd()}")
    print("🔧 CORS headers enabled (browser launched with web security disabled).")
    print("✅ Press Ctrl+C to stop.")
    httpd.serve_forever()
PY
  SERVER_PID=$!
}

open_browser() {
  local url="http://localhost:${PORT}"
  echo "🌐 Opening Chrome with CORS disabled at ${url}..."
  if command -v open >/dev/null 2>&1; then
    open -n -a "Google Chrome" --args --disable-web-security --user-data-dir="${BROWSER_PROFILE}" --disable-features=VizDisplayCompositor "${url}"
  elif command -v google-chrome >/dev/null 2>&1; then
    google-chrome --disable-web-security --user-data-dir="${BROWSER_PROFILE}" --disable-features=VizDisplayCompositor "${url}" &
  else
    echo "⚠️ Chrome not found. 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 Development..."
kill_port "${PORT}"
set_env dev
build_web
copy_x_app_sdk
start_server
trap cleanup EXIT INT TERM
sleep 2
open_browser
wait "${SERVER_PID}"
