# shellcheck shell=dash
___x_cmd_llmf_model_export(){
    case "$1" in
        -h|--help)  ___x_cmd help -m llmf model export; return ;;
    esac

    local model="$1"
    local fp="$2"
    local x_=

    ___x_cmd_llmf___model_confirm "$model" || {
        ___x_cmd_runmode_allow_chatty || return $?
        llmf:info "Select the model to export from the local"
        x_=; ___x_cmd_llmf_model_ls___app_ || return $?
        model="$x_"
    }

    x_=; ___x_cmd_llmf_model_which_ "$model" || N=llmf M="Not found this model" log:ret:1
    local model_path="$x_"
    llmf:info --model "$model" --export-path "$fp"

    [ -n "$fp" ] || N=llmf M="Please provide the export file path" log:ret:64
    ___x_cmd ui yesno "Confirm exporting $model_path file to $fp" || return $?
    ___x_cmd ensurefp "$fp"
    ___x_cmd_llmf_model___lncp "$model_path" "$fp" || return $?
    llmf:info "Export successful"
}

___x_cmd_llmf_model_import(){
    case "$1" in
        -h|--help)  ___x_cmd help -m llmf model import; return ;;
    esac

    local fp="$1"
    local model="$2"
    [ -f "$fp" ] || N=llmf M="[filepath=$fp] is not a file" log:ret:64

    ___x_cmd_llmf___model_confirm "$model" || {
        ___x_cmd_runmode_allow_chatty || return $?
        llmf:info "Select which model to import into"
        x_=; ___x_cmd_llmf_model_ls___app_ || return $?
        model="$x_"
    }
    llmf:info --model "$model" --import-file "$fp"

    local model_path="$___X_CMD_LLMF_MODEL_DATA_CACHE/$model"
    ___x_cmd ensurefp "$model_path"
    [ ! -f "$model_path" ] || {
        ___x_cmd ui yesno "[model_path=$model_path] already exists, overwrite it?" || return $?
        ___x_cmd rmrf "$model_path" || return $?
    }

    ___x_cmd_llmf_model___lncp "$fp" "$model_path" || return $?
    llmf:info "Import successful"
}

___x_cmd_llmf_model___lncp(){
    local src="$1"
    local tgt="$2"
    ___x_cmd_cmds ln "$src" "$tgt" 2>/dev/null || {
        llmf:info "fail to use hard link, fall back to using cp"
        ___x_cmd_cmds cp "$src" "$tgt" || {
            llmf:warn --src "$src" --tgt "$tgt" "Fail to copy"
            return 1
        }
    }
}
