#!/usr/bin/env bash
# Remove color variable definitions from scripts that already source lib/init.sh
# Only removes if no ${RED|GREEN|YELLOW|BLUE|CYAN|NC} usages remain.
# Writes a report to docs/COLOR_VARS_CLEANUP.md
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
REPORT="$ROOT_DIR/docs/COLOR_VARS_CLEANUP.md"

mkdir -p "$ROOT_DIR/docs"

mapfile -t FILES < <(cd "$ROOT_DIR" && grep -rl --include='*.sh' 'source "$SCRIPT_DIR/../lib/init.sh"' scripts | sort)
changed=()
skipped=()

{
  echo "# Color Variables Cleanup"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  for f in "${FILES[@]}"; do
    # skip if any color variable is still referenced
    if grep -qE '\$\{(RED|GREEN|YELLOW|BLUE|CYAN|NC)\}' "$f"; then
      echo "- [ ] $(realpath --relative-to="$ROOT_DIR" "$f") (has color refs, skipped)" || true
      continue
    fi
    # remove color var definitions and 'Colors for output' comment lines
    tmp="$(mktemp)"; cp "$f" "$tmp"
    sed -E '/^[[:space:]]*#\s*Colors( for output)?/d' "$f" | \
      sed -E '/^[[:space:]]*(RED|GREEN|YELLOW|BLUE|CYAN|NC)=.*/d' > "$f.__new__"
    mv "$f.__new__" "$f"
    if ! bash -n "$f"; then
      # revert if syntax fails
      cp "$tmp" "$f"; rm -f "$tmp"
      echo "- [ ] $(realpath --relative-to="$ROOT_DIR" "$f") (reverted due to syntax error)" || true
      continue
    fi
    rm -f "$tmp"
    changed+=("$f")
    echo "- [x] $(realpath --relative-to="$ROOT_DIR" "$f") (color vars removed)" || true
  done

  echo
  echo "## Summary"
  echo "- Cleaned: ${#changed[@]} files"
  echo "- Skipped: ${#skipped[@]} files"
} > "$REPORT"

echo "Cleanup complete. Report: $REPORT"
