#!/bin/bash
# pre-commit hook to prevent hardcoded user paths in committed files
# Install: cp scripts/pre-commit-no-hardcoded-paths .git/hooks/pre-commit
#          (or append to existing .git/hooks/pre-commit)

# Get staged files, excluding binary files and node_modules
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM \
  | grep -v 'node_modules/' \
  | grep -v '.mcp.json' \
  || true)

if [ -z "$STAGED_FILES" ]; then
  exit 0
fi

echo "Checking staged files for hardcoded user paths..."

VIOLATIONS_FOUND=0

for file in $STAGED_FILES; do
  # Skip binary files
  if file "$file" 2>/dev/null | grep -qE 'binary|executable|ELF|Mach-O'; then
    continue
  fi

  # Check only added lines (lines starting with +, excluding the +++ header)
  MATCHES=$(git diff --cached -- "$file" \
    | grep -E '^\+' \
    | grep -v '^+++' \
    | grep -oE '/Users/[^/[:space:]"'"'"']+|/home/[^/[:space:]"'"'"']+' \
    || true)

  if [ ! -z "$MATCHES" ]; then
    echo ""
    echo "❌ Hardcoded user path found in: $file"
    echo "$MATCHES" | while read -r match; do
      echo "   $match"
    done
    VIOLATIONS_FOUND=1
  fi
done

if [ $VIOLATIONS_FOUND -eq 1 ]; then
  echo ""
  echo "============================================="
  echo "COMMIT BLOCKED: Hardcoded user path detected"
  echo "============================================="
  echo ""
  echo "Paths like /Users/<username>/ or /home/<username>/ only work on one machine."
  echo ""
  echo "Portable alternatives:"
  echo "  Shell:  REPO_ROOT=\"\$(cd \"\$(dirname \"\${BASH_SOURCE[0]}\")/.\" && pwd)\""
  echo "  Node:   import { homedir } from \"os\""
  echo "  Python: from pathlib import Path; Path.home()"
  echo "  Docs:   Use relative paths from repo root (e.g. .claude/agents/)"
  echo ""
  exit 1
fi

echo "✓ No hardcoded user paths found"
exit 0
