#!/bin/bash

# Pre-commit hook for Ultimate Multisite
# Runs PHPCS and PHPStan on staged PHP files
# Runs ESLint and Stylelint on staged JS/CSS files

set -e

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

echo -e "${GREEN}Running pre-commit checks...${NC}"

HAS_ERRORS=0

# =============================================================================
# PHP Checks (PHPCS and PHPStan)
# =============================================================================

# Get list of staged PHP files
STAGED_PHP_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.php$' | grep -v '^vendor/' | grep -v '^tests/' || true)

if [ -n "$STAGED_PHP_FILES" ]; then
    echo -e "${YELLOW}Checking PHP files:${NC}"
    echo "$STAGED_PHP_FILES"

    # Check if composer dependencies are installed
    if [ ! -f "vendor/bin/phpcs" ] || [ ! -f "vendor/bin/phpstan" ]; then
        echo -e "${RED}Error: Please run 'composer install' to install development dependencies.${NC}"
        exit 1
    fi

    # Run PHPCS on staged files
    echo -e "${YELLOW}Running PHPCS...${NC}"
    HAS_PHPCS_ERRORS=0
    PHPCS_FAILED_FILES=""
    for FILE in $STAGED_PHP_FILES; do
        if [ -f "$FILE" ]; then
            if ! vendor/bin/phpcs --colors "$FILE"; then
                PHPCS_FAILED_FILES="$PHPCS_FAILED_FILES $FILE"
                HAS_PHPCS_ERRORS=1
            fi
        fi
    done

    # If PHPCS found errors, try to auto-fix them with PHPCBF
    if [ $HAS_PHPCS_ERRORS -ne 0 ]; then
        echo -e "${YELLOW}PHPCS found errors. Running PHPCBF to auto-fix...${NC}"

        FIXED_FILES=""
        for FILE in $PHPCS_FAILED_FILES; do
            if [ -f "$FILE" ]; then
                # Run phpcbf (it returns 1 if it made changes, 0 if no changes needed)
                vendor/bin/phpcbf "$FILE" || true

                # Re-run phpcs to check if the file is now clean
                if vendor/bin/phpcs --colors "$FILE" 2>&1; then
                    echo -e "${GREEN}✓ Auto-fixed: $FILE${NC}"
                    FIXED_FILES="$FIXED_FILES $FILE"
                    # Stage the fixed file
                    git add "$FILE"
                else
                    echo -e "${RED}✗ Could not fully fix: $FILE${NC}"
                fi
            fi
        done

        # Re-check if there are still errors after auto-fixing
        HAS_PHPCS_ERRORS=0
        for FILE in $STAGED_PHP_FILES; do
            if [ -f "$FILE" ]; then
                vendor/bin/phpcs --colors "$FILE" > /dev/null 2>&1 || HAS_PHPCS_ERRORS=1
            fi
        done

        if [ $HAS_PHPCS_ERRORS -eq 0 ]; then
            echo -e "${GREEN}All PHPCS errors have been auto-fixed!${NC}"
        fi
    fi

    # Run PHPStan on staged files
    echo -e "${YELLOW}Running PHPStan...${NC}"
    HAS_PHPSTAN_ERRORS=0
    PHPSTAN_FILES=""
    for FILE in $STAGED_PHP_FILES; do
        if [ -f "$FILE" ] && [[ "$FILE" =~ ^inc/ ]]; then
            PHPSTAN_FILES="$PHPSTAN_FILES $FILE"
        fi
    done

    if [ -n "$PHPSTAN_FILES" ]; then
        vendor/bin/phpstan analyse --no-progress --error-format=table $PHPSTAN_FILES || HAS_PHPSTAN_ERRORS=1
    fi

    # Track PHP errors
    if [ $HAS_PHPCS_ERRORS -ne 0 ] || [ $HAS_PHPSTAN_ERRORS -ne 0 ]; then
        HAS_ERRORS=1
        if [ $HAS_PHPCS_ERRORS -ne 0 ]; then
            echo -e "${YELLOW}Some PHPCS errors could not be auto-fixed. Please fix them manually.${NC}"
            echo -e "${YELLOW}Run 'vendor/bin/phpcs' to see remaining errors.${NC}"
        fi
    fi
else
    echo -e "${GREEN}No PHP files to check.${NC}"
fi

# =============================================================================
# JS/CSS Checks (ESLint and Stylelint via lint-staged)
# =============================================================================

# Get list of staged JS/CSS files
STAGED_JS_CSS_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|css)$' | grep -v '\.min\.' || true)

if [ -n "$STAGED_JS_CSS_FILES" ]; then
    echo -e "${YELLOW}Checking JS/CSS files:${NC}"
    echo "$STAGED_JS_CSS_FILES"

    if command -v npx &> /dev/null; then
        echo -e "${YELLOW}Running lint-staged...${NC}"
        if ! npx lint-staged; then
            HAS_ERRORS=1
            echo -e "${RED}lint-staged found errors.${NC}"
        fi
    else
        echo -e "${YELLOW}Warning: npx not found. Skipping JS/CSS linting.${NC}"
        echo -e "${YELLOW}Run 'npm install' to set up the development environment.${NC}"
    fi
else
    echo -e "${GREEN}No JS/CSS files to check.${NC}"
fi

# =============================================================================
# Final Result
# =============================================================================

if [ $HAS_ERRORS -ne 0 ]; then
    echo -e "${RED}Pre-commit checks failed!${NC}"
    echo -e "${YELLOW}To bypass these checks, use: git commit --no-verify${NC}"
    exit 1
fi

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