#!/usr/bin/env bash
# deckctl status — aggregate module health and unit states (reports only; exit 0).
set -euo pipefail

cmd_status() {
  local root="$DECKCTL_ROOT"
  local manifest moddir modname kind unit_state health_col svc unit_name hp

  [[ -d "$root/modules" ]] || die "missing modules/ directory at $root"

  printf "%-16s %-10s %-12s %s\n" "MODULE" "KIND" "UNIT" "HEALTH"

  while IFS= read -r manifest; do
    [[ -n "$manifest" ]] || continue
    moddir=$(dirname "$manifest")
    modname=$(basename "$moddir")

    kind=$(jq -r '.kind // "-"' "$manifest")
    unit_state="-"
    health_col="-"

    if jq -e '.services | type == "array" and length > 0' "$manifest" >/dev/null 2>&1; then
      svc=$(jq -r '.services[0]' "$manifest")
      unit_name=$(basename "$svc" .service)
      unit_state=$(systemctl --user show -p ActiveState --value "$unit_name" 2>/dev/null || echo "unknown")
    fi

    if jq -e 'has("health")' "$manifest" >/dev/null 2>&1; then
      hp="$moddir/$(jq -r '.health' "$manifest")"
      if [[ -x "$hp" ]]; then
        set +e
        (cd "$moddir" && ./"$(jq -r '.health' "$manifest")") >/dev/null 2>&1
        health_col=$?
        set -e
      else
        health_col="missing"
      fi
    fi

    printf "%-16s %-10s %-12s %s\n" "$modname" "$kind" "$unit_state" "$health_col"
  done < <(find "$root/modules" -mindepth 2 -maxdepth 2 -name 'deck.module.json' | sort)

  exit 0
}
