#!/bin/sh

# Pre-commit hook: auto-formats staged files and ensures tests pass before committing

echo "Running pre-commit checks..."

# 1. Auto-format staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(ts|tsx|js|jsx|json|md)$')

if [ -n "$STAGED_FILES" ]; then
  echo "Auto-formatting..."
  echo "$STAGED_FILES" | xargs deno fmt
  if [ $? -ne 0 ]; then
    echo ""
    echo "Auto-format failed. Fix the issues manually and try again."
    exit 1
  fi
  echo "$STAGED_FILES" | xargs git add
fi

# 2. Run all tests
echo "Running tests..."
deno task test
if [ $? -ne 0 ]; then
  echo ""
  echo "Tests failed. Fix the failing tests before committing."
  exit 1
fi

echo "All checks passed."
