#!/bin/bash
# scripts/dev-health-check.sh — Verify mkl-dev instance is actually serving requests
#
# Checks ports 3004 (mkl-dev-core) and 3005 (mkl-dev-products) are listening.
# pm2 can report "online" during crash loops, so port state is ground truth.
# Exits 0 if healthy, 1 if not. Used by Start MKL workflow.

set -u

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}Dev instance health check (dev.techtoschool.com)...${NC}"

# Query remote state in one ssh round-trip. Heredoc keeps quoting clean.
REMOTE_OUT=$(ssh mkl bash -s << 'REMOTE'
ss -tln | grep -qE ':3004 ' && echo "CORE_PORT=1" || echo "CORE_PORT=0"
ss -tln | grep -qE ':3005 ' && echo "PROD_PORT=1" || echo "PROD_PORT=0"
CORE_RESTARTS=$(pm2 jlist 2>/dev/null | node -e '
try {
  const procs = JSON.parse(require("fs").readFileSync(0));
  const p = procs.find(x => x.name === "mkl-dev-core");
  console.log(p ? p.pm2_env.restart_time : "missing");
} catch (e) { console.log("?"); }
')
PROD_RESTARTS=$(pm2 jlist 2>/dev/null | node -e '
try {
  const procs = JSON.parse(require("fs").readFileSync(0));
  const p = procs.find(x => x.name === "mkl-dev-products");
  console.log(p ? p.pm2_env.restart_time : "missing");
} catch (e) { console.log("?"); }
')
echo "CORE_RESTARTS=$CORE_RESTARTS"
echo "PROD_RESTARTS=$PROD_RESTARTS"
REMOTE
)

eval "$REMOTE_OUT"

HEALTHY=true

if [[ "${CORE_PORT:-0}" == "1" ]]; then
    echo -e "  ${GREEN}✓${NC} mkl-dev-core listening on :3004 (${CORE_RESTARTS:-?} restarts)"
else
    echo -e "  ${RED}✗${NC} mkl-dev-core NOT listening on :3004 (restarts: ${CORE_RESTARTS:-?})"
    HEALTHY=false
fi

if [[ "${PROD_PORT:-0}" == "1" ]]; then
    echo -e "  ${GREEN}✓${NC} mkl-dev-products listening on :3005 (${PROD_RESTARTS:-?} restarts)"
else
    echo -e "  ${RED}✗${NC} mkl-dev-products NOT listening on :3005 (restarts: ${PROD_RESTARTS:-?})"
    HEALTHY=false
fi

if [[ "$HEALTHY" == "false" ]]; then
    echo ""
    echo -e "${YELLOW}Last error log entries:${NC}"
    ssh mkl 'pm2 logs mkl-dev-core mkl-dev-products --err --lines 15 --nostream 2>&1 | tail -30' || true
    echo ""
    echo -e "${YELLOW}Diagnose:${NC} ssh mkl \"pm2 logs mkl-dev-products --lines 100 --nostream\""
    echo -e "${YELLOW}Restart: ${NC} ssh mkl \"pm2 restart mkl-dev-products --update-env\""
    echo -e "${YELLOW}Redeploy:${NC} ./scripts/deploy-dev.sh"
    exit 1
fi

echo -e "${GREEN}Dev instance healthy ✓${NC}"
exit 0
