# shellcheck shell=dash
___x_cmd_wttr___main(){
    [ "$#" -gt 0 ] || set -- --app

    local ___X_CMD_WTTR_VIEW=""

    while [ "$#" -gt 0 ]; do
        local op="$1"; shift
        case "$op" in
            -h|--help)      ___x_cmd_wttr___help;           return ;;
            :help)          ___x_cmd_wttr___api :help;      return ;;

            --app)          ___x_cmd_wttr___app "$@";       return  ;;
            --api)          ___x_cmd_wttr___api "$@";       return ;;

            --unit)         ___x_cmd_wttr___unit "$1";      return ;;

            -n|--narrow)    ___X_CMD_WTTR_VIEW=n ;;

            *)              ___x_cmd_wttr___app "$op" "$@"; return ;;
        esac
    done
}

___x_cmd_wttr___help(){
    x help -m wttr "$@"  >&2
    return 1
}

___X_CMD_WTTR_DATA_OPTION="$___X_CMD_ROOT_DATA/wttr/OPTION"

___x_cmd_wttr___unit(){
    # uscs/metric/METRIC

    x ensurefp "$___X_CMD_WTTR_DATA_OPTION"
    case "$1" in
        uscs)    printf "%s\n" "u" >"$___X_CMD_WTTR_DATA_OPTION"    ;;
        metric)  printf "%s\n" "m" >"$___X_CMD_WTTR_DATA_OPTION"    ;;
        METRIC)  printf "%s\n" "M" >"$___X_CMD_WTTR_DATA_OPTION"    ;;
        adapt)   printf "%s\n" "" >"$___X_CMD_WTTR_DATA_OPTION"     ;;

        -h|--help)      ___x_cmd_wttr___help  --unit;        return ;;
        *)       N=x M="Unknown option ==> $1" log:ret:64
    esac
}

___x_cmd_wttr___app(){
    local option=""
    if [ -f "$___X_CMD_WTTR_DATA_OPTION" ]; then
        option="$(___x_cmd_cmds_cat "$___X_CMD_WTTR_DATA_OPTION")"
    fi

    local city="${1}"

    local col; col="$(x ui col)"
    if [ "$col" -lt 63 ]; then      x:error "terminal col size require greater than or equal to 63"
    elif [ "$col" -lt 126 ]; then   ___x_cmd_wttr___api "${city}?${___X_CMD_WTTR_VIEW:-n}${option}"
    else                            ___x_cmd_wttr___api "${city}?${___X_CMD_WTTR_VIEW}${option}"
    fi
}

___x_cmd_wttr___api(){
    case "$1" in
        -h|--help)      ___x_cmd_wttr___help  --api;        return ;;
        ?*)             if [ -z "$LANG" ]; then         command curl                                    "https://wttr.in/$1"
                        else                            command curl -H "Accept-Language: ${LANG%_*}"   "https://wttr.in/$1" ; return
                        fi
                        ;;
        *)              N=x M="Unknown option ==> $1" log:ret:64
    esac



}
