#!/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; }

# 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