#!/usr/bin/env bash
# 啟動 gateway + worker + vite（需 infra 已 up、已 migrate；不碰資料）
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

load_env
require_cmd go
require_cmd npm

if [[ ! -x "$BACKEND_DIR/bin/gateway" || ! -x "$BACKEND_DIR/bin/worker" ]]; then
  log "binary missing — building…"
  "$DEPLOY_DIR/scripts/build.sh"
fi

# 停舊再起（殺 pidfile / cmdline / 佔用埠）
"$DEPLOY_DIR/scripts/stop.sh" || true
load_env

if port_in_use "${GATEWAY_PORT}"; then
  leftovers="$(pids_on_port "${GATEWAY_PORT}" | tr -s ' ')"
  die "gateway 埠 :${GATEWAY_PORT} 仍被佔用 pids=[${leftovers:-?}] — 先 sudo kill -9 或 make -C deploy stop"
fi

# Public web base for mails
export PUBLIC_WEB_BASE="${PUBLIC_WEB_BASE:-http://127.0.0.1:${WEB_PORT}}"

log "start gateway :${GATEWAY_PORT}…"
cd "$BACKEND_DIR"
export PORT="${GATEWAY_PORT}"
# 用絕對路徑寫進 cmdline，方便下次 stop 精準匹配
nohup "$BACKEND_DIR/bin/gateway" -f "$BACKEND_DIR/etc/gateway.yaml" >"$LOG_GATEWAY" 2>&1 &
echo $! >"$PID_GATEWAY"
sleep 1
if ! pid_alive "$(cat "$PID_GATEWAY")"; then
  tail -30 "$LOG_GATEWAY" || true
  die "gateway failed — see $LOG_GATEWAY"
fi

for i in $(seq 1 20); do
  if curl -sf "http://127.0.0.1:${GATEWAY_PORT}/api/v1/ping" >/dev/null 2>&1; then
    log "gateway ping ok"
    break
  fi
  [[ "$i" -eq 20 ]] && { tail -40 "$LOG_GATEWAY"; die "gateway not responding"; }
  sleep 0.3
done

log "start worker…"
cd "$BACKEND_DIR"
export WORKER_ID="${WORKER_ID:-local-worker-1}"
nohup "$BACKEND_DIR/bin/worker" -f "$BACKEND_DIR/etc/gateway.yaml" >"$LOG_WORKER" 2>&1 &
echo $! >"$PID_WORKER"
sleep 0.6
if ! pid_alive "$(cat "$PID_WORKER")"; then
  tail -30 "$LOG_WORKER" || true
  die "worker failed — see $LOG_WORKER"
fi
log "worker ok pid=$(cat "$PID_WORKER") WORKER_ID=$WORKER_ID"

log "start web :${WEB_PORT}…"
cd "$WEB_DIR"
# 先清 web 埠，避免舊 vite 殘留
kill_port "${WEB_PORT}" || true
wait_port_free "${WEB_PORT}" 4 || true
nohup npm run dev -- --host 0.0.0.0 --port "${WEB_PORT}" >"$LOG_WEB" 2>&1 &
echo $! >"$PID_WEB"
sleep 2

if ! curl -sf "http://127.0.0.1:${WEB_PORT}/" >/dev/null 2>&1; then
  log "web still starting… (check $LOG_WEB)"
fi

log "=== running ==="
log "  Web:      http://127.0.0.1:${WEB_PORT}/"
log "  API:      http://127.0.0.1:${GATEWAY_PORT}/api/v1/ping"
log "  Worker:   pid=$(cat "$PID_WORKER") id=$WORKER_ID"
log "  Public:   ${PUBLIC_WEB_BASE:-}"
log "  Assets:   ${HAIXUN_STORAGE_S3_PUBLIC_BASE_URL:-}/…"
log "  Mailpit:  http://127.0.0.1:${MAILPIT_UI_PORT:-8025}"
log "  MinIO:    http://127.0.0.1:${MINIO_CONSOLE_PORT:-9001}"
log "  logs:     $RUN_DIR/"
log "  管理員帳號不由 migration 建立；首次部署請使用 runtime seeder"
