#!/usr/bin/env bash
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

load_env 2>/dev/null || log "env not loaded"

echo "=== ports ==="
ss -tlnp 2>/dev/null | grep -E ":(${GATEWAY_PORT:-8888}|${WEB_PORT:-5173}|27017|6379|9000|9001|1025|8025|80)\s" || true

echo "=== pids ==="
[[ -f "$PID_GATEWAY" ]] && echo "gateway pidfile=$(cat "$PID_GATEWAY") alive=$(pid_alive "$(cat "$PID_GATEWAY")" && echo yes || echo no)" || echo "gateway (no pid file)"
[[ -f "$PID_WORKER" ]] && echo "worker  pidfile=$(cat "$PID_WORKER") alive=$(pid_alive "$(cat "$PID_WORKER")" && echo yes || echo no)" || echo "worker  (no pid file)"
[[ -f "$PID_WEB" ]] && echo "web     pidfile=$(cat "$PID_WEB") alive=$(pid_alive "$(cat "$PID_WEB")" && echo yes || echo no)" || echo "web     (no pid file)"

echo "=== health ==="
curl -sS -o /dev/null -w "gateway ping %{http_code}\n" "http://127.0.0.1:${GATEWAY_PORT:-8888}/api/v1/ping" 2>/dev/null || echo "gateway down"
curl -sS -o /dev/null -w "web %{http_code}\n" "http://127.0.0.1:${WEB_PORT:-5173}/" 2>/dev/null || echo "web down"
curl -sS -o /dev/null -w "minio %{http_code}\n" "http://127.0.0.1:${MINIO_API_PORT:-9000}/minio/health/live" 2>/dev/null || echo "minio down"
if [[ -f "$PID_WORKER" ]] && pid_alive "$(cat "$PID_WORKER")"; then
  echo "worker process alive"
else
  echo "worker down"
fi

echo "=== docker (haixun-infra) ==="
docker compose --env-file "$(resolve_env_file 2>/dev/null || echo /dev/null)" \
  -f "$COMPOSE_FILE" ps 2>/dev/null || docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null | head -20 || true
