# shellcheck shell=dash
___X_CMD_CHAT_MINION_DIR="$___X_CMD_ROOT_DATA/chat/data/minion"

xrc:mod:lib     chat    minion/path

___x_cmd_chat_minion(){
    [ $# -gt 0 ] || set -- ls

    local op="$1";      shift
    case "$op" in
        -h|--help)
            ___x_cmd help -m chat minion ;;
        ls|which_|which|create|rm|prompt|getitem)
            ___x_cmd_chat_minion_"$op" "$@" ;;
        *)
            N=chat M="Unsupported subcmd ==> $op" log:ret:64 ;;
    esac
}

___x_cmd_chat_minion_ls(){
    # ___x_cmd_func_consumer worker 'x fsiter $1'
    # ___x_cmd_chat_minion_path_for worker

    ___x_cmd_chat_minion_path_for eval 'x fsiter $e'
}

# path which
___x_cmd_chat_minion_path_which_(){
    x_="$___X_CMD_ROOT_MOD/chat/lib/minions/$1.minion.yml"
    [ -f "$x_" ]
}

___x_cmd_chat_minion_cache_json_(){
    local json_cache=
    local minion="$1"
    if [ -f "$minion" ]; then
        x_=; ___x_cmd_abspath_ "$minion" || return $?
        json_cache="${___X_CMD_ROOT_CACHE}/chat/minion$x_"
    elif ___x_cmd_chat_minion_path_which_ "$minion"; then
        json_cache="${___X_CMD_ROOT_CACHE}/chat/minion$x_"
        minion="$x_"
    else
        chat:error "Not found the minion file of $minion"
        return 1
    fi
    x_=""
    chat:debug "json_cache[$json_cache]"
    ___x_cmd ensurefp "$json_cache"
    < "$minion" ___x_cmd y2j > "$json_cache" || return $?
    x_="$json_cache"
    [ -f "$x_" ]
}

___x_cmd_chat_minion_which(){
    local x_=""
    ___x_cmd_chat_minion_path_which_ "$@" || return $?
    printf "%s\n" "$x_"
}

___x_cmd_chat_minion_prompt(){
    local x_=""
    ___x_cmd_chat_minion_path_which_ "$@" || {
        [ -f "$1" ] || N=chat M="No such minion found ==> $1" log:ret:64
        x_="$1"
    }
    # Using json to handle it
    ___x_cmd y2j <"$x_" | command awk -f "$___X_CMD_CHAT_MINION_DIR/$x_/prompt.awk"
}

# Using yml attribute
___x_cmd_chat_minion_create(){
    :
}

___x_cmd_chat_minion_rm(){
    :
}

___x_cmd_chat_minion_getitem(){
    local minion_json_cache="$1"
    local itemname="$2"

    ___x_cmd cawk -E itemname,session,history_num,minion,model,chatid,minion_json_cache,system,type,filelist_attach,temperature,seed,maxtoken,def_model   \
        -E cfg_history_num,cfg_session,cfg_minion,cfg_model,cfg_maxtoken,cfg_seed,cfg_temperature,cfg_ctx \
        -m j/json,j/jiter,j/jcp,re,u/unicode \
        -f "$___X_CMD_ROOT_MOD/chat/lib/awk/util.awk"   \
        -f "$___X_CMD_ROOT_MOD/chat/lib/awk/minion.awk" \
        -f "$___X_CMD_ROOT_MOD/chat/lib/awk/minion_getitem.awk"
}
