#!/usr/bin/env bash
# Setup Git hooks for satag-amicron-entity-bundle
# Installs pre-commit and pre-push hooks for GitLab CI validation
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} $*"; }
log_success() { echo -e "${GREEN}✓${NC} $*"; }
log_warn() { echo -e "${YELLOW}⚠${NC} $*"; }
log_error() { echo -e "${RED}✗${NC} $*"; }

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
HOOKS_SOURCE="$PROJECT_ROOT/.githooks"
HOOKS_TARGET="$PROJECT_ROOT/.git/hooks"

log_info "Installing Git hooks for satag-amicron-entity-bundle..."

# Check if .githooks directory exists
if [ ! -d "$HOOKS_SOURCE" ]; then
    log_error ".githooks directory not found at: $HOOKS_SOURCE"
    exit 1
fi

# Check if .git directory exists
if [ ! -d "$PROJECT_ROOT/.git" ]; then
    log_error "Not a git repository. Run this from project root."
    exit 1
fi

# Install hooks
INSTALLED=0
SKIPPED=0

for hook_file in "$HOOKS_SOURCE"/*; do
    if [ -f "$hook_file" ]; then
        hook_name=$(basename "$hook_file")
        target_file="$HOOKS_TARGET/$hook_name"
        
        # Check if hook already exists
        if [ -f "$target_file" ]; then
            log_warn "Hook already exists: $hook_name (backing up as $hook_name.bak)"
            cp "$target_file" "$target_file.bak"
        fi
        
        # Copy and make executable
        cp "$hook_file" "$target_file"
        chmod +x "$target_file"
        
        log_success "Installed: $hook_name"
        ((INSTALLED++))
    fi
done

echo ""
log_success "Git hooks installation complete!"
log_info "  Installed: $INSTALLED hook(s)"
log_info "  Location: $HOOKS_TARGET"

echo ""
log_info "Hooks installed:"
log_info "  • pre-commit: Validates .gitlab-ci.yml with 'glab ci lint'"
log_info "  • pre-push: Optional local pipeline validation"

echo ""
log_info "To bypass hooks temporarily: git commit --no-verify"
log_warn "Only bypass in emergencies - hooks catch errors early!"

exit 0