#!/usr/bin/env bash
set -Eeuo pipefail

# Copyright (c) 2026 Red Authors
# License: MIT
#

# Run Rust formatter before commit. This script is intended to be installed as:
#   git config core.hooksPath .githooks
# Then it will run automatically on `git commit`.

REPO_ROOT_DIR=$(cd "$(dirname "$0")"/.. && pwd)

echo "[pre-commit] Checking Rust formatting..."

# First, check formatting to decide whether to block the commit
if python3 "${REPO_ROOT_DIR}/red/scripts/format_rust.py" --check; then
  echo "[pre-commit] Formatting check passed."
  exit 0
else
  status=$?
  if [ "$status" -eq 2 ]; then
    echo "[pre-commit] Formatter prerequisites missing. Aborting commit."
    exit 2
  fi
  echo "[pre-commit] Code is not properly formatted. Running formatter..."
  python3 "${REPO_ROOT_DIR}/red/scripts/format_rust.py"
  echo "[pre-commit] Code was reformatted. Review changes and re-run commit."
  # Block commit; do not stage files automatically
  exit 1
fi
