#!/usr/bin/env bash
# Common utility functions
# Usage: source "$SCRIPT_DIR/lib/common/utils.sh"

# Source colors if not already sourced
[ -z "${RED:-}" ] && source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/colors.sh"

# Check if command exists
command_exists() {
    command -v "$1" &> /dev/null
}

# Require command (exits if not found)
require_command() {
    local cmd="$1"
    local install_hint="${2:-}"
    
    if ! command_exists "$cmd"; then
        echo -e "${RED}Error: $cmd not found${NC}" >&2
        [ -n "$install_hint" ] && echo -e "${YELLOW}Hint: $install_hint${NC}" >&2
        exit 1
    fi
}

# Confirm action
confirm() {
    local prompt="${1:-Are you sure?}"
    local default="${2:-n}"
    
    if [ "$default" = "y" ]; then
        local options="[Y/n]"
    else
        local options="[y/N]"
    fi
    
    read -p "$(echo -e "${YELLOW}${prompt} ${options}: ${NC}")" -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]] || ([ "$default" = "y" ] && [[ -z $REPLY ]]); then
        return 0
    else
        return 1
    fi
}

# Wait for user input
press_enter_to_continue() {
    read -p "$(echo -e "${CYAN}Press Enter to continue...${NC}")"
}

# Print header box
print_header() {
    local title="$1"
    local width="${2:-80}"
    
    echo "╔$(printf '═%.0s' $(seq 1 $((width-2))))╗"
    printf "║ %-${width-4}s ║\n" "$title"
    echo "╚$(printf '═%.0s' $(seq 1 $((width-2))))╝"
    echo
}

# Print centered text
print_centered() {
    local text="$1"
    local width="${2:-80}"
    printf "%*s\n" $(((${#text} + width) / 2)) "$text"
}

# Trim whitespace
trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"  # Remove leading whitespace
    var="${var%"${var##*[![:space:]]}"}"  # Remove trailing whitespace
    echo "$var"
}

# Check if running in dry-run mode
is_dry_run() {
    [ "${DRY_RUN:-0}" = "1" ] || [ "${DRY_RUN:-0}" = "true" ]
}

