
#   temp failure:   5       -- could retry
#   logic failure:  4       -- fatal failure
#   interrupted:    3       -- abort by users

___x_cmd_coco_shcmd(){
    local cmd=""
    local risk="medium"       # low, medium, high, default to medium
    local timeout=""          # optional timeout in seconds

    arg:init:x  coco
    while [ $# -gt 0 ]; do
        case "$1" in
            --cmd)          cmd="$2";           arg:2:shift ;;
            --timeout)      timeout="$2";       arg:2:shift ;;
            --risk)         risk="$2";          arg:2:shift ;;
            *)              break ;;
        esac
    done

    [ -n "$cmd" ] || N=coco M="Please provide the command to execute" log:ret:64

    coco:info --risk "$risk" --m:command "$cmd" "Command to execute:" 2>/dev/tty >&2
    if [ "$risk" = "low" ]; then
        coco:info "Low risk command, skipping user confirmation"
    elif [ "$is_tool_force" = 1 ]; then
        coco:info "Tool Force mode enabled, skipping user confirmation"
    else
        local confirmid=""
        coco:info "Requesting user confirmation for command execution" 2>/dev/tty >&2

        ___x_cmd ui select confirmid "Confirm to execute the command." \
            "Yes" "No" 2>/dev/tty >&2 || return $?

        case "$confirmid" in
            1)  coco:info "User granted permission to execute command"
                ;;
            2)  coco:error "User permission denied for command execution"
                printf "[BREAK] 1\n" >> "$X_COCO_TOOL_ENACTCMD_FOLDER/log"
                return 1
                ;;
        esac
    fi

    if [ "$timeout" -gt 0 ]; then
        ___x_cmd_coco_shcmd_timeout "$timeout" "${SHELL:-/bin/sh}" -c "$cmd"
    else
        "${SHELL:-/bin/sh}" -c "$cmd"
    fi
}

___x_cmd_coco_shcmd_timeout(){
    local secs="$1"; shift
    (
        local pid=; local watcher=; local rc=;
        "$@" & pid=$!
        (
            sleep "$secs"
            if kill -0 "$pid" 2>/dev/null; then
                coco:info "sending signal TERM to command '$*'"
                ___x_cmd kill -r -s TERM "$pid" 2>/dev/null
                sleep 1
                kill -0 "$pid" 2>/dev/null && ___x_cmd kill -r -s KILL "$pid" 2>/dev/null
            fi
        ) & watcher=$!

        wait "$pid"
        rc=$?

        kill "$watcher" 2>/dev/null || true
        wait "$watcher" 2>/dev/null || true
        return $rc
    )
}
