#!/usr/bin/env bash
# Generate scripts inventory and command index (local-only)
# Outputs:
#   - docs/SCRIPTS_INVENTORY.md
#   - docs/COMMANDS_INDEX.md

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd)"
source "/home/intlc/projects/smom-dbis-138/scripts/lib/init.sh"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/init.sh"

QUIET=0
LIMIT=30
while [[ $# -gt 0 ]]; do
  case "$1" in
    --quiet) QUIET=1; shift ;;
    --limit) LIMIT="$2"; shift 2 ;;
    *) echo "Unknown arg: $1"; exit 1 ;;
  esac
done

DOC_INV="$ROOT_DIR/docs/SCRIPTS_INVENTORY.md"
DOC_CMD="$ROOT_DIR/docs/COMMANDS_INDEX.md"

emit() { if [ $QUIET -eq 0 ]; then echo -e "$@"; fi }

ensure_azure_cli || true

# Collect scripts list (exclude lib)
mapfile -t ALL_SCRIPTS < <(cd "$ROOT_DIR" && find scripts -type f -name '*.sh' ! -path '*/lib/*' | sort)

total_count=${#ALL_Scripts[@]:-${#ALL_SCRIPTS[@]}}
emit "Found $total_count shell scripts (excluding scripts/lib)."

# Build per-file metrics
tmp_metrics=$(mktemp)
{
  printf "path\tlines\tsubdir\thas_lib\thas_color_vars\thas_manual_az\tcalls\n"
  for f in "${ALL_SCRIPTS[@]}"; do
    lines=$(wc -l < "$f" | tr -d ' ')
    rel=${f#"$ROOT_DIR/"}
    subdir=$(echo "$rel" | awk -F'/' '{print ($2? $2 : "root")}')
    if grep -qE '^SCRIPT_DIR=.*BASH_SOURCE' "$f" && grep -q 'source\s\+"\$SCRIPT_DIR/\.\./lib/init\.sh"' "$f"; then
      has_lib=1
    else
      has_lib=0
    fi
    if grep -qE '^[[:space:]]*(RED|GREEN|YELLOW|BLUE|CYAN|NC)=' "$f"; then
      color=1
    else
      color=0
    fi
    if grep -qE '(^|[[:space:]])(command -v[[:space:]]+az|az[[:space:]]+account[[:space:]]+(show|set))' "$f"; then
      manaz=1
    else
      manaz=0
    fi
    calls=$(grep -hoE 'scripts/[A-Za-z0-9_./-]+\.sh' "$f" | sort -u | tr '\n' ' ' || true)
    printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" "$rel" "$lines" "$subdir" "$has_lib" "$color" "$manaz" "$calls"
  done
} > "$tmp_metrics"

# Generate SCRIPTS_INVENTORY.md
{
  echo "# Scripts Inventory"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  echo "Total scripts (excluding scripts/lib): $total_count"
  echo
  echo "## By directory"
  echo
  awk -F'\t' 'NR>1{c[$3]++} END{for(k in c){printf "- %s: %d\n", k, c[k]} }' "$tmp_metrics"
  echo
  echo "## Top ${LIMIT} scripts by line count"
  echo
  echo "| # | Script | Lines | Uses lib | Color vars | Manual az checks |"
  echo "|---:|:------|------:|:--------:|:----------:|:----------------:|"
  awk -F'\t' 'NR>1{print $0}' "$tmp_metrics" | sort -t$'\t' -k2,2nr | head -n "$LIMIT" |
    nl -w2 -s' | ' |
    awk -F'\t' '{printf "%s | `%s` | %s | %s | %s | %s |\n", $1, $2, $3, ($4?"yes":"no"), ($5?"yes":"no"), ($6?"yes":"no")}'

  echo
  echo "## Library adoption status"
  echo
  total=$(awk 'END{print NR-1}' "$tmp_metrics")
  with=$(awk -F'\t' 'NR>1&&$4==1{c++} END{print c+0}' "$tmp_metrics")
  echo "- With lib/init.sh: $with / $total"
  echo "- Without lib/init.sh: "$((total-with))

  echo
  echo "## Potential follow-ups"
  echo
  echo "- Standardize Azure CLI checks via \`ensure_azure_cli\` where \`manual az\` is yes and \`Uses lib\` is yes"
  echo "- Remove color variable declarations where \`Color vars\` = yes and script already uses \`log_*\`"
  echo "- Consider adopting lib/init.sh for high-line-count scripts with \`Uses lib\` = no"

  echo
  echo "## Script call graph (edges)"
  echo
  echo "Format: caller -> callee"
  awk -F'\t' 'NR>1 && $7!=""{ split($7,a," "); for(i in a){print "- " $1 " -> " a[i]} }' "$tmp_metrics"
} > "$DOC_INV"

# Generate COMMANDS_INDEX.md from Makefile
{
  echo "# Commands Index (Makefile → Script Map)"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  echo "| Target | Script |"
  echo "|:------ |:-------|"
  awk '
    BEGIN{t=""}
    /^[A-Za-z0-9_.-]+:/{
      # Capture target name up to colon
      split($0,a,":"); t=a[1]; next
    }
    /^[\t]/ {
      if ($0 ~ /scripts\/.*\.sh/) {
        match($0, /scripts\/[A-Za-z0-9_\/.+-]+\.sh([^ ]*)?/, m);
        if (m[0] != "") { gsub(/^\t+/,"",$0); printf "| %s | \\`%s\\` |\n", t, m[0]; }
      }
    }
  ' "$ROOT_DIR/Makefile"
} > "$DOC_CMD"

emit "Wrote: $DOC_INV"
emit "Wrote: $DOC_CMD"
rm -f "$tmp_metrics"
exit 0
