#!/usr/bin/env bash
# Initialize common libraries
# Usage: source "$SCRIPT_DIR/lib/init.sh"
#
# This script loads all common libraries in the correct order.
# Individual scripts can source this instead of sourcing each library separately.

# Get lib directory (this file's directory)
LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Get script directory if not set (try to get from calling script)
if [ -z "${SCRIPT_DIR:-}" ]; then
    # Try to get from calling script (BASH_SOURCE[2] because init.sh adds one level)
    if [ -n "${BASH_SOURCE[2]:-}" ]; then
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[2]}")" && pwd)"
    elif [ -n "${BASH_SOURCE[1]:-}" ]; then
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[1]}")" && pwd)"
    fi
fi

# Source libraries in order
source "${LIB_DIR}/common/paths.sh"
source "${LIB_DIR}/common/colors.sh"
source "${LIB_DIR}/common/logging.sh"
source "${LIB_DIR}/common/utils.sh"
source "${LIB_DIR}/common/env.sh"
source "${LIB_DIR}/common/metadata.sh"
source "${LIB_DIR}/common/validation.sh" 2>/dev/null || true
source "${LIB_DIR}/common/retry.sh" 2>/dev/null || true
source "${LIB_DIR}/common/error-handling.sh" 2>/dev/null || true
source "${LIB_DIR}/config/env.sh"
source "${LIB_DIR}/config/regions.sh"
source "${LIB_DIR}/azure/cli.sh" 2>/dev/null || true
source "${LIB_DIR}/forge-scope.sh"

# Log that libraries are loaded (only in debug mode)
# Use default 1 if LOG_LEVEL is unset or not numeric (e.g. from .env)
_ll="${LOG_LEVEL:-1}"
[[ "$_ll" =~ ^[0-9]+$ ]] && [ "$_ll" -le 0 ] && log_debug "Common libraries loaded from ${LIB_DIR}" || true
