#!/usr/bin/env bash
# docker_health_check.sh — detect unhealthy Docker containers.
set -euo pipefail

if ! command -v docker >/dev/null 2>&1; then
  echo '{"health":"healthy"}'
  exit 0
fi

UNHEALTHY=$(docker ps --filter "health=unhealthy" --format "{{.Names}}" 2>/dev/null || true)

if [ -n "$UNHEALTHY" ]; then
  COUNT=$(echo "$UNHEALTHY" | wc -l | tr -d ' ')
  NAMES=$(echo "$UNHEALTHY" | tr '\n' ',' | sed 's/,$//')
  echo "{\"health\":\"degraded\",\"signalKind\":\"docker-unhealthy\",\"evidence\":\"$COUNT unhealthy container(s): $NAMES\",\"metrics\":{\"docker_unhealthy\":$COUNT}}"
else
  TOTAL=$(docker ps -q 2>/dev/null | wc -l | tr -d ' ' || echo 0)
  echo "{\"health\":\"healthy\",\"metrics\":{\"docker_unhealthy\":0,\"docker_total\":$TOTAL}}"
fi
