#!/bin/bash
set -e

echo "🔍 Running pre-commit hooks..."

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

# Get list of staged files
STAGED_RUST_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.rs$' || true)
STAGED_PYTHON_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.py$' || true)

# Flag to track if we need to fail
LINT_FAILED=0

# ====================
# Rust Linting
# ====================
if [ -n "$STAGED_RUST_FILES" ]; then
    echo -e "${YELLOW}📝 Formatting Rust code with cargo fmt...${NC}"
    
    # Run cargo fmt and check if it made changes
    if ! cargo fmt --all -- --check > /dev/null 2>&1; then
        echo -e "${YELLOW}⚠️  Rust code was not formatted. Running cargo fmt...${NC}"
        cargo fmt --all
        
        # Check if cargo fmt fixed everything
        if ! cargo fmt --all -- --check > /dev/null 2>&1; then
            echo -e "${RED}❌ cargo fmt failed to fix all formatting issues${NC}"
            LINT_FAILED=1
        else
            # Stage the formatted files
            echo "$STAGED_RUST_FILES" | xargs git add
            echo -e "${GREEN}✅ Rust code formatted successfully${NC}"
        fi
    else
        echo -e "${GREEN}✅ Rust code is already properly formatted${NC}"
    fi
    
    echo -e "${YELLOW}🔎 Running clippy...${NC}"
    # Run clippy with warnings as errors
    if ! cargo clippy --all-targets --all-features -- -D warnings; then
        echo -e "${RED}❌ Clippy found issues that need to be fixed manually${NC}"
        LINT_FAILED=1
    else
        echo -e "${GREEN}✅ Clippy checks passed${NC}"
    fi
fi

# ====================
# Python Linting
# ====================
if [ -n "$STAGED_PYTHON_FILES" ]; then
    echo -e "${YELLOW}📝 Formatting Python code with black...${NC}"
    
    # Check if black is installed
    if ! command -v black &> /dev/null; then
        echo -e "${YELLOW}⚠️  black is not installed. Installing...${NC}"
        if ! pip install black > /dev/null 2>&1; then
            echo -e "${RED}❌ Failed to install black${NC}"
            LINT_FAILED=1
        fi
    fi
    
    # Only proceed if black is available
    if command -v black &> /dev/null; then
        # Run black on staged Python files
        if ! echo "$STAGED_PYTHON_FILES" | xargs black --check > /dev/null 2>&1; then
            echo -e "${YELLOW}⚠️  Python code was not formatted. Running black...${NC}"
            
            # Try to format with black
            if echo "$STAGED_PYTHON_FILES" | xargs black; then
                # Verify formatting was successful
                if echo "$STAGED_PYTHON_FILES" | xargs black --check > /dev/null 2>&1; then
                    # Stage the formatted files
                    echo "$STAGED_PYTHON_FILES" | xargs git add
                    echo -e "${GREEN}✅ Python code formatted successfully${NC}"
                else
                    echo -e "${RED}❌ Black formatting verification failed${NC}"
                    LINT_FAILED=1
                fi
            else
                echo -e "${RED}❌ Black failed to format Python files${NC}"
                LINT_FAILED=1
            fi
        else
            echo -e "${GREEN}✅ Python code is already properly formatted${NC}"
        fi
    fi
fi

# ====================
# Final Check
# ====================
if [ $LINT_FAILED -eq 1 ]; then
    echo -e "${RED}❌ Pre-commit hook failed. Please fix the issues above before committing.${NC}"
    exit 1
fi

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