#!/bin/sh
#
# Pre-commit hook: Fast checks to catch issues before committing
# Runs: cargo fmt check, cargo clippy
#

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo "${CYAN}╭─────────────────────────────────────────╮${NC}"
echo "${CYAN}│          Pre-commit Checks              │${NC}"
echo "${CYAN}╰─────────────────────────────────────────╯${NC}"

# Check if there are any staged Rust files
STAGED_RS_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.rs$' || true)

if [ -z "$STAGED_RS_FILES" ]; then
    echo "${YELLOW}No Rust files staged, skipping checks${NC}"
    exit 0
fi

# 1. Check formatting
echo ""
echo "${YELLOW}▸ Checking formatting...${NC}"
if ! cargo fmt --all -- --check; then
    echo ""
    echo "${RED}✖ Formatting check failed!${NC}"
    echo "${YELLOW}  Run 'cargo fmt' to fix formatting issues${NC}"
    exit 1
fi
echo "${GREEN}✔ Formatting OK${NC}"

# 2. Run clippy (quick check, warnings allowed)
echo ""
echo "${YELLOW}▸ Running clippy...${NC}"
if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo ""
    echo "${RED}✖ Clippy found issues!${NC}"
    echo "${YELLOW}  Fix the warnings above before committing${NC}"
    exit 1
fi
echo "${GREEN}✔ Clippy OK${NC}"

# 3. Quick compile check
echo ""
echo "${YELLOW}▸ Checking compilation...${NC}"
if ! cargo check --all-targets --all-features; then
    echo ""
    echo "${RED}✖ Compilation failed!${NC}"
    exit 1
fi
echo "${GREEN}✔ Compilation OK${NC}"

echo ""
echo "${GREEN}╭─────────────────────────────────────────╮${NC}"
echo "${GREEN}│       ✔ All pre-commit checks passed    │${NC}"
echo "${GREEN}╰─────────────────────────────────────────╯${NC}"
echo ""

