#!/usr/bin/env bash
# list.sh — Lista todas las automatizaciones del catálogo crons/ con nombre, tipo y descripción.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CRONS_DIR="$REPO_ROOT/crons"

if [[ ! -d "$CRONS_DIR" ]]; then
  echo "No se encontró el directorio crons/." >&2
  exit 1
fi

# Collect entries: name, kind, default_cron, description
entries=()
while IFS= read -r -d '' schedule_file; do
  name=""
  description=""
  kind=""
  cron_expr=""

  while IFS= read -r line; do
    case "$line" in
      name:*)        name="${line#name:}";        name="${name// /}" ;;
      description:*) description="${line#description:}"; description="${description# }"; description="${description#\"}"; description="${description%\"}" ;;
      "  kind:"*)    kind="${line#*kind:}";       kind="${kind// /}" ;;
      default_cron:*) cron_expr="${line#default_cron:}"; cron_expr="${cron_expr# }"; cron_expr="${cron_expr//\"/}" ;;
    esac
  done < "$schedule_file"

  if [[ -n "$name" ]]; then
    entries+=("$name|$kind|$cron_expr|$description")
  fi
done < <(find "$CRONS_DIR" -name "schedule.yaml" -print0 | sort -z)

if [[ ${#entries[@]} -eq 0 ]]; then
  echo "No hay automatizaciones en crons/."
  exit 0
fi

# Print header
printf "%-22s %-15s %-15s %s\n" "NOMBRE" "TIPO" "CRON" "DESCRIPCIÓN"
printf "%-22s %-15s %-15s %s\n" "------" "----" "----" "-----------"

for entry in "${entries[@]}"; do
  IFS='|' read -r name kind cron_expr description <<< "$entry"
  printf "%-22s %-15s %-15s %s\n" "$name" "$kind" "$cron_expr" "$description"
done
