#!/usr/bin/env bash
# Generate a command registry index at docs/COMMANDS_INDEX.md
# Scans scripts/ for *.sh and extracts: name, path, category, purpose, help support, dry-run support

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
OUT="$ROOT_DIR/docs/COMMANDS_INDEX.md"
mkdir -p "$ROOT_DIR/docs"

mapfile -t FILES < <(cd "$ROOT_DIR" && find scripts -type f -name '*.sh' | sort)

echo "# Commands Index" > "$OUT"
echo "" >> "$OUT"
echo "Generated: $(date -Iseconds)" >> "$OUT"
echo "" >> "$OUT"
echo "| Script | Category | Path | Help | Dry-run | Purpose |" >> "$OUT"
echo "|--------|----------|------|------|---------|---------|" >> "$OUT"

for f in "${FILES[@]}"; do
  rel="${f#$ROOT_DIR/}"
  name="$(basename "$f")"
  category="$(echo "$rel" | cut -d/ -f2)"
  # purpose: prefer SCRIPT_DESC, else first comment line
  purpose=""
  if grep -qE '^SCRIPT_DESC="' "$f"; then
    purpose=$(grep -E '^SCRIPT_DESC="' "$f" | head -n1 | sed 's/^SCRIPT_DESC="\(.*\)"$/\1/' | tr '|' ' ')
  else
    # first non-empty comment line, excluding shebang
    purpose=$(grep -E '^#\s*.+$' "$f" | grep -v '^#!' | head -n1 | sed 's/^#\s*//' | tr '|' ' ')
  fi
  purpose=${purpose:-""}
  # help support: handle_help presence or --help in usage/help blocks
  help="No"
  if grep -q 'handle_help' "$f" || grep -q -- '--help' "$f"; then
    help="Yes"
  fi
  # dry-run support: presence of DRY_RUN variable or run()/net_call wrappers
  dry="No"
  if grep -q 'DRY_RUN' "$f" || grep -qE '\brun\s*\(' "$f" || grep -qE '\bnet_call\s*\(' "$f"; then
    dry="Yes"
  fi
  printf "| %s | %s | \`%s\` | %s | %s | %s |\n" "$name" "$category" "$rel" "$help" "$dry" "${purpose}" >> "$OUT"
done

echo "Wrote $OUT"
