#!/bin/bash
# File: hooks/pre-commit
# Purpose: Enforce safe commit practices and prevent direct commits to main
# Context:
#   1. Prevents commits directly to main branch (PR only policy)
#   2. Warns if another device has a lock, allowing users to abort if needed

# ============================================================================
# Check 1: Prevent commits to main (main branch protection)
# ============================================================================
current_branch=$(git symbolic-ref --short HEAD 2>/dev/null)

if [ "$current_branch" = "main" ]; then
  echo ""
  echo "❌ COMMIT REJECTED: Direct commits to main are forbidden!"
  echo ""
  echo "The 'main' branch is protected and can only be updated via PR merge."
  echo ""
  echo "✅ Correct workflow:"
  echo "   1. Switch to dev or feature branch:"
  echo "      $ git checkout dev"
  echo "      $ git checkout -b feature/my-feature dev"
  echo ""
  echo "   2. Make your changes and commit:"
  echo "      $ git add . && git commit -m 'feat: your change'"
  echo ""
  echo "   3. Push and create a PR:"
  echo "      $ git push origin feature/my-feature"
  echo "      $ gh pr create --base dev --head feature/my-feature"
  echo ""
  echo "🚀 For direct main updates (hotfixes only):"
  echo "   - Contact the project maintainer"
  echo "   - Use: git commit --no-verify (⚠️  not recommended)"
  echo ""
  exit 1
fi

# ============================================================================
# Check 2: Device lock conflict detection (multi-device safety)
# ============================================================================
if [ -f .dropbox/DEVICE_LOCK ]; then
  current_device=$(hostname 2>/dev/null || echo "unknown")
  locked_device=$(cat .dropbox/DEVICE_LOCK 2>/dev/null)

  if [ "$locked_device" != "$current_device" ] && [ ! -z "$locked_device" ]; then
    echo ""
    echo "⚠️  WARNING: Device lock detected!"
    echo "    Locked by: $locked_device"
    echo "    Current:   $current_device"
    echo ""
    echo "This may indicate another device is currently working on this repo."
    echo "Proceeding may cause conflicts or data loss."
    echo ""

    # Allow user to abort
    read -p "Continue with commit? (y/N): " -r
    if [[ ! "$REPLY" =~ ^[Yy]$ ]]; then
      echo "Commit aborted."
      exit 1
    fi
  fi
fi

# ============================================================================
# Check 3: Warn-only encoding scan (mojibake early detection)
# ============================================================================
if command -v bash >/dev/null 2>&1; then
  : # ensure POSIX-ish env
fi

if [ -x bin/scan-encoding ]; then
  echo "[pre-commit] Running warn-only encoding scan..."
  # Do not block commits; write findings for later review.
  bin/scan-encoding \
    --paths "docs/**/*.md" "src/**/*.py" \
    --output reports/encoding_scan_findings_precommit.txt \
    >/dev/null 2>&1 || true
fi

exit 0
