#!/usr/bin/env bash
# Validate all shell scripts locally (no git/network). Produces docs/SCRIPTS_QA_REPORT.md
set -u
ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
REPORT="$ROOT_DIR/docs/SCRIPTS_QA_REPORT.md"
mkdir -p "$ROOT_DIR/docs"

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

ok=0; fail=0
tmp=$(mktemp)
{
  echo "# Scripts QA Report"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  echo "## Bash syntax check (bash -n)"
  for f in "${FILES[@]}"; do
    if bash -n "$f" 2>/dev/null; then
      echo "- [OK] ${f#$ROOT_DIR/}"; ((ok++))
    else
      echo "- [FAIL] ${f#$ROOT_DIR/}"; ((fail++))
    fi
  done
  echo
  echo "Summary: $ok OK, $((ok+fail)) total"

  if command -v shellcheck >/dev/null 2>&1; then
    echo
    echo "## ShellCheck summary"
    for f in "${FILES[@]}"; do
      shellcheck -f gcc "$f" || true
    done | tee "$tmp"
    echo
    echo "- ShellCheck issues: $(wc -l < "$tmp") lines reported"
  else
    echo
    echo "## ShellCheck"
    echo "shellcheck not found; skipping. Install with: sudo apt-get install shellcheck"
  fi
} > "$REPORT"

rm -f "$tmp"
echo "QA report written: $REPORT"
