#!/usr/bin/env bash
# dev-all.sh — start gateway + service + frontend together for browser-mode dev.
#
# Reads each subproject's .env.local (or .env if absent) and exports the merged
# set into all three processes. On Ctrl-C, cleanly tears down all child PIDs.
#
# Usage:
#   bash scripts/dev-all.sh
#
# Requires:
#   - .env.local files filled in under gateway/, service/, frontend/
#   - All three `npm install`s already done (run scripts/setup.sh first time)
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${ROOT}"

PIDS=()
cleanup() {
  echo ""
  echo "[dev-all] tearing down…"
  for pid in "${PIDS[@]:-}"; do
    if [[ -n "${pid:-}" ]] && kill -0 "${pid}" 2>/dev/null; then
      kill "${pid}" 2>/dev/null || true
    fi
  done
  wait 2>/dev/null || true
  echo "[dev-all] done"
}
trap cleanup EXIT INT TERM

dotenv_or_skip() {
  # Echo the .env.local path (absolute) if present, .env otherwise.
  # Absolute path is required because callers `cd` into subdirs before sourcing.
  local dir="${ROOT}/$1"
  if [[ -f "${dir}/.env.local" ]]; then
    echo "${dir}/.env.local"
  elif [[ -f "${dir}/.env" ]]; then
    echo "${dir}/.env"
  else
    echo ""
  fi
}

require_env() {
  local label="$1" path="$2"
  if [[ -z "${path}" ]]; then
    echo "[dev-all] ❌ ${label} 缺 .env.local。复制 ${label}/.env.example → ${label}/.env.local 后填值再跑。" >&2
    exit 1
  fi
}

GW_ENV="$(dotenv_or_skip gateway)"
SVC_ENV="$(dotenv_or_skip service)"
FE_ENV="$(dotenv_or_skip frontend)"

require_env gateway "${GW_ENV}"
require_env service "${SVC_ENV}"
require_env frontend "${FE_ENV}"

echo "[dev-all] gateway env = ${GW_ENV}"
echo "[dev-all] service env = ${SVC_ENV}"
echo "[dev-all] frontend env = ${FE_ENV}"

# All three are independent at startup (service doesn't connect to gateway
# until first prompt; frontend connects to service lazily). Launch in parallel.
( cd gateway  && set -a && source "${GW_ENV}"  && set +a && npm run dev ) & PIDS+=($!)
( cd service  && set -a && source "${SVC_ENV}" && set +a && npm run dev ) & PIDS+=($!)
( cd frontend && set -a && source "${FE_ENV}"  && set +a && npm run dev ) & PIDS+=($!)

echo ""
echo "[dev-all] up:"
echo "  gateway   http://localhost:4290"
echo "  service   ws://localhost:4291"
echo "  frontend  http://localhost:4292"
echo "  (Ctrl-C here to stop all)"

# Wait for any child to exit; cleanup trap kills the rest.
wait -n
