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

BACKEND_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUN_DIR="$BACKEND_DIR/.run"
COMPOSE_FILE="$BACKEND_DIR/deploy/docker-compose.yml"
BACKEND_URL="${HAIXUN_BACKEND_URL:-http://127.0.0.1:8890}"
WEB_URL="${HAIXUN_WEB_URL:-http://127.0.0.1:5173}"

check_pid() {
  local name="$1"
  local file="$RUN_DIR/${name}.pid"
  if [[ -f "$file" ]]; then
    local pid
    pid="$(cat "$file" 2>/dev/null || true)"
    if [[ -n "${pid:-}" ]] && kill -0 "$pid" 2>/dev/null; then
      echo "  $name: running (pid=$pid)"
      return 0
    fi
  fi
  echo "  $name: stopped"
  return 1
}

echo "Haixun dev services"
echo ""

if command -v docker >/dev/null 2>&1 && [[ -f "$COMPOSE_FILE" ]]; then
  echo "Docker:"
  docker compose -f "$COMPOSE_FILE" ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || echo "  (docker compose not running)"
  echo ""
fi

echo "Processes:"
check_pid api || true
check_pid web || true
check_pid worker || true
echo ""

echo "Health:"
if curl -fsS "$BACKEND_URL/api/v1/health" >/dev/null 2>&1; then
  echo "  API health: OK ($BACKEND_URL)"
else
  echo "  API health: down ($BACKEND_URL)"
fi
if curl -fsS "$WEB_URL" >/dev/null 2>&1; then
  echo "  Web:        OK ($WEB_URL)"
else
  echo "  Web:        down ($WEB_URL)"
fi