#!/usr/bin/env bash
# Pre-commit: fast quality gate — format, compile-check, and lint.
# Runs only when at least one .rs, build.rs, or Cargo.toml file is staged.
# Tests live in pre-push to keep commits snappy.
set -euo pipefail

if ! command -v cargo >/dev/null 2>&1; then
  echo "pre-commit: cargo not found, skipping." >&2
  exit 0
fi

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

# Only run when Rust source or manifests are staged.
staged_rs=()
while IFS= read -r file; do
  if [[ "$file" == *.rs || "$file" == "Cargo.toml" || "$file" == "build.rs" ]]; then
    staged_rs+=("$file")
  fi
done < <(git diff --cached --name-only --diff-filter=ACMR)

if [[ "${#staged_rs[@]}" -eq 0 ]]; then
  exit 0
fi

echo "pre-commit: rustfmt"
cargo fmt --all
# Re-stage anything rustfmt touched that was already staged.
git add -- "${staged_rs[@]}"

echo "pre-commit: cargo check"
RUSTFLAGS="-D warnings" cargo check --lib --all-features

echo "pre-commit: cargo clippy"
cargo clippy --lib --all-features -- -D warnings

echo "pre-commit: ok"
