# shellcheck shell=dash

___x_cmd_claude_mthreads(){
    local op="$1"
    case "$op" in
        -h|--help)      ___x_cmd help -m claude mthreads; return 0 ;;
        --cfg)          ___x_cmd mthreads --cfg "$@";     return 0 ;;
        --)             shift ;;
    esac

    local model=""
    local apikey=""
    local endpoint=""
    local x_=""

    claude:provider:fetch:init
    ___x_cmd_claude_mthreads___fetch_   || return $?

    ANTHROPIC_API_KEY="" API_TIMEOUT_MS="$x_timeout"        \
        ___x_cmd_claude_other___use     mt                \
        "$x_url" "$x_apikey" "$x_model" "$x_fastmodel" "$x_nonessential_traffic" "$x_effortlevel" "$@"
}

___x_cmd_claude_mthreads___fetch_(){
    local model=""
    local apikey=""
    local codingplan_apikey=""
    local endpoint=

    ___x_cmd mthreads --cur model:= apikey:= codingplan_apikey:= endpoint:= 2>/dev/null

    local apikey_to_request=""
    if [ -n "$codingplan_apikey" ]; then
        apikey_to_request="$codingplan_apikey"
        endpoint="https://coding-plan-endpoint.kuaecloud.net"
    elif [ -n "$apikey" ]; then
        apikey_to_request="$apikey"
        [ -n "$endpoint" ] || endpoint="https://coding-plan-endpoint.kuaecloud.net"
    else
        claude:warn \
            --tip1 'x mthreads --cfg'                       \
            --tip2 'x mthreads --cfg codingplan_apikey=<YOUR-CODING-PLAN-API-KEY>' \
            --tip2 'x mthreads --cfg apikey=<YOUR-API-KEY>' \
            "Please setup MOORE THREADS API-KEY."

        if ___x_cmd_runmode_allow_manual; then
            ___x_cmd mthreads --cfg|| return $?
            ___x_cmd mthreads --cur model:= apikey:= codingplan_apikey:= endpoint:= 2>/dev/null
            x_apikey="$apikey"
            [ -z "$codingplan_apikey" ] || x_apikey="$codingplan_apikey"
        fi
        [ -n "$x_apikey" ] || N=claude M="Failed to retrieve API-KEY. Please check your configuration." log:ret:1
    fi

    x_url="$endpoint"
    x_apikey="$apikey_to_request"

    x_model="${model}"
    [ -n "$x_model" ] || x_model="GLM-4.7"

    x_fastmodel="${x_model}"
    x_effortlevel=auto

    x_timeout="${API_TIMEOUT_MS:-"3000000"}"
}
