# shellcheck shell=dash disable=SC2016

___x_cmd_feishu_abot_send(){
    param:void

    [ $# -gt 0 ]    ||  set -- --help

    local op="$1" ;     shift
    case "$op" in
        -h|--help)
                ___x_cmd help -m feishu abot send ; return 0 ;;
        --text|--image|--file|--card)
                ___x_cmd_feishu_abot_send_"${op#--}" "$@"
                ;;
        *)      N=feishu M="Unknown op -> $op" log:ret:64   ;;
    esac
}

___x_cmd_feishu_abot_send_text(){
    local chatid="" json_output="" fp=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --chatid)   chatid="$2" ; arg:2:shift ;;
            -j|--json)  json_output=1; shift ;;
            --fp)       fp=1; shift ;;
            -h|--help)  ___x_cmd help -m feishu abot send --text; return 0 ;;
            *) break ;;
        esac
    done

    if [ -z "$chatid" ] || [ "$chatid" = "admin" ]; then
        chatid=""
        ___x_cmd_feishu_cur chatid:= 2>/dev/null
        [ -n "$chatid" ] || N=feishu M="Please set your default chat id first ==> 'x feishu --cfg chatid=<chatid>'" log:ret:1
    fi

    local msg="$1"
    # msg="$( ___x_cmd_feishu___jqu "$msg")"

    local msg_json
    msg_json="$(___x_cmd jq -n          \
            --arg msg "$msg"            \
            --arg chatid "$chatid"      \
            '{
              msg_type: "post",
              receive_id: $chatid,
              content: {zh_cn: {content: [[{tag: "md", text: $msg}]]}} | tojson
            }')"

    feishu:debug "$(printf "%s" "$msg_json" )"
    local resp; resp="$(printf "%s" "$msg_json" | ___x_cmd_feishu_appsend___ "$chatid")"

    [ -z "$json_output" ] || {
        printf "%s" "$resp"
        return
    }

    local x_; ___x_cmd date timestamp_
    local send_time="$x_"

    local statu ; statu="$(printf "%s" "$resp" | {  ___x_cmd jo env .msg ; echo "$msg" ; })"
    if [ "$statu" = "success" ]; then
        ___x_cmd_ui_tf true "Sent text message successfully"

        if [ -n "$fp" ]; then
            local sent_data_path="$___X_CMD_ROOT_DATA/feishu/abot/sent/data_${chatid}.tsv"
            ___x_cmd ensurefp "$sent_data_path"
            printf '%s\t%s\t%s\n' "$send_time" "text" "$msg" >> "$sent_data_path"
        fi
    else
        ___x_cmd_ui_tf false "Failed to send message:" "ErrorMsg:$resp"
    fi
}

___x_cmd_feishu_abot_send_image(){
    local chatid
    local image_path
    local json_output=
    local fp=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --chatid)   chatid="$2" ; arg:2:shift ;;
            -j|--json)  json_output=1; shift ;;
            --fp)       fp=1; shift ;;
            -h|--help)  ___x_cmd help -m feishu abot send --image; return 0 ;;
            *) break ;;
        esac
    done

    if [ -z "$chatid" ] || [ "$chatid" = "admin" ]; then
        chatid=""
        ___x_cmd_feishu_cur chatid:= 2>/dev/null
        [ -n "$chatid" ] || N=feishu M="Please set your default chat id first ==> 'x feishu --cfg chatid=<chatid>'" log:ret:1
    fi

    image_path="$1"
    [ -f "$image_path" ] || N=feishu M="File not found: $file_path" log:ret:1
    local resp; resp="$(___x_cmd_feishu_appupload_image_ "$image_path")"


    local image_key; image_key="$(printf "%s" "$resp" | { ___x_cmd jq -r .data.image_key ; })"
    if [ -n "$image_key" ]; then
        local msg_json; msg_json="$(___x_cmd_cmds cat <<A
{
    "content": "{\"image_key\":\"$image_key\"}",
    "msg_type": "image",
    "receive_id": "$chatid"
}
A
)"
        feishu:debug "$(printf "%s" "$msg_json")"
        local send_resp; send_resp="$(printf "%s" "$msg_json" | ___x_cmd_feishu_appsend___ "$chatid")"

        [ -z "$json_output" ] || {
            printf "%s" "$resp"
            return
        }

        local x_; ___x_cmd date timestamp_
        local send_time="$x_"

        local statu ; statu="$(printf "%s" "$send_resp" | {  ___x_cmd jo env .msg ; echo "$msg" ; })"
        if [ "$statu" = "success" ]; then
            ___x_cmd_ui_tf true "Sent image successfully"

            if [ -n "$fp" ]; then
                local asset_dir="$___X_CMD_ROOT_DATA/feishu/abot/sent/asset"
                ___x_cmd mkdirp "$asset_dir"
                local target_path="${asset_dir}/${send_time}_${image_path##*/}"

                ___x_cmd_cmds cp "$image_path" "$target_path" || {
                    feishu:warn "Failed to copy image to $target_path"
                }

                local sent_data_path="$___X_CMD_ROOT_DATA/feishu/abot/sent/data_${chatid}.tsv"
                ___x_cmd ensurefp "$sent_data_path"
                printf '%s\t%s\t%s\n' "$send_time" "image" "$target_path" >> "$sent_data_path" || {
                    feishu:warn "Failed to save sent image info to $sent_data_path"
                }
            fi
        else
            ___x_cmd_ui_tf false "Failed to send image:" "ErrorMsg:$send_resp"
        fi
    else
        ___x_cmd_ui_tf false "Failed to upload image:" "ErrorMsg:$resp"
    fi
}

___x_cmd_feishu_abot_send_file(){
    local chatid
    local name
    local file_path
    local json_output=
    local fp=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)  ___x_cmd help -m feishu abot send --file; return 0 ;;
            --chatid)   chatid="$2" ;  arg:2:shift ;;
            --name)     name="$2" ;     arg:2:shift ;;
            -j|--json)  json_output=1;  shift ;;
            --fp)       fp=1; shift ;;
            *) break ;;
        esac
    done

    if [ -z "$chatid" ] || [ "$chatid" = "admin" ]; then
        chatid=""
        ___x_cmd_feishu_cur chatid:= 2>/dev/null
        [ -n "$chatid" ] || N=feishu M="Please set your default chat id first ==> 'x feishu --cfg chatid=<chatid>'" log:ret:1
    fi

    file_path="$1"
    [ -f "$file_path" ] || N=feishu M="File not found: $file_path" log:ret:1
    local resp; resp="$(___x_cmd_feishu_appupload_file_ "$file_path")"

    local file_key;
    file_key="$(printf "%s" "$resp" | ___x_cmd jq -r .data.file_key)"
    if [ -n "$file_key" ]; then
        local msg_json; msg_json="$(___x_cmd_cmds cat <<A
{
    "content": "{\"file_key\":\"$file_key\"}",
    "msg_type": "file",
    "receive_id": "$chatid"
}
A
)"
        feishu:debug "$(printf "%s" "$msg_json")"
        local send_resp;
        send_resp="$(printf "%s" "$msg_json" | ___x_cmd_feishu_appsend___ "$chatid")"

        [ -z "$json_output" ] || {
            printf "%s" "$resp"
            return
        }

        local x_; ___x_cmd date timestamp_
        local send_time="$x_"

        local statu; statu="$(printf "%s" "$send_resp" | {  ___x_cmd jo env .msg ; echo "$msg" ; })"
        if [ "$statu" = "success" ]; then
            ___x_cmd_ui_tf true "Sent file successfully"

            if [ -n "$fp" ]; then
                local asset_dir="$___X_CMD_ROOT_DATA/feishu/abot/sent/asset"
                ___x_cmd mkdirp "$asset_dir"
                local target_path="${asset_dir}/${send_time}_${file_path##*/}"

                ___x_cmd_cmds cp "$file_path" "$target_path" || {
                    feishu:warn "Failed to copy file to $target_path"
                }
                local sent_data_path="$___X_CMD_ROOT_DATA/feishu/abot/sent/data_${chatid}.tsv"
                ___x_cmd ensurefp "$sent_data_path"
                printf '%s\t%s\t%s\n' "$send_time" "file" "$target_path" >> "$sent_data_path" || {
                    feishu:warn "Failed to save sent file info to $sent_data_path"
                }
            fi
        else
            ___x_cmd_ui_tf false "Failed to send file:" "ErrorMsg:$send_resp"
        fi
    else
        ___x_cmd_ui_tf false "Failed to upload file:" "ErrorMsg:$resp"
    fi
}

___x_cmd_feishu_abot_send_card(){
    local chatid="" json_output="" fp="" file_input=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --chatid)   chatid="$2" ; arg:2:shift ;;
            -f|--file)  file_input="$2"; arg:2:shift ;;
            -j|--json)  json_output=1; shift ;;
            --fp)       fp=1; shift ;;
            -h|--help)  ___x_cmd help -m feishu abot send --card; return 0 ;;
            *) break ;;
        esac
    done

    if [ -z "$chatid" ] || [ "$chatid" = "admin" ]; then
        chatid=""
        ___x_cmd_feishu_cur chatid:= 2>/dev/null
        [ -n "$chatid" ] || N=feishu M="Please set your default chat id first ==> 'x feishu --cfg chatid=<chatid>'" log:ret:1
    fi

    local content
    if [ -n "$file_input" ]; then
        [ -f "$file_input" ] || N=feishu M="File not found: $file_input" log:ret:1
        content="$(___x_cmd_cmds cat "$file_input")"
    elif [ "$1" = "-" ]; then
        content="$(___x_cmd_cmds_cat)"
    else
        content="$1"
    fi
    [ -n "$content" ] || N=feishu M="Card markdown content is empty" log:ret:1

    # Build the Schema 2.0 interactive card inline and embed it as the
    # `content` string in one jq pass (Feishu requires `content` to be a string).
    # ref: https://open.feishu.cn/document/uAjLw4CM/ukzMukzMukzM/feishu-cards/card-json-v2-structure
    local msg_json
    msg_json="$(___x_cmd jq -n                      \
        --arg content "$content"                    \
        --arg chatid "$chatid"                      \
        '{
            msg_type: "interactive",
            receive_id: $chatid,
            content: {
                schema: "2.0",
                config: { width_mode: "fill" },
                body: {
                    elements: [
                        { tag: "markdown", content: $content }
                    ]
                }
            } | tojson
        }')"

    feishu:debug "$(printf "%s" "$msg_json" )"
    local resp; resp="$(printf "%s" "$msg_json" | ___x_cmd_feishu_appsend___ "$chatid")"

    [ -z "$json_output" ] || {
        printf "%s" "$resp"
        return
    }

    local statu ; statu="$(printf "%s" "$resp" | {  ___x_cmd jo env .msg ; echo "$msg" ; })"
    if [ "$statu" = "success" ]; then
        ___x_cmd_ui_tf true "Sent card message successfully"

        if [ -n "$fp" ]; then
            local x_; ___x_cmd date timestamp_
            local send_time="$x_"
            local sent_data_path="$___X_CMD_ROOT_DATA/feishu/abot/sent/data_${chatid}.tsv"
            ___x_cmd ensurefp "$sent_data_path"
            printf '%s\t%s\t%s\n' "$send_time" "card" "$content" >> "$sent_data_path"
        fi
    else
        ___x_cmd_ui_tf false "Failed to send card:" "ErrorMsg:$resp"
    fi
}

___x_cmd_feishu_appsend___(){
    local x_=; local cur_token
    ____x_cmd_tenant_token ; cur_token="$x_"

    local receive_id_type="chat_id"
    case "$1" in
        ou_*)   receive_id_type="open_id" ;;
        oc_*)   receive_id_type="chat_id" ;;
        un_*)   receive_id_type="union_id" ;;
        e_*)    receive_id_type="user_id" ;;
        *@*)    receive_id_type="email" ;;
    esac

    ___x_cmd curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=${receive_id_type}" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $cur_token" \
    -d @-
}

___x_cmd_feishu_appupload_image_(){
    local x_=; local cur_token
    ____x_cmd_tenant_token ; cur_token="$x_"

    image_path="$1"
    [ -f "$image_path" ] || N=feishu M="File not found: $image_path" log:ret:1

    ___x_cmd curl -s -X POST 'https://open.feishu.cn/open-apis/im/v1/images?image_type=message' \
        -H "Authorization: Bearer $cur_token" \
        -F "image_type=message" \
        -F "image=@${image_path}"
}

___x_cmd_feishu_appupload_file_(){
    local x_=; local cur_token
    ____x_cmd_tenant_token ; cur_token="$x_"

    file_path="$1"
    [ -f "$file_path" ] || N=feishu M="File not found: $file_path" log:ret:1

    local file_name="${file_path##*/}"
    local file_type="stream"

    feishu:debug "[filename=$file_name],[filetype=$file_type],[file=$file_path]"
    ___x_cmd curl -s -X POST 'https://open.feishu.cn/open-apis/im/v1/files' \
        -H "Authorization: Bearer $cur_token" \
        -H "Content-Type: multipart/form-data" \
        -F "file_type=${file_type}" \
        -F "file_name=${file_name}" \
        -F "file=@${file_path}"
}

___x_cmd_feishu___jqu(){
    local IFS=" "
    printf "%s" "$*" | ___x_cmd_cmds_awk '
{
    text = (text == "") ? $0 : (text "\n" $0)
}
END{
    gsub("\n", "\\\\&", text)
    gsub("\n", "\\n", text)
    gsub("\t", "\\t", text)
    printf("%s", text)
}
'
}