# shellcheck shell=sh
# shellcheck disable=SC3043,2034

xrc cfgy
___x_cmd_gh_cfg(){
    param:void
    [ "$#" -gt 0 ] || {
        _____x_cmd_gh_help --cfg
        return 64
    }

    local op="$1"; shift
    case "$op" in
        -h|--help)  ___x_cmd help -m gh --cfg ;;
        token=*)    ___x_cmd_gh_cfg___invoke "$op" "$@"
                    ! ___x_cmd gh model --has-apikey 2>/dev/null >&2 || ___x_cmd chat --setalias gh gh gh-model
                    ;;
        *)          ___x_cmd_gh_cfg___invoke "$op" "$@" ;;
    esac
}

___x_cmd_gh_cur(){
    param:void
    local X_help_cmd=; X_help_cmd='___x_cmd help -m gh --cur' help:arg:parse
    ___x_cmd_gh_cfg___invoke --current "$@"
}


___x_cmd_gh_init(){
    param:void
    local cur_token=; local cur_owner=; local cur_endpoint=; local cur_web_endpoint=
    if [ -f "$(___x_cmd_gh_cur --get config)" ]; then
        ___x_cmd_gh_cur cur_token:=token cur_owner:=owner cur_endpoint:=endpoint cur_web_endpoint:=web_endpoint 2>/dev/null
    fi

    local X_help_cmd=; X_help_cmd='___x_cmd help -m gh init' help:arg:parse
    ___x_cmd_gh_cfg___invoke --init \
        token           "Set up GitHub token"           "${cur_token}"      '=~*'  "^g.*"           -- \
        endpoint        "Set up endpoint"               "${cur_endpoint:-"https://api.github.com"}" -- \
        web_endpoint    "Set up web_endpoint"           "${cur_web_endpoint:-"https://github.com"}" -- \
        owner           "Set up owner name (optional)"  "${cur_owner}"      '=~'   "^[^:\\/ ]" || return $?

    if ___x_cmd ui yesno "Whether to set the default Github model ?" ; then
        ___x_cmd_gh_model ls --app  || return $?
    fi

    ! ___x_cmd gh model --has-apikey 2>/dev/null >&2 || ___x_cmd chat --setalias gh gh gh-model
}

# TODO: ___X_CMD_GH_CFG_VARLIST="token,owner,endpoint,web_endpoint,repo,issue,pr"
___X_CMD_GH_CFG_VARLIST="token,owner,endpoint,web_endpoint,repo,ai_model,ai_maxtoken,ai_seed,ai_temperature,ai_proxy"
___x_cmd_gh_cfg___invoke(){
    # shellcheck disable=2154
    ___x_cmd_cfgy_obj   \
        --prefix            ___X_CMD_GH_CFG_DATA                    \
        --default-config    "${___X_CMD_ROOT_CFG}/gh/X.cfg.yml"     \
        --current-config    "${___X_CMD_GH_LOCAL_CONFIG}"           \
        --current-profile   "${___X_CMD_GH_LOCAL_PROFILE}"          \
        --varlist           "$___X_CMD_GH_CFG_VARLIST"              \
        "$@"
}
