# shellcheck shell=dash disable=SC2034

xrc cfgy
___x_cmd_ollama_cfg(){
    [ "$#" -gt 0 ] || {
        ___x_cmd_ollama_init
        return
    }

    local op="$1"; shift
    case "$op" in
        -h|--help)      ___x_cmd help -m ollama --cfg ;;
        endpoint=*)     ___x_cmd_ollama_cfg___invoke "$op" "$@"
                        ! ___x_cmd_ollama_has_endpoint 2>/dev/null >&2 || ___x_cmd chat --setalias ollama o
                        ;;
        *)              ___x_cmd_ollama_cfg___invoke "$op" "$@" ;;
    esac
}

___x_cmd_ollama_cur(){
    local X_help_cmd=; X_help_cmd='x help -m ollama --cur' help:arg:parse
    ___x_cmd_ollama_cfg --current "$@"
}

___x_cmd_ollama_init(){
    local cur_ctx=;local cur_temperature=;local cur_endpoint=;

    if [ -f "$(___x_cmd_ollama_cur --get config)" ]; then
        ___x_cmd_ollama_cur  cur_endpoint:=endpoint cur_temperature:=temperature  cur_ctx:=ctx 2>/dev/null
    fi

    ___x_cmd_ollama_cfg___invoke --init ${cur_model:+"--ctrl_exit_strategy"}                                             \
        temperature "Set temperature (optional)"       "${cur_temperature:-"0.3"}"                       --              \
        ctx         "Set num_ctx (optional)"           "${cur_ctx:-"8000"}"                              --              \
        endpoint    "Set endpoint (optional)"           "$cur_endpoint" || return $?

    ! ___x_cmd_ollama_has_endpoint 2>/dev/null >&2 || ___x_cmd chat --setalias ollama o
}

___x_cmd_ollama_has_endpoint(){
    local apikey=
    ___x_cmd_ollama_cur     endpoint:= 2>/dev/null
    [ -n "$apikey" ] || {
        ollama:error "Please setting up your endpoint first ==> 'x ollama --cfg endpoint=<your endpoint>'"
        return 1
    }
}

# Config setting the key.
# set the default prompt

___X_CMD_OLLAMA_CFG_VARLIST="endpoint,temperature,ctx"
___x_cmd_ollama_cfg___invoke(){
    ___x_cmd_cfgy_obj                                                \
        --prefix            ___X_CMD_OLLAMA_CFG_DATA                \
        --default-config    "${___X_CMD_ROOT_CFG}/ollama/X.cfg.yml" \
        --current-config    "${___X_CMD_OLLAMA_LOCAL_CONFIG}"       \
        --current-profile   "${___X_CMD_OLLAMA_LOCAL_PROFILE}"      \
        --varlist           "$___X_CMD_OLLAMA_CFG_VARLIST"          \
        "$@"
}

