#!/usr/bin/env bash
# odb-validation: runtime health checks for opendeviationbar on bigblack
#
# Usage (from your Mac):
#   ssh bigblack 'bash ~/opendeviationbar-py/.claude/skills/odb-validation/scripts/validate.sh'
#
# Usage (locally if Prometheus/ClickHouse are tunneled):
#   bash .claude/skills/odb-validation/scripts/validate.sh
#
# Optional: run only specific checks
#   bash validate.sh aletheia nemesis
#
# Exit codes: 0=all pass, 1=warnings, 2=at least one failure
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHECKS_DIR="$SCRIPT_DIR/checks"

# Colors (disabled if not a terminal)
if [[ -t 1 ]]; then
  RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m'
  CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
else
  RED=''; YELLOW=''; GREEN=''; CYAN=''; BOLD=''; RESET=''
fi

TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC')
echo -e "${BOLD}=== ODB Validation — $TIMESTAMP ===${RESET}"
echo ""

# Determine which checks to run
ALL_CHECKS=(
  aletheia-concurrent-worker-cascade-heal-race-artifact-detector
  tantalus-redis-write-lock-serialization-timeout-contention-auditor
  charybdis-kintsugi-repair-total-duration-and-vision-download-saturation-monitor
  nemesis-kintsugi-repair-throughput-regression-and-near-stall-detector
  mnemosyne-kintsugi-log-stale-shard-dismissal-accumulation-auditor
  clickhouse-mergetree-active-parts-and-merge-queue-pressure-monitor
)
if [[ $# -gt 0 ]]; then
  CHECKS=("$@")
else
  CHECKS=("${ALL_CHECKS[@]}")
fi

overall=0
declare -A results

for check in "${CHECKS[@]}"; do
  script="$CHECKS_DIR/$check.sh"
  if [[ ! -f "$script" ]]; then
    echo -e "${YELLOW}SKIP${RESET}  [$check] — script not found at $script"
    results[$check]="SKIP"
    continue
  fi
  chmod +x "$script"

  # Run check, capture output and exit code
  set +e
  output=$(bash "$script" 2>&1)
  code=$?
  set -e

  case $code in
    0) label="${GREEN}PASS${RESET}"; results[$check]="PASS" ;;
    1) label="${YELLOW}WARN${RESET}"; results[$check]="WARN"; [[ $overall -lt 1 ]] && overall=1 ;;
    2) label="${RED}FAIL${RESET}";   results[$check]="FAIL"; overall=2 ;;
    *) label="${YELLOW}SKIP${RESET}"; results[$check]="SKIP" ;;
  esac

  echo -e "$output"
  echo ""
done

# Summary line
pass=0; warn=0; fail=0; skip=0
for r in "${results[@]}"; do
  case $r in PASS) ((pass++));; WARN) ((warn++));; FAIL) ((fail++));; SKIP) ((skip++));; esac
done

echo -e "${BOLD}Summary: ${GREEN}${pass} PASS${RESET}  ${YELLOW}${warn} WARN${RESET}  ${RED}${fail} FAIL${RESET}  ${skip} SKIP${RESET}"
if [[ $overall -eq 0 ]]; then
  echo -e "Exit: ${GREEN}0 — all checks passed${RESET}"
elif [[ $overall -eq 1 ]]; then
  echo -e "Exit: ${YELLOW}1 — warnings present${RESET}"
else
  echo -e "Exit: ${RED}2 — failures detected${RESET}"
fi
exit $overall
