#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
BACKEND_DIR="$ROOT_DIR/haixun-backend"
CONFIG_FILE="${HAIXUN_BACKEND_CONFIG:-etc/gateway.yaml}"
BACKEND_URL="${HAIXUN_BACKEND_URL:-http://127.0.0.1:8890}"

pids=()
owned_pids=()

cleanup() {
  local code=$?
  if ((${#owned_pids[@]} > 0)); then
    echo ""
    echo "[dev-8d] stopping backend and worker..."
    kill "${owned_pids[@]}" 2>/dev/null || true
    wait "${owned_pids[@]}" 2>/dev/null || true
  fi
  exit "$code"
}

trap cleanup EXIT INT TERM

if curl -fsS "$BACKEND_URL/api/v1/health" >/dev/null 2>&1; then
  echo "[dev-8d] backend already running: $BACKEND_URL"
else
  echo "[dev-8d] starting Go backend: $CONFIG_FILE"
  (
    cd "$BACKEND_DIR"
    go run ./gateway.go -f "$CONFIG_FILE"
  ) &
  pids+=("$!")
  owned_pids+=("$!")

  echo "[dev-8d] waiting for backend health..."
  for _ in $(seq 1 30); do
    if curl -fsS "$BACKEND_URL/api/v1/health" >/dev/null 2>&1; then
      break
    fi
    if ! kill -0 "${pids[0]}" 2>/dev/null; then
      wait "${pids[0]}"
    fi
    sleep 1
  done

  if ! curl -fsS "$BACKEND_URL/api/v1/health" >/dev/null 2>&1; then
    echo "[dev-8d] backend health check timed out: $BACKEND_URL" >&2
    exit 1
  fi
fi

echo "[dev-8d] starting Node 8D worker"
(
  cd "$ROOT_DIR"
  npm run worker:style-8d
) &
pids+=("$!")
owned_pids+=("$!")

echo "[dev-8d] running pids=${pids[*]}"
echo "[dev-8d] press Ctrl+C to stop both"

while true; do
  for pid in "${owned_pids[@]}"; do
    if ! kill -0 "$pid" 2>/dev/null; then
      wait "$pid"
      exit $?
    fi
  done
  sleep 1
done
