#!/usr/bin/env bash
# Show allocated ports and whether each PM2 app is listening.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=lib/node-env-port.sh
source "$ROOT/scripts/lib/node-env-port.sh"
PORTS_FILE="$ROOT/logs/ports.env"

API_PORT="$(node_env_port "$ROOT" 2>/dev/null || echo "")"
CALENDAR_APACHE_MODE=0
CALENDAR_HOST_PORT=""
CALENDAR_PUBLIC_PORT=""
CALENDAR_EMBED_PORT=""
if [[ -f "$PORTS_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$PORTS_FILE"
fi
# API port always from node/.env (ignore any stale value in ports.env)
if [[ -n "$API_PORT" ]]; then
  CALENDAR_API_PORT="$API_PORT"
fi

port_status() {
  local port=$1
  if command -v lsof >/dev/null 2>&1 && lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then
    echo "listening"
  elif command -v ss >/dev/null 2>&1 && ss -ltn 2>/dev/null | grep -qE ":${port}\b"; then
    echo "listening"
  else
    echo "free"
  fi
}

printf 'Calendar ports (API from node/.env PORT=%s):\n\n' "${CALENDAR_API_PORT:-?}"
printf '  API:             http://localhost:%-5s  [%s]\n' "$CALENDAR_API_PORT" "$(port_status "$CALENDAR_API_PORT")"
if [[ "${CALENDAR_APACHE_MODE:-0}" == "1" ]]; then
  printf '  (Apache mode — static apps served by Apache, not PM2)\n'
else
  printf '  Host dashboard:  http://localhost:%-5s  [%s]\n' "${CALENDAR_HOST_PORT:-—}" "$(port_status "${CALENDAR_HOST_PORT:-0}")"
  printf '  Public booking:  http://localhost:%-5s  [%s]\n' "${CALENDAR_PUBLIC_PORT:-—}" "$(port_status "${CALENDAR_PUBLIC_PORT:-0}")"
  printf '  Embed widget:    http://localhost:%-5s  [%s]\n' "${CALENDAR_EMBED_PORT:-—}" "$(port_status "${CALENDAR_EMBED_PORT:-0}")"
fi

if command -v pm2 >/dev/null 2>&1; then
  printf '\nPM2 calendar processes:\n'
  if pm2 jlist >/dev/null 2>&1; then
    pm2 jlist 2>/dev/null | node -e "
      let raw = '';
      process.stdin.on('data', (c) => { raw += c; });
      process.stdin.on('end', () => {
        try {
          const apps = JSON.parse(raw).filter((a) => a.name?.startsWith('calendar-'));
          if (!apps.length) { console.log('  (none running)'); return; }
          for (const a of apps) console.log('  ' + a.name + ': ' + (a.pm2_env?.status ?? 'unknown'));
        } catch { console.log('  (could not parse pm2 list)'); }
      });
    " || true
  else
    pm2 status 2>/dev/null | grep calendar || echo '  (none running)'
  fi
fi

printf '\nApache: Define CALENDAR_API http://127.0.0.1:%s (configure-apache.sh)\n' "${CALENDAR_API_PORT:-?}"
