#!/usr/bin/env bash
# Pre-commit hook: Validate GitLab CI configuration when modified
# Part of satag-amicron-entity-bundle
set -euo pipefail

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

# Log functions
log_info() { echo -e "${BLUE}ℹ${NC} $*" >&2; }
log_success() { echo -e "${GREEN}✓${NC} $*" >&2; }
log_warn() { echo -e "${YELLOW}⚠${NC} $*" >&2; }
log_error() { echo -e "${RED}✗${NC} $*" >&2; }

# Function to run ECS fix on staged PHP files
run_ecs_fix() {
    log_info "Checking for staged PHP files..."
    
    # Get list of staged PHP files
    STAGED_PHP_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.php$' || true)
    
    if [ -z "$STAGED_PHP_FILES" ]; then
        log_info "No PHP files staged, skipping ECS fix"
        return 0
    fi
    
    log_info "Running ECS fix on staged PHP files..."
    
    # Run ECS fix via Docker
    if docker compose exec -T --user=application -w /app app_server \
        ./vendor-bin/ecs/vendor/bin/ecs check --fix; then
        log_success "ECS fix completed successfully"
        
        # Re-stage files that were fixed
        echo "$STAGED_PHP_FILES" | while read -r file; do
            if [ -f "$file" ]; then
                git add "$file"
            fi
        done
        
        log_info "Re-staged fixed PHP files"
    else
        log_error "ECS fix failed!"
        log_error "Please fix the issues above and try again"
        log_warn "To bypass this check (NOT recommended): git commit --no-verify"
        return 1
    fi
}

# Run ECS fix first
if ! run_ecs_fix; then
    exit 1
fi

# Check if .gitlab-ci.yml was modified in staged changes
if ! git diff --cached --name-only | grep -q '\.gitlab-ci\.yml$'; then
    log_info "No GitLab CI configuration changes detected, skipping validation"
    exit 0
fi

log_info "GitLab CI configuration modified, validating..."

# Check if glab is available
if ! command -v glab &> /dev/null; then
    log_error "glab CLI not found. Install from: https://gitlab.com/gitlab-org/cli"
    log_error "  brew install glab  (macOS)"
    log_error "  Or download from releases page"
    exit 1
fi

# Check if glab is authenticated
if ! glab auth status &> /dev/null; then
    log_error "glab not authenticated. Run: glab auth login"
    exit 1
fi

# Validate GitLab CI YAML syntax
log_info "Running: glab ci lint"
if glab ci lint; then
    log_success "GitLab CI configuration is valid"
else
    echo ""
    log_error "GitLab CI YAML validation failed!"
    log_error "Fix the errors above and try again"
    log_warn "To bypass this check (NOT recommended): git commit --no-verify"
    exit 1
fi

exit 0