#!/usr/bin/env bash
# Generate docs indices for scripts and tags
# Inputs: docs/COMMANDS_INDEX.md and docs/scripts/*.md
# Outputs:
#   - docs/SCRIPTS_INDEX.md (by category)
#   - docs/tags/* (help-yes, dryrun-yes, category-<name>)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
CMD_IDX="$ROOT_DIR/docs/COMMANDS_INDEX.md"
OUT_MAIN="$ROOT_DIR/docs/SCRIPTS_INDEX.md"
TAGS_DIR="$ROOT_DIR/docs/tags"
mkdir -p "$TAGS_DIR"

if [ ! -f "$CMD_IDX" ]; then
  echo "Missing $CMD_IDX; run generate-commands-index.sh first" >&2
  exit 1
fi

# Read table rows (skip header lines starting with '|--------')
mapfile -t ROWS < <(grep '^|' "$CMD_IDX" | grep -v '^|\-' | grep -v '^| Script |')

# Initialize structures
declare -A by_category
declare -A tag_help
declare -A tag_dry

for row in "${ROWS[@]}"; do
  # Split columns: | Script | Category | Path | Help | Dry-run | Purpose |
  # Use awk to safely split by | and trim
  cols=$(echo "$row" | awk -F'\|' '{for(i=2;i<=NF-1;i++){gsub(/^ +| +$/,"",$i); printf("%s\t", $i)} print ""}')
  script=$(echo "$cols" | awk -F'\t' '{print $1}')
  category=$(echo "$cols" | awk -F'\t' '{print $2}')
  path=$(echo "$cols" | awk -F'\t' '{print $3}')
  help=$(echo "$cols" | awk -F'\t' '{print $4}')
  dry=$(echo "$cols" | awk -F'\t' '{print $5}')
  purpose=$(echo "$cols" | awk -F'\t' '{print $6}')

  key="$category"
  by_category["$key"]+="| $script | \`$path\` | $help | $dry | $purpose |\n"

  if [ "$help" = "Yes" ]; then
    tag_help["help-yes"]+="| $script | $category | \`$path\` | $purpose |\n"
  fi
  if [ "$dry" = "Yes" ]; then
    tag_dry["dryrun-yes"]+="| $script | $category | \`$path\` | $purpose |\n"
  fi
done

# Write main index
{
  echo "# Scripts Index"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  for cat in $(printf '%s\n' "${!by_category[@]}" | sort); do
    echo "## $cat"
    echo
    echo "| Script | Path | Help | Dry-run | Purpose |"
    echo "|--------|------|------|---------|---------|"
    printf "%b" "${by_category[$cat]}"
    echo
  done
} > "$OUT_MAIN"

# Write tag pages
write_tag_page(){
  local tagname="$1"; shift
  local content="$1"
  local out="$TAGS_DIR/${tagname}.md"
  {
    echo "# Tag: $tagname"
    echo
    echo "Generated: $(date -Iseconds)"
    echo
    echo "| Script | Category | Path | Purpose |"
    echo "|--------|----------|------|---------|"
    printf "%b" "$content"
  } > "$out"
}

if [ -n "${tag_help[help-yes]:-}" ]; then
  write_tag_page "help-yes" "${tag_help[help-yes]}"
fi
if [ -n "${tag_dry[dryrun-yes]:-}" ]; then
  write_tag_page "dryrun-yes" "${tag_dry[dryrun-yes]}"
fi

echo "Wrote $OUT_MAIN and tags in $TAGS_DIR"
