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

# Ensure we're at the repo root
cd "$(git rev-parse --show-toplevel)" || exit 1

echo "Running cargo fmt (auto-format)..."
# Run formatter to apply fixes but do not stage them. If formatting changed,
# fail the commit so the user can review and stage the changes manually.
cargo fmt --all
if ! git diff --quiet --exit-code; then
  echo "" >&2
  echo "ERROR: cargo fmt modified files. Review changes, stage them, and commit again." >&2
  git --no-pager diff --name-only
  exit 1
fi

echo "Running cargo clippy..."
# Matches CI: deny warnings to keep code health strict
if ! cargo clippy --workspace --all-targets --all-features -- -D warnings; then
  echo "" >&2
  echo "ERROR: clippy found warnings/errors. Fix them before committing." >&2
  exit 1
fi

echo "Running cargo test..."
if ! cargo test --workspace --all-features; then
  echo "" >&2
  echo "ERROR: Some tests failed. Fix tests before committing." >&2
  exit 1
fi

echo "All pre-commit checks passed."
exit 0
