#!/bin/sh
# Pre-commit hook to check formatting and linting with auto-fix capabilities.

EXIT_CODE=0

echo "Checking for staged changes in src/..."
# Check if any staged files are within the src/ directory
if git diff --cached --name-only | grep -q '^src/'; then
  echo "Found staged changes in src/. Running Rust checks..."

  # 1. Check formatting
  echo "Checking formatting..."
  if ! cargo fmt --all -- --check; then
    echo "Formatting issues found. Attempting to auto-fix..."
    cargo fmt
    # Stage the formatted files that were already staged
    git diff --name-only | grep '^src/' | xargs -I{} git add {}
    echo "Formatting fixed and changes staged."
  else
    echo "Formatting OK."
  fi

  # 2. Run Clippy linter
  echo "Running linter..."
  if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo "Clippy issues found. Attempting to auto-fix..."
    # Note: --fix is a nightly feature, so we check if it works
    if cargo clippy --fix --allow-dirty --allow-staged -- -D warnings 2>/dev/null; then
      # Stage the fixed files that were already staged
      git diff --name-only | grep '^src/' | xargs -I{} git add {}
      echo "Clippy issues fixed and changes staged."
    else
      echo "Automatic fix failed. Please fix the issues manually."
      EXIT_CODE=1
    fi
  else
    echo "Clippy checks OK."
  fi

  # 3. Run tests
  if [ $EXIT_CODE -eq 0 ]; then # Only run tests if previous steps passed
    echo "Running tests (including integration-tests feature)..."
    if ! cargo test --all-features; then
      echo "Tests failed. Please fix the issues manually."
      EXIT_CODE=1
    else
      echo "Tests passed."
    fi
  fi

  if [ $EXIT_CODE -eq 0 ]; then
    echo "Rust checks passed successfully."
  else
    echo "Some issues could not be fixed automatically. Please resolve them manually."
  fi
else
  echo "No staged changes found in src/. Skipping Rust checks."
fi

exit $EXIT_CODE
