# shellcheck shell=dash disable=SC2034

___x_cmd_hub_cc(){
    [ $# -gt 0 ] || ___x_cmd help -m hub cc
    case "$1" in
        -h|--help)      ___x_cmd help -m hub cc  "$@" ;;
        *)              ___x_cmd_hub_cc_ "$@";;
    esac
}

arg:init hub
___x_cmd_hub_cc_(){
    local file_path
    local x_os
    local artifacts
    local run
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)      ___x_cmd help -m hub cc  "$@" ;;
            --os)           x_os="$2";      arg:2:shift;;
            -o|--output)    artifacts="$2"; arg:2:shift;;
            # --run)        run="true";     arg:2:shift;;
            *)  file_path="$1";      shift;;
        esac
    done
    local x_=""; ___x_cmd_hub_cc_os_ "${x_os}" || return 1
    x_os="$x_"
    ___x_cmd_hub_cc_file_ "${file_path}" || return

    local file_name
    file_name="$(basename "${file_path}")"
    file_name="${file_name%.*}"
    if ___x_cmd os is win;then
        file_path="$(___x_cmd pwsh path linux_to_win "${file_path}")"
        [ -z "${artifacts}" ] || artifacts="$(___x_cmd pwsh path linux_to_win "${artifacts}")"
    fi
    ___x_cmd_hub_cc_build_ "${file_path}" "${artifacts}"

}

___x_cmd_hub_cc_os_(){
    local x_os="$1"
    if [ -z "${os}" ];then
        local os_name
        local os_arch
        os_name=$(___x_cmd os name)
        os_arch=$(___x_cmd os arch)
        x_="${os_name}/${os_arch}"
    else
        x_="${x_os}"
    fi
}

___x_cmd_hub_cc_file_(){
    local file_path="$1"
    [ -f "${file_path}" ] || N=hub M="File does not exist, please enter the correct file path" log:ret:64
    local file_type="${file_path##*.}"
    case "$file_type" in
        go|zig|gop|rs|xgo) hub:debug "file_type: ${file_type}"     ;;
        *) N=hub M="The script file does not support or does not recognize the script type" log:ret:64 ;;
    esac
}

___x_cmd_hub_cc_build_(){
    local file_path="$1"
    local artifacts="$2"
    local url="https://cc.hub.x-cmd.com"
    local hub_token
    hub_token="$(___x_cmd_hub_token)"
    local x_=; ___x_cmd_hub_cc_cerify_
    local cc_token="${x_}"
    [ -n "${cc_token}" ] || N=hub M="Failed to obtain token" log:ret:64
    ___x_cmd curl -X POST -o "${file_path%.*}" "${url}/xcmd/build" \
            --form "file=@\"${file_path}\"" \
            --form "os_name=\"${x_os}\"" \
            --form "run=\"false\""  \
            --form "hub_token"="\"${hub_token}\""   \
            --form "cc_token"="\"${cc_token}\"" || return 1
    [ -z "$artifacts" ] || [ -f "${artifacts}" ] || ___x_cmd mv "${file_path%.*}" "${artifacts}"
}

___x_cmd_hub_cc_cerify_(){
    x_="$(___x_cmd_hub_cfg --get cc_token)"
    if [ -z "${x_}" ]; then
        local url="https://verify.hub.x-cmd.com"
        x_="$(___x_cmd curl -X GET "${url}/api/v0/verify/$hub_token")"
        ___x_cmd_hub_cfg --set cc_token="${x_}"
    fi
}