#!/bin/bash
# Pre-commit hook for Authly
# Runs ruff linting and formatting checks before allowing commit

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[PRE-COMMIT]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[PRE-COMMIT]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[PRE-COMMIT]${NC} $1"
}

print_error() {
    echo -e "${RED}[PRE-COMMIT]${NC} $1"
}

# Check if uv is available
if ! command -v uv >/dev/null 2>&1; then
    print_error "uv is not installed or not in PATH"
    print_error "Please install uv: curl -LsSf https://astral.sh/uv/install.sh | sh"
    exit 1
fi

print_status "Running pre-commit checks..."

# Get list of staged Python files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E "\.(py)$" || true)

if [ -z "$STAGED_FILES" ]; then
    print_status "No Python files staged for commit"
    exit 0
fi

print_status "Checking staged Python files:"
echo "$STAGED_FILES" | sed 's/^/  - /'
echo

# Run ruff check on staged files
print_status "Running ruff check..."
if uv run ruff check $STAGED_FILES; then
    print_success "Ruff check passed!"
else
    if [[ "${AUTHLY_NO_AUTO_FIX:-false}" == "true" ]]; then
        print_error "Ruff check failed!"
        print_error "Please fix the linting errors and try again"
        print_error "You can run: uv run ruff check --fix $STAGED_FILES"
        exit 1
    else
        print_status "Auto-fixing ruff issues..."
        if uv run ruff check --fix $STAGED_FILES; then
            # Re-stage the fixed files
            for file in $STAGED_FILES; do
                git add "$file"
            done
            print_success "Ruff issues auto-fixed and re-staged!"
        else
            print_error "Some ruff issues could not be auto-fixed!"
            print_error "Please fix the remaining errors manually and try again"
            exit 1
        fi
    fi
fi

# Check if files need formatting
print_status "Checking code formatting..."
FORMAT_CHECK=$(uv run ruff format --check $STAGED_FILES 2>&1 || true)

if echo "$FORMAT_CHECK" | grep -q "Would reformat"; then
    print_warning "Some files need formatting:"
    echo "$FORMAT_CHECK" | grep "Would reformat" | sed 's/^/  - /'
    echo
    
    # Auto-format files (can be disabled with AUTHLY_NO_AUTO_FIX=true)
    if [[ "${AUTHLY_NO_AUTO_FIX:-false}" == "true" ]]; then
        print_error "Auto-formatting disabled by AUTHLY_NO_AUTO_FIX=true"
        print_error "Please run: uv run ruff format $STAGED_FILES"
        print_error "Then add the changes and commit again"
        exit 1
    else
        print_status "Auto-formatting files..."
        uv run ruff format $STAGED_FILES
        
        # Re-stage the formatted files
        for file in $STAGED_FILES; do
            if echo "$FORMAT_CHECK" | grep -q "$file"; then
                git add "$file"
                print_status "Re-staged formatted file: $file"
            fi
        done
        
        print_success "Files auto-formatted and re-staged!"
    fi
else
    print_success "Code formatting check passed!"
fi

# Optional: Run tests on staged files (uncomment if desired)
# print_status "Running tests..."
# if uv run pytest tests/ -x --tb=short; then
#     print_success "Tests passed!"
# else
#     print_error "Tests failed!"
#     exit 1
# fi

print_success "All pre-commit checks passed! 🎉"
exit 0