#!/bin/bash
# Pre-commit hook to run tests before committing to master/main branches
# This ensures code quality and prevents broken commits

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

# Get the current branch name
current_branch=$(git symbolic-ref HEAD 2>/dev/null | sed -e 's,.*/\(.*\),\1,')

# Check if we're on master or main branch
if [ "$current_branch" = "master" ] || [ "$current_branch" = "main" ]; then
    echo -e "${YELLOW}⚠️  You're committing directly to $current_branch branch.${NC}"
    echo -e "${BLUE}🔍 Running tests to ensure code quality...${NC}"
    echo ""
    
    # Check if virtual environment exists
    if [ ! -d "venv" ]; then
        echo -e "${YELLOW}Creating virtual environment...${NC}"
        python3 -m venv venv
    fi
    
    # Activate virtual environment and run tests
    echo -e "${BLUE}Running test suite...${NC}"
    
    # Run tests with proper environment
    if source venv/bin/activate 2>/dev/null && python -m pytest tests/ -q --tb=short; then
        deactivate 2>/dev/null
        echo ""
        echo -e "${GREEN}✅ All tests passed! Proceeding with commit.${NC}"
        echo -e "${YELLOW}📌 Remember: Direct commits to $current_branch should be avoided.${NC}"
        echo -e "${YELLOW}   Consider using feature branches and PRs instead.${NC}"
    else
        deactivate 2>/dev/null
        echo ""
        echo -e "${RED}❌ Tests failed! Commit aborted.${NC}"
        echo -e "${YELLOW}Please fix the failing tests before committing.${NC}"
        echo ""
        echo "To run tests manually:"
        echo "  source venv/bin/activate"
        echo "  python -m pytest tests/ -v"
        exit 1
    fi
else
    # On feature branches, run a quick lint check
    echo -e "${BLUE}🔍 Running quick checks on feature branch...${NC}"
    
    # Check for Python syntax errors in staged files
    git diff --cached --name-only --diff-filter=ACM | grep '\.py$' | while read file; do
        if [ -f "$file" ]; then
            python -m py_compile "$file" 2>/dev/null
            if [ $? -ne 0 ]; then
                echo -e "${RED}❌ Syntax error in $file${NC}"
                exit 1
            fi
        fi
    done
    
    echo -e "${GREEN}✅ Quick checks passed!${NC}"
fi

exit 0