# shellcheck shell=dash

___x_cmd_weixin_bot_send(){
    local op="$1";shift

    ___X_CMD_WEIXIN_BOT_SENT_DATA="$___X_CMD_ROOT_DATA/weixin/bot/sent/data.tsv"

    case "$op" in
        -h|--help)  ___x_cmd_weixin___help bot send ; return 0 ;;
        --text|--raw)
            "___x_cmd_weixin_bot_send_${op#--}" "$@"
            ;;
        --image|--file|--video)
            ___x_cmd_weixin_bot_send_media "${op#--}" "$@"
            ;;
        *)  ___x_cmd_weixin_u_subcmd_invalid "bot send" "$op"
            ;;
    esac
}


___x_cmd_weixin_bot_send_text(){
    local json_output=""
    local fp=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -j|--json) json_output=1; shift ;;
            --fp)               fp=1; shift ;;
            -h|--help) ___x_cmd_weixin___help bot send --text; return 0 ;;
            *) break ;;
        esac
    done

    local text="$1"
    [ -n "$text" ] || N=weixin M="Text content required" log:ret:1

    local user_id=""
    ___x_cmd_weixin_cur user_id:= 2>/dev/null
    [ -n "$user_id" ] || N=weixin M="No login information obtained. Please scan the QR code to log in first. ``x weixin login``" log:ret:1

    local context_token
    if [ -f "$___X_CMD_WEIXIN_CONTEXT_TOKEN" ]; then
        read -r context_token < "$___X_CMD_WEIXIN_CONTEXT_TOKEN"
    fi

    [ -n "$context_token" ] || {
        weixin:warn "context_token is empty, send a message in WeChat to bind your account..."
        ___x_cmd_weixin_listen_once___ || return "$?"
        read -r context_token < "$___X_CMD_WEIXIN_CONTEXT_TOKEN"
        [ -n "$context_token" ] || {
            weixin:error "Failed to get context_token after retry"
            return 1
        }
        weixin:info "Bind successfully"
    }
    # Build and send message
    local msg_json
    msg_json=$(___x_cmd_cmds cat <<EOF
{
  "msg": {
    "to_user_id": "$user_id",
    "message_type": 2,
    "client_id":"$(___x_cmd rand uuid)",
    "message_state": 2,
    "context_token": "$context_token",
    "item_list": [
      {
        "type": 1,
        "text_item": { "text": "$( ___x_cmd_weixin___jqu "$text" )" }
      }
    ]
  },
  "base_info": { "channel_version": "1.0.2" }
}
EOF
)


    local resp; resp="$(printf "%s" "$msg_json" | ___x_cmd_weixin_u_curl POST "/ilink/bot/sendmessage" -d @-)"
    [ "$resp" = "{}" ] || {
        ___x_cmd_ui_tf false "Failed to send message:" "$resp"
        return 1
    }

    if [ -n "$fp" ]; then
        local x_; ___x_cmd date timestamp_
        local send_time="$x_"

        ___x_cmd ensurefp "$___X_CMD_WEIXIN_BOT_SENT_DATA"
        printf '%s\ttext\t%s\n' "$send_time" "$text" >> "$___X_CMD_WEIXIN_BOT_SENT_DATA" || {
            weixin:warn "Failed to save sent message to $___X_CMD_WEIXIN_BOT_SENT_DATA"
        }
    fi

    ___x_cmd_ui_tf true "Sent text message successfully"
}

___x_cmd_weixin_bot_send_raw(){
    local json_output=""

    while [ $# -gt 0 ]; do
        case "$1" in
            -j|--json) json_output=1; shift ;;
            -h|--help) ___x_cmd_weixin___help bot send raw; return 0 ;;
            *) break ;;
        esac
    done

    local raw="${1}"
    [ "$raw" = "-" ] && raw="$(___x_cmd_cmds_cat)"
    [ -z "$raw" ] && { weixin:error "JSON content required"; return 1; }

    local resp; resp="$(___x_cmd_weixin_u_curl POST "/ilink/bot/sendmessage" -d "$raw")"

    if [ -n "$json_output" ]; then
        printf "%s\n" "$resp"
    else
        local ret; ret="$(printf "%s" "$resp" | ___x_cmd jo env .ret)"
        if [ "$ret" = "0" ]; then
            ___x_cmd_ui_tf true "Sent message successfully"
        else
            ___x_cmd_ui_tf false "Failed to send message:" "$resp"
        fi
    fi
}

___x_cmd_weixin_bot_send_media(){
    local msg_type="$1"; shift
    local file_path=""
    local json_output=""
    local fp=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -j|--json) json_output=1; shift ;;
            --fp)               fp=1; shift ;;
            -h|--help) ___x_cmd_weixin___help bot send "--${msg_type}"; return 0 ;;
            *) file_path="$1" ; break ;;
        esac
    done

    [ -f "$file_path" ] || { weixin:error "File not found: $file_path"; return 1; }

    local upload_result; upload_result="$(___x_cmd_weixin_util_upload_media "$file_path" "$msg_type")" || {
        weixin:error "Failed to upload $msg_type"
        return 1
    }
    local resp; resp="$(printf "%s" "$upload_result" | ___x_cmd_weixin_u_curl POST "/ilink/bot/sendmessage" -d "@-")"
    [ "$resp" = "{}" ] || {
        ___x_cmd_ui_tf false "Failed to send message:" "$resp"
        return 1
    }

    if [ -n "$fp" ]; then
        local x_; ___x_cmd date timestamp_
        local send_time="$x_"
        local asset_dir="$___X_CMD_ROOT_DATA/weixin/bot/sent/asset"
        ___x_cmd mkdirp "$asset_dir"
        local target_path="${asset_dir}/${send_time}_${file_path##*/}"

        ___x_cmd_cmds cp "$file_path" "$target_path" || {
            weixin:warn "Failed to copy media to $target_path"
        }
        ___x_cmd ensurefp "$___X_CMD_WEIXIN_BOT_SENT_DATA"
        printf '%s\t%s\t%s\n' "$send_time" "$msg_type" "$target_path" >> "$___X_CMD_WEIXIN_BOT_SENT_DATA" || {
            weixin:warn "Failed to save sent media info to $___X_CMD_WEIXIN_BOT_SENT_DATA"
        }
    fi

    ___x_cmd_ui_tf true "Sent text message successfully"
}



