# shellcheck shell=dash

___x_cmd_whisper_model_download(){
    local x_=""
    ___x_cmd_whisper_model_download_ "$@" || return 1
    printf "%s" "${x_}"
}

___x_cmd_whisper_model_download_(){
    local modelName="${1}"
    local url="ggerganov/whisper.cpp/resolve/main"

    [ -n "$modelName" ] || {
        ___x_cmd_runmode_allow_chatty || N=whisper M="modelName is empty" log:ret:1

        local x_=
        ___x_cmd_whisper_model_ls___app_
        [ -n "$x_" ] || return 1
        modelName="$x_"
    }

    local tmpfp="$___X_CMD_ROOT_TMP/model/${modelName}.bin"
    ___x_cmd ensurefp "$tmpfp"

    local tgtfp="$___X_CMD_ROOT_DATA/model/${modelName}.bin"

    [ -f "$tgtfp" ] || (
        ___x_cmd huggingface --publicdownload "${url}"/"ggml-${modelName}.bin" "$tmpfp" || {
            ___x_cmd_whisper_model_download___clean
            return
        }
        ___x_cmd mv "$tmpfp" "$tgtfp"
    )

    # TODO: in the future, check the hash
    x_="$tgtfp"
}

___x_cmd_whisper_model_download___clean(){
    ___x_cmd rmrf "$tmpfp"
    whisper:error "download model $modelName failed"
    return 1
}
