#!/usr/bin/env sh

# Ensure hooks run from repo root (we intentionally do not source Husky internals).
ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
if [ -n "$ROOT" ]; then
  cd "$ROOT" || exit 1
fi

# Prefer local binaries (prettier/lint-staged/etc.)
export PATH="$PWD/node_modules/.bin:$PATH"

# Check if Husky is disabled via environment variable
if [ "$HUSKY_ENABLED" = "false" ]; then
  echo "⚠️  Husky disabled via HUSKY_ENABLED=false"
  echo "💡 To re-enable: unset HUSKY_ENABLED or export HUSKY_ENABLED=true"
  exit 0
fi

echo "🔐 Scanning staged changes for secrets..."
bash scripts/secret-scan-staged.sh

echo "🐶 Running pre-commit hooks for common platform..."

# Run lint-staged on staged files
pnpm exec lint-staged

# CC.8 — Re-run the roadmap progress counter whenever the roadmap is staged.
# Updates the §11.2 progress block + per-wave headings + re-stages the file
# so the commit captures the refreshed counts. Silent no-op when the file
# wasn't touched.
if git diff --cached --name-only | grep -q "^docs/UI_ROADMAP_2026_V3_CROSS_REPO\.md$"; then
  echo "📊 Refreshing roadmap progress counter..."
  pnpm dlx tsx scripts/count-roadmap-progress.ts docs/UI_ROADMAP_2026_V3_CROSS_REPO.md \
    && git add docs/UI_ROADMAP_2026_V3_CROSS_REPO.md
fi
