#!/bin/bash
#
# Git Pre-Commit Hook: Unit Test Enforcement
#
# This hook runs all unit tests before allowing a commit.
# It enforces the 100% unit test passing requirement.
#
# Installation:
#   cp .git-hooks/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#
# Bypass (use sparingly, WIP commits only):
#   git commit --no-verify

set -e

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

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}🧪 Running Unit Tests Before Commit${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Navigate to backend directory (where this hook should run)
BACKEND_DIR="/mnt/NV2/Development/strat-gameplay-webapp/backend"

if [ ! -d "$BACKEND_DIR" ]; then
    echo -e "${RED}❌ ERROR: Backend directory not found at $BACKEND_DIR${NC}"
    echo -e "${YELLOW}   This hook should be run from the backend directory.${NC}"
    exit 1
fi

cd "$BACKEND_DIR"

# Check if uv is available
if ! command -v uv &> /dev/null; then
    echo -e "${RED}❌ ERROR: UV package manager not found${NC}"
    echo -e "${YELLOW}   Install UV: curl -LsSf https://astral.sh/uv/install.sh | sh${NC}"
    exit 1
fi

# Run unit tests
echo -e "${YELLOW}Running unit tests...${NC}"
echo ""

if uv run pytest tests/unit/ -q; then
    echo ""
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}✅ All unit tests passed! Proceeding with commit.${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    exit 0
else
    echo ""
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${RED}❌ Unit tests FAILED - Commit aborted!${NC}"
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo -e "${YELLOW}Please fix the failing tests before committing.${NC}"
    echo ""
    echo -e "${YELLOW}To see detailed error messages, run:${NC}"
    echo -e "  ${BLUE}uv run pytest tests/unit/ -v${NC}"
    echo ""
    echo -e "${YELLOW}To bypass this check (WIP commits only):${NC}"
    echo -e "  ${BLUE}git commit --no-verify${NC}"
    echo ""
    echo -e "${RED}⚠️  WARNING: Never bypass on main branch!${NC}"
    echo ""
    exit 1
fi
