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

# Capture currently staged Rust files so we can restage their formatted versions
staged_rs=$(git diff --name-only --cached -z -- '*.rs' || true)

echo "[pre-commit] cargo fmt --all (applying formatting)"
cargo fmt --all

# Restage only files that were already staged prior to formatting
if [[ -n "${staged_rs}" ]]; then
  echo "[pre-commit] restaging formatted files"
  printf '%s' "${staged_rs}" | xargs -0 git add --
fi

echo "[pre-commit] cargo clippy -D warnings"
cargo lint

if [[ -z "${SKIP_CARGO_TEST:-}" ]]; then
  echo "[pre-commit] cargo test (set SKIP_CARGO_TEST=1 to skip)"
  cargo test --workspace --all-targets --all-features
else
  echo "[pre-commit] skipping cargo test due to SKIP_CARGO_TEST"
fi
