#!/usr/bin/env bash
# scripts/test-rename-consistency.sh
# Guards against residual `topgauge` strings after the v1.0.0 rename.
# Exits non-zero if any non-allowlisted file still contains the old name tokens.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

# Allowlist:
#   - this script itself (mentions topgauge in comments + log output)
#   - the captured fixture stdin.real.json (auth data — must NOT be renamed)
#   - src/index-parse.test.ts (asserts against the captured fixture's
#     historical cwd/repo.name — must stay in sync with stdin.real.json)
#   - CLAUDE.md (documents the historical v0.7.0 and v1.0.0 renames,
#     must preserve `tokenplan-usage-hud` / `topgauge` literal references)
#   - README.md (the v1.0.0 upgrade-flow section legitimately references
#     the OLD name being uninstalled: `/topgauge:uninstall`,
#     `cache/topgauge/`, `_topgauge_managed`, etc.)
#   - CHANGELOG.md (per-release history; entries describe what happened
#     in past releases and must remain historically accurate, including
#     the v0.7.0 paragraph that references `topgauge-cc`)
#   - package-lock.json (regenerated by `npm install`, not a source of truth)
#   - scripts/test-reset.sh (projectHash comment explains the v1.0.0 rename:
#     "the repo root is `CreditGauge`, not `topgauge`")
#   - node_modules / dist / .git / .superpowers / docs about the rename work
ALLOWLIST_REGEX='(^|/)(\.git/|node_modules/|dist/|\.superpowers/|docs/superpowers/(specs|plans)/2026-07-17-(rename-topgauge-to-creditgauge(-design)?|balance-per-entry-color)|scripts/test-rename-consistency\.sh$|scripts/test-reset\.sh$|src/__fixtures__/stdin\.real\.json$|src/index-parse\.test\.ts$|CLAUDE\.md$|README\.md$|CHANGELOG\.md$|package-lock\.json$)'

PATTERNS=(
  'topgauge'
  'TopGauge'
  'ToPGauge'
  'TOPGAUGE_'
  '_topgauge_managed'
)

FAIL=0
for pattern in "${PATTERNS[@]}"; do
  # grep -rEl is portable; --include filters to text source extensions
  HITS=$(grep -rEl "$pattern" \
    --include='*.ts' --include='*.js' --include='*.mjs' \
    --include='*.sh' --include='*.md' --include='*.json' \
    --include='*.yml' --include='*.yaml' --include='*.txt' \
    . 2>/dev/null \
    | grep -vE "$ALLOWLIST_REGEX" \
    || true)
  if [ -n "$HITS" ]; then
    echo "FAIL: residual '$pattern' in:"
    echo "$HITS" | sed 's/^/  /'
    FAIL=1
  fi
done

if [ $FAIL -ne 0 ]; then
  echo
  echo "Rename-incomplete: residual topgauge tokens found."
  echo "If a hit is legitimate (e.g. captured fixture, lockfile), add it to the allowlist in this script."
  exit 1
fi

echo "OK: no residual topgauge tokens in source."