#!/bin/sh
# Pre-commit: fast local lint gate before commit. Full suite runs in pre-push/CI.
set -e

ensure_node_tooling() {
  if command -v node >/dev/null 2>&1 && command -v pnpm >/dev/null 2>&1; then
    return 0
  fi

  NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
  if [ -s "$NVM_DIR/nvm.sh" ]; then
    # shellcheck disable=SC1090
    . "$NVM_DIR/nvm.sh" --no-use
    nvm use --silent node >/dev/null 2>&1 || true
  fi

  if ! command -v node >/dev/null 2>&1 || ! command -v pnpm >/dev/null 2>&1; then
    echo "❌ node and pnpm must be available before committing"
    echo "   Install them or make sure your nvm setup is available to git hooks."
    exit 1
  fi
}

ensure_node_tooling

echo "🔍 Pre-commit checks..."

STAGED_FILES=$(git diff --cached --name-only)
APP_CHANGED=false

for FILE in $STAGED_FILES; do
  case "$FILE" in
    .github/workflows/*|.husky/*|docs/*|*.md)
      ;;
    *)
      APP_CHANGED=true
      ;;
  esac
done

if [ "$APP_CHANGED" = false ]; then
  echo "  → app checks skipped (docs/workflow/hooks only)"
  echo "✅ Pre-commit passed"
  exit 0
fi

# Lint only when frontend source files are staged. Typecheck and test coverage
# run in the pre-push gate.
STAGED_LINTABLE=$(echo "$STAGED_FILES" | grep -E '\.(ts|tsx|js|jsx|mjs)$' || true)
if [ -n "$STAGED_LINTABLE" ]; then
  echo "  → lint..."
  pnpm lint --quiet
fi

echo "✅ Pre-commit passed"
