#!/usr/bin/env bash
set -e

# Pre-commit Hook
#
# To install:
#   git config core.hooksPath .githooks
#
# To bypass (use sparingly):
#   git commit --no-verify

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

echo "Running pre-commit checks..."

# 0. Prevent committing gitignored files
echo -n "Checking for gitignored files... "
ignored_staged=$(git diff --cached --name-only --diff-filter=d | while read -r file; do
  if git check-ignore --no-index -q "$file" 2>/dev/null; then
    echo "$file"
  fi
done)

if [[ -n "${ignored_staged}" ]]; then
    echo -e "${RED}FAILED${NC}"
    echo "error: gitignored files must not be included in source control:" >&2
    echo "${ignored_staged}" | sed 's/^/  /' >&2
    echo "" >&2
    echo "Remove them with: git reset HEAD <file>" >&2
    exit 1
fi
echo -e "${GREEN}OK${NC}"

# 1. Format check (fast)
echo -n "Checking formatting... "
if cargo fmt --all -- --check 2>/dev/null; then
    echo -e "${GREEN}OK${NC}"
else
    echo -e "${RED}FAILED${NC}"
    echo "Run 'cargo fmt --all' to fix formatting"
    exit 1
fi

# 2. Quick compile check
echo -n "Checking compilation... "
if cargo check --workspace --all-targets --all-features 2>/dev/null; then
    echo -e "${GREEN}OK${NC}"
else
    echo -e "${RED}FAILED${NC}"
    exit 1
fi

echo -e "${GREEN}Pre-commit checks passed!${NC}"
echo ""
echo "Tip: Run './scripts/lint-check.sh' for comprehensive style guide checks"
