#!/bin/bash
#
# Pre-commit hook for Hemmer Provider SDK
#
# This hook runs automatically before each commit to ensure code quality.
# It performs the following checks:
#   1. Code formatting (cargo fmt)
#   2. Linting (cargo clippy)
#   3. Tests (cargo test)
#
# To bypass this hook temporarily, use: git commit --no-verify
#

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo ""
echo "Running pre-commit checks..."
echo ""

# Check 1: Format code
echo "[1/3] Checking code formatting with cargo fmt..."
if cargo fmt --all -- --check > /dev/null 2>&1; then
    echo -e "${GREEN}Done${NC} Code is properly formatted"
else
    echo -e "${YELLOW}Warning:${NC} Code needs formatting, auto-formatting now..."
    cargo fmt --all
    # Re-add formatted files to staging area so they're included in the commit
    git add -u
    echo -e "${GREEN}Done${NC} Code formatted and staged"
fi

# Check 2: Run clippy
echo ""
echo "[2/3] Running clippy..."
# Note: We check clippy but don't fail on warnings since there may be existing warnings
# This ensures clippy runs but doesn't block commits due to pre-existing issues
if cargo clippy --workspace --all-targets 2>&1 | grep -q "error\["; then
    echo -e "${RED}Error:${NC} Clippy found errors. Please fix them before committing."
    echo ""
    cargo clippy --workspace --all-targets
    exit 1
else
    # Check for warnings but don't fail
    if cargo clippy --workspace --all-targets 2>&1 | grep -q "warning:"; then
        echo -e "${YELLOW}Warning:${NC} Clippy warnings found (not blocking commit)"
    else
        echo -e "${GREEN}Done${NC} No clippy issues"
    fi
fi

# Check 3: Run tests
echo ""
echo "[3/3] Running tests..."
if cargo test --workspace --quiet 2>&1; then
    echo -e "${GREEN}Done${NC} All tests passed"
else
    echo -e "${RED}Error:${NC} Tests failed. Please fix failing tests before committing."
    exit 1
fi

echo ""
echo -e "${GREEN}All pre-commit checks passed!${NC}"
echo ""

exit 0
