#!/bin/sh

# Kindling pre-push hook
# Runs linting, formatting, type checking, and tests before pushing

# Automation bypass: blacksmith has its own test gate and CI re-runs every check on the
# PR, and it pushes `blacksmith/*` branches WITHOUT --no-verify. Skip this heavy local
# suite when every ref being pushed is a blacksmith branch (or SKIP_PREPUSH is set).
# Human pushes to normal branches still run the full suite below.
if [ -n "$SKIP_PREPUSH" ]; then
  echo "pre-push: skipped (SKIP_PREPUSH set)"
  exit 0
fi
_bs_skip=1
_bs_saw=0
while read -r _local_ref _rest; do
  [ -z "$_local_ref" ] && continue
  _bs_saw=1
  case "$_local_ref" in
    refs/heads/blacksmith/*) : ;;
    *) _bs_skip=0 ;;
  esac
done
if [ "$_bs_saw" = 1 ] && [ "$_bs_skip" = 1 ]; then
  echo "pre-push: skipping checks for blacksmith automation branch"
  exit 0
fi

echo "Running pre-push checks..."

# Store the current directory
cd "$(git rev-parse --show-toplevel)"

# Run Prettier format check
echo "\n[1/6] Checking formatting (Prettier)..."
npm run format:check
if [ $? -ne 0 ]; then
  echo "\n❌ Formatting check failed. Run 'npm run format' to fix."
  exit 1
fi

# Run ESLint
echo "\n[2/6] Running linter (ESLint)..."
npm run lint
if [ $? -ne 0 ]; then
  echo "\n❌ Linting failed. Fix the errors above before pushing."
  exit 1
fi

# Run TypeScript/Svelte type check
echo "\n[3/6] Running type check (svelte-check)..."
npm run check
if [ $? -ne 0 ]; then
  echo "\n❌ Type check failed. Fix the errors above before pushing."
  exit 1
fi

# Run Rust format check
echo "\n[4/6] Checking Rust formatting (cargo fmt)..."
cd src-tauri
cargo fmt --all -- --check
if [ $? -ne 0 ]; then
  echo "\n❌ Rust formatting check failed. Run 'cargo fmt' in src-tauri/ to fix."
  exit 1
fi

# Run Clippy
echo "\n[5/6] Running Rust linter (clippy)..."
cargo clippy -- -D warnings
if [ $? -ne 0 ]; then
  echo "\n❌ Clippy check failed. Fix the warnings above before pushing."
  exit 1
fi
cd ..

# Run tests
echo "\n[6/6] Running tests (Vitest)..."
npm test
if [ $? -ne 0 ]; then
  echo "\n❌ Tests failed. Fix the failing tests before pushing."
  exit 1
fi

echo "\n✅ All pre-push checks passed!"
exit 0
