# shellcheck shell=dash disable=SC2317

___x_cmd_cmdnotfound_init(){

case "${___X_CMD_SHELL}" in
    zsh)
command_not_found_handler(){
    ___x_cmd_cmdnotfound_handle "$@"
}
        ;;
    bash)
        case "$BASH_VERSION" in
            1*|2*|3*)
                ___x_cmd_cmdnotfound_repl
                return
            ;;
        esac

command_not_found_handle() {
    ___x_cmd_cmdnotfound_handle "$@"
}
        ;;
    *)
        ___x_cmd_cmdnotfound_repl
esac

}


# Ask the user to use repl
___x_cmd_cmdnotfound_repl(){
    :
    x:info "There is no command_not_found hook in current shell[${___X_CMD_SHELL}]."
}

# Thank: https://unix.stackexchange.com/questions/691258/bash-zsh-hook-add-to-path-only-if-no-matching-file-found

___x_cmd_cmdnotfound_handle(){
    if x meta hasmod "$1"; then
        local ___X_CMD_XRC_SET_MAIN
        xrc "$1";
        if [ -z "${___X_CMD_XRC_SET_MAIN}" ]; then
            x:error "Module ${1} is not runnable"
            return 1
        fi
        shift; "${___X_CMD_XRC_SET_MAIN}" "$@"
        return
    fi

    # TODO: for those which doesn't want to access web source too much, we should skip

    x:info "Module[$1] Not found. Now searching x package."
    local x_; if x pkg cmd2pkg_ "$1"; then
        x pkg init "$x_"
        if x runnable "$1"; then
            x:error "Module $1 is not runnable"
        fi
        "$@"
        return
    fi

    # x:info "Command[$1] Not found in any x package. Now searching x install."
    # local x_; if x install cmd2install_ "$1"; then
    #     x install "$x_"
    #     if x runnable "$1"; then
    #         x:error "Module $1 is not runnable"
    #     fi
    #     "$@"
    #     return
    # fi

    # TODO: Do the fuzzy search

    x:info "Sorry. We don't find any command in x-cmd module, package."
    # TODO: Do you want to search brew, apt, dnf, or other?
    "$@"
}

