#!/usr/bin/env bash
# 人設 8D Node worker（Playwright 公開爬蟲）
# 設定一律讀 deploy/.env.dev
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$ROOT/deploy/.env.dev"
WORKER_DIR="$ROOT/backend/worker"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "找不到 $ENV_FILE，請先：cp deploy/.env.dev.example deploy/.env.dev" >&2
  exit 1
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

: "${HAIXUN_BACKEND_URL:=http://127.0.0.1:8890}"
: "${HAIXUN_WORKER_SECRET:?請在 deploy/.env.dev 設定 HAIXUN_WORKER_SECRET}"
: "${HAIXUN_NODE_WORKER_ID:=local-style-8d}"
: "${HAIXUN_WORKER_POLL_MS:=3000}"
: "${HAIXUN_8D_TARGET_SAMPLES:=4}"
: "${PLAYWRIGHT_HEADLESS:=true}"

export HAIXUN_BACKEND_URL HAIXUN_WORKER_SECRET HAIXUN_NODE_WORKER_ID
export HAIXUN_WORKER_POLL_MS HAIXUN_8D_TARGET_SAMPLES PLAYWRIGHT_HEADLESS

echo "[start-node-worker] backend=$HAIXUN_BACKEND_URL worker_id=$HAIXUN_NODE_WORKER_ID"

if ! curl -sf "${HAIXUN_BACKEND_URL}/api/v1/health" >/dev/null; then
  echo "[start-node-worker] API 連不上，請先啟動 gateway（並 source deploy/.env.dev）" >&2
  exit 1
fi

cd "$WORKER_DIR"

ensure_worker_deps() {
  local need_install=false

  if [[ ! -d node_modules ]]; then
    need_install=true
  elif ! node -e "require('esbuild').transformSync('1',{loader:'js'})" >/dev/null 2>&1; then
    echo "[start-node-worker] node_modules 平台不符（常見於 macOS → Linux 複製），重新安裝…"
    rm -rf node_modules
    need_install=true
  fi

  if $need_install; then
    echo "[start-node-worker] npm install…"
    npm install
  fi
}

ensure_worker_deps

echo "[start-node-worker] 確認 Playwright Chromium（已安裝會略過）…"
npx playwright install chromium

verify_playwright_chromium() {
  if node --input-type=module -e "
    import { chromium } from 'playwright';
    const browser = await chromium.launch({ headless: true });
    await browser.close();
  " >/dev/null 2>&1; then
    return 0
  fi

  echo "[start-node-worker] Chromium 無法啟動（Linux 常見：缺少 libatk 等系統函式庫）" >&2
  echo "[start-node-worker] 請在本機執行：cd $WORKER_DIR && sudo npx playwright install-deps chromium" >&2
  return 1
}

echo "[start-node-worker] 驗證 Chromium 可啟動…"
verify_playwright_chromium

exec npm run style-8d