#!/usr/bin/env bash
# Public-core boundary scan — flags tenant-shaped literals in platform/runtime
# code. See AGENTS.md "Layer and public-core invariants". A non-test hit needs a clear
# generic-platform justification or removal. Exits 1 on any hit (CI-gateable).
set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

pattern='"[A-Za-z0-9_]+__c"|FROM[[:space:]]+[A-Za-z0-9_]+__c|ProfileId[[:space:]]*[=!]=|Profile[[:space:]]*[=!]=|DeveloperName[[:space:]]*[=!]='

scan_roots=(backend frontend shared)
if [ -d nexuscrm-api-host ]; then
  scan_roots+=(nexuscrm-api-host)
fi
if [ "$#" -gt 0 ]; then
  scan_roots=("$@")
fi

if command -v rg >/dev/null 2>&1; then
  hits=$(rg -n "$pattern" "${scan_roots[@]}" \
    --glob '!**/*_test.go' \
    --glob '!frontend/node_modules/**' \
    --glob '!frontend/dist/**' \
    --glob '!frontend/package-lock.json' || true)
else
  hits=$(grep -RInE "$pattern" "${scan_roots[@]}" \
    --exclude='*_test.go' \
    --exclude-dir=node_modules \
    --exclude-dir=dist \
    --exclude=package-lock.json || true)
fi

if [ -n "$hits" ]; then
  printf '%s\n\n' "$hits"
  echo "Boundary scan: hits above need a generic-platform justification or removal." >&2
  exit 1
fi
echo "Boundary scan: clean (${scan_roots[*]})."
