#!/usr/bin/env bash
# Cursor rule hygiene — run from the Flutter app repository root.
# Usage: bash tool/cursor_audit.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
RULES_DIR="$REPO_ROOT/.cursor/rules"

if [[ ! -d "$RULES_DIR" ]]; then
  echo "No .cursor/rules at $RULES_DIR — run cursor_gen first."
  exit 0
fi

echo "=== Cursor rule audit ==="
echo "Rules without fenced code blocks (\`\`\`):"
missing=0
while IFS= read -r -d '' f; do
  if ! grep -q '```' "$f" 2>/dev/null; then
    echo "  $f"
    missing=1
  fi
done < <(find "$RULES_DIR" -name '*.mdc' -print0)

if [[ "$missing" -eq 0 ]]; then
  echo "  (none — every .mdc contains at least one \`\`\` fence)"
fi

echo ""
echo "Rules with alwaysApply: true (should be few):"
grep -rl 'alwaysApply: true' "$RULES_DIR" 2>/dev/null | while read -r p; do echo "  $p"; done || true

echo ""
feat_dir="$RULES_DIR/features"
if [[ -d "$feat_dir" ]]; then
  echo "Stale feature rules (no lib/features/<name>):"
  stale=0
  for f in "$feat_dir"/*.mdc; do
    [[ -e "$f" ]] || continue
    name="$(basename "$f" .mdc)"
    if [[ ! -d "$REPO_ROOT/lib/features/$name" ]]; then
      echo "  STALE: $f"
      stale=1
    fi
  done
  if [[ "$stale" -eq 0 ]]; then
    echo "  (none)"
  fi
else
  echo "No rules/features/ directory."
fi

echo "=== Done ==="
