#!/usr/bin/env bash
# Checks health endpoints for all running Teletraan services.

set -euo pipefail

PASS=0
FAIL=0
RESULTS=()

check_service() {
  local name="$1"
  local port="$2"
  local path="${3:-/health}"
  local url="http://localhost:${port}${path}"

  if curl -sf --max-time 3 "$url" > /dev/null 2>&1; then
    RESULTS+=("  [PASS] ${name} :${port}")
    PASS=$((PASS + 1))
  else
    RESULTS+=("  [FAIL] ${name} :${port}  (${url} unreachable)")
    FAIL=$((FAIL + 1))
  fi
}

check_pm2_service() {
  local name="$1"
  if pm2 list 2>/dev/null | grep -q "│ ${name} "; then
    local status
    status=$(pm2 list 2>/dev/null | grep "│ ${name} " | awk -F'│' '{print $4}' | tr -d ' ')
    if [ "$status" = "online" ]; then
      return 0
    fi
  fi
  return 1
}

echo ""
echo "Teletraan Health Check"
echo "─────────────────────────────────"

# Channel server (always present)
check_service "channel-server" "7100"

# Load manifest to find installed modules
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
MANIFEST="${REPO_ROOT}/config/manifest.json"

if [ -f "$MANIFEST" ]; then
  # Check each installed module's port
  if command -v node &>/dev/null; then
    while IFS= read -r line; do
      name=$(echo "$line" | cut -d: -f1 | tr -d ' "')
      port=$(echo "$line" | cut -d: -f2 | tr -d ' ,')
      if [ -n "$name" ] && [ -n "$port" ] && [[ "$port" =~ ^[0-9]+$ ]]; then
        check_service "$name" "$port"
      fi
    done < <(node -e "
      const m = JSON.parse(require('fs').readFileSync('${MANIFEST}', 'utf8'));
      const modules = m.modules || m;
      for (const [k,v] of Object.entries(modules)) {
        const ports = v.requiredPorts || v.ports || [];
        if (ports.length) console.log(k + ':' + ports[0]);
      }
    " 2>/dev/null || true)
  fi
else
  # Fallback: check known default ports
  check_service "notifications" "8087"
  check_service "calendar" "8084"
  check_service "status" "8086"
fi

echo ""
for r in "${RESULTS[@]}"; do
  echo "$r"
done

echo ""
TOTAL=$((PASS + FAIL))
if [ "$FAIL" -eq 0 ]; then
  echo "Overall: ${PASS}/${TOTAL} services healthy  [OK]"
  exit 0
else
  echo "Overall: ${PASS}/${TOTAL} services healthy  [${FAIL} FAILING]"
  exit 1
fi
