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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
BACKEND_DIR="$ROOT_DIR/haixun-backend"
RUN_DIR="$BACKEND_DIR/.run"
LOG_DIR="$RUN_DIR/logs"
COMPOSE_FILE="$BACKEND_DIR/deploy/docker-compose.yml"
CONFIG_FILE="${HAIXUN_BACKEND_CONFIG:-etc/gateway.yaml}"
BACKEND_URL="${HAIXUN_BACKEND_URL:-http://127.0.0.1:8890}"
WEB_URL="${HAIXUN_WEB_URL:-http://127.0.0.1:5173}"

mkdir -p "$RUN_DIR" "$LOG_DIR"

bash "$BACKEND_DIR/scripts/stop-all.sh"

if ! command -v docker >/dev/null 2>&1; then
  echo "[start-all] docker not found; skip mongo/redis" >&2
else
  echo "[start-all] starting mongo + redis..."
  docker compose -f "$COMPOSE_FILE" up -d
fi

echo "[start-all] starting Go API ($CONFIG_FILE)..."
(
  cd "$BACKEND_DIR"
  go run ./gateway.go -f "$CONFIG_FILE"
) >"$LOG_DIR/api.log" 2>&1 &
echo $! >"$RUN_DIR/api.pid"

echo "[start-all] waiting for API health ($BACKEND_URL)..."
for _ in $(seq 1 40); do
  if curl -fsS "$BACKEND_URL/api/v1/health" >/dev/null 2>&1; then
    break
  fi
  if ! kill -0 "$(cat "$RUN_DIR/api.pid")" 2>/dev/null; then
    echo "[start-all] API exited early; see $LOG_DIR/api.log" >&2
    tail -n 20 "$LOG_DIR/api.log" >&2 || true
    exit 1
  fi
  sleep 1
done
if ! curl -fsS "$BACKEND_URL/api/v1/health" >/dev/null 2>&1; then
  echo "[start-all] API health check timed out; see $LOG_DIR/api.log" >&2
  exit 1
fi

if [[ ! -d "$BACKEND_DIR/web/node_modules" ]]; then
  echo "[start-all] installing web dependencies..."
  (cd "$BACKEND_DIR/web" && npm install)
fi

echo "[start-all] starting web dev server..."
(
  cd "$BACKEND_DIR/web"
  npm run dev
) >"$LOG_DIR/web.log" 2>&1 &
echo $! >"$RUN_DIR/web.pid"

echo "[start-all] starting Node 8D worker..."
(
  cd "$ROOT_DIR"
  npm run worker:style-8d
) >"$LOG_DIR/worker.log" 2>&1 &
echo $! >"$RUN_DIR/worker.pid"

sleep 2

echo ""
echo "[start-all] all services started"
echo "  API:    $BACKEND_URL"
echo "  Web:    $WEB_URL"
echo "  Logs:   $LOG_DIR/{api,web,worker}.log"
echo "  Stop:   make -C haixun-backend stop-all"
echo "  Status: make -C haixun-backend status-all"