#!/usr/bin/env bash
# CI grep guards — Law 1, Law 4, Law 9 enforcement.
# Exit non-zero on any forbidden pattern.
set -e
cd "$(dirname "$0")/../.."

# Law 4: fail loudly if rg is missing as a binary. Without this, the
# `if rg ...` tests below see rg-not-found (non-zero exit) and skip the
# guard body — the script exits 0 with a misleading "passed" message.
# `command -v` requires rg to be a real binary, not just a shell function
# (which Claude Code's interactive shell aliases — bash subshells don't
# inherit it). Install: brew install ripgrep.
if ! command -v rg >/dev/null 2>&1; then
  echo "GUARD FATAL: ripgrep (rg) not in PATH; cannot run guards." >&2
  echo "Install: brew install ripgrep" >&2
  exit 2
fi

GUARD_FAILED=0

# Guard 1: literal projects-root path outside paths.py / tests / archive
if rg -n 'Path\(["\x27]~/Dropbox/CLAUDE_PROJECTS/projects["\x27]\)' \
     --glob '!**/core/paths.py' --glob '!**/test_*' \
     --glob '!**/_archive/**' \
     recoil/ 2>/dev/null; then
  echo "GUARD 1 FAILED: literal projects-root path leaked outside paths.py" >&2
  GUARD_FAILED=1
fi

# Guard 2: Path.home() variant — catches both inline form
# (`Path.home() / "Dropbox/CLAUDE_PROJECTS/projects"`) AND split-path form
# (`Path.home() / "Dropbox" / "CLAUDE_PROJECTS" / "projects"`). The
# alternation handles both; rg -U lets the regex span the line.
if rg -nU 'Path\.home\(\)\s*/\s*"Dropbox/CLAUDE_PROJECTS/projects"|Path\.home\(\)\s*(/\s*"[^"]+"\s*){2,}/\s*"projects"' \
     --glob '!**/core/paths.py' --glob '!**/test_*' \
     --glob '!**/tests/**' \
     --glob '!**/_archive/**' \
     --glob '!**/ci_grep_guards.sh' \
     recoil/ 2>/dev/null; then
  echo "GUARD 2 FAILED: Path.home() projects-root variant leaked" >&2
  GUARD_FAILED=1
fi

# Guard 3: import-idiom guard for files CP-A touched
if rg -n '^from core\.' --glob '*.py' --glob '!**/test_*' \
     --glob '!**/core/paths.py' \
     recoil/api/ recoil/console-v2/ 2>/dev/null; then
  echo "GUARD 3 FAILED: 'from core.' idiom in recoil/api or recoil/console-v2" >&2
  GUARD_FAILED=1
fi

if [ "$GUARD_FAILED" -ne 0 ]; then
  echo "CI grep guards FAILED" >&2
  exit 1
fi
echo "CI grep guards passed"
