# bash_safe_run
# -------------
# Ejecutar comandos con manejo de errores y trap.
# Incluye safe_run, setup_error_trap y error_trap_handler.
#
# USO (sourced):
#   source bash_safe_run.sh
#   setup_error_trap
#   safe_run "go build ./..." "BUILD_FAILED" "La compilacion fallo"

SCRIPT_DIR_BASH_SAFE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR_BASH_SAFE/bash_log.sh"
bash_log_init

safe_run() {
    local cmd="$1"
    local error_code="${2:-COMMAND_FAILED}"
    local error_desc="${3:-El comando fallo: $cmd}"

    debug "Ejecutando: $cmd"

    if ! eval "$cmd"; then
        error "$error_desc ($error_code)"
        return 1
    fi

    return 0
}

setup_error_trap() {
    trap 'error_trap_handler $? $LINENO' ERR
}

error_trap_handler() {
    local exit_code=$1
    local line_number=$2

    if [ "$exit_code" -ne 0 ]; then
        echo ""
        error "El script fallo en la linea $line_number con codigo de salida $exit_code"
        echo -e "${GRAY}Consulta el log: ${ERROR_LOG_FILE:-/tmp/script-errors.log}${NC}"
        echo ""
    fi
}
