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

echo "→ pre-commit: checking formatting + clippy"

# Stash unstaged changes so we only check staged files
STASH_NAME="pre-commit-$(date +%s)"
git stash --staged --quiet --include-untracked --message "$STASH_NAME" 2>/dev/null || true

cleanup() {
  git stash list --format='%s' | grep -qFx "$STASH_NAME" && git stash pop --quiet 2>/dev/null || true
}
trap cleanup EXIT

# ── cargo fmt ─────────────────────────────────────────────────────────────────
cargo fmt --check 2>/dev/null
fmt_exit=$?
if [ $fmt_exit -ne 0 ]; then
  echo "❌ cargo fmt: some files are not formatted. Run 'cargo fmt' and stage again."
  exit 1
fi
echo "  ✓ cargo fmt"

# ── cargo clippy ──────────────────────────────────────────────────────────────
cargo clippy --all-targets -- -D warnings 2>/dev/null
clippy_exit=$?
if [ $clippy_exit -ne 0 ]; then
  echo "❌ cargo clippy: fix warnings before committing."
  exit 1
fi
echo "  ✓ cargo clippy"

echo "✓ pre-commit passed"
