# shellcheck shell=dash

___x_cmd_feishu_parse(){
    param:void

    [ $# -gt 0 ] || set -- help
    local op="$1" ;
    case "$op" in
        -h|--help)      ___x_cmd help -m feishu parse "$@" ; return 0 ;;
    esac

    local chatid="$1"
    local range="$2"
    local start_line=""
    local end_line=""

    case "$range" in
        *:*)
            start_line="${range%%:*}"
            end_line="${range##*:}"
            ;;
        *)
            start_line="$2"
            end_line="$3"
            ;;
    esac

    [ -n "$chatid" ] || N=feishu M="Please provide the chat ID" log:ret:1

    local x_
    local botdata
    ___x_cmd_feishu_abot_data_which_ "$chatid" || return $?
    botdata="$x_"
    [ -f "$botdata" ] || N=feishu M="Data file not found for chat ${chatid}" log:ret:1

    { [ -n "$start_line" ] && [ "$start_line" -gt 0 ]; } || N=feishu M="Invalid start line for parse msg: '${start_line}'" log:ret:64

    start_line="${start_line}" \
    end_line="${end_line}"   \
    ___x_cmd awk0 -m j/json -m j/jiter \
            -f "$___X_CMD_ROOT_MOD/feishu/lib/awk/bot_parse.awk" < "$botdata" | {
        local is_ref="" msg_time="" msg_sender_id="" msg_type="" msg_text="" msg_image_key="" msg_file_key="" msg_file_name="" msg_chat_id="" msg_message_id="" msg_parent_id=""
        while   read -r is_ref && \
                read -r msg_time && \
                read -r msg_sender_id && \
                read -r msg_type && \
                read -r msg_text && \
                read -r msg_image_key && \
                read -r msg_file_key && \
                read -r msg_file_name && \
                read -r msg_chat_id && \
                read -r msg_message_id && \
                read -r msg_parent_id; do
            ___x_cmd_feishu_parse_item___ "$is_ref" "" "$msg_time" "$msg_sender_id" "$msg_type" "$msg_text" "$msg_image_key" "$msg_file_key" "$msg_file_name" "$msg_chat_id" "$msg_message_id" "$msg_parent_id"
        done
    }
}

# TODO:
___x_cmd_feishu_get_ref_message(){
    local msg_id="$1"
    local x_=; ____x_cmd_tenant_token || return $?
    local cur_token="$x_"

    ___x_cmd curl -s -L -X GET "https://open.feishu.cn/open-apis/im/v1/messages/${msg_id}" \
        -H "Authorization: Bearer $cur_token"
}

___x_cmd_feishu_parse_ref_content(){
    local ref_json="$1"
    local ref_msg_id="$2"

    # Determine start index and ref type display
    local start_index=0
    local ref_type_display=""
    local first_msg_type
    first_msg_type="$(printf "%s" "$ref_json" | ___x_cmd jq -r '.data.items[0].msg_type // empty' 2>/dev/null)"
    if [ "$first_msg_type" = "merge_forward" ]; then
        start_index=1
        ref_type_display="MergeForward"
    fi

    # Extract items as individual JSON lines, starting from start_index
    local items_jsonl
    items_jsonl="$(printf "%s" "$ref_json" | ___x_cmd jq -c ".data.items[${start_index}:][]" 2>/dev/null)"

    [ -n "$items_jsonl" ] || return 1

    # Pass all items to awk for parsing, write to temp file to avoid subshell
    local tmp_ref="${___X_CMD_FEISHU_TMP}/ref_parse_$$"
    printf "%s\n" "$items_jsonl" | ___x_cmd awk0 -m j/json -m j/jiter \
        -f "$___X_CMD_ROOT_MOD/feishu/lib/awk/bot_parse.awk" > "$tmp_ref"

    # Read parsed output and call ___x_cmd_feishu_parse_item___ for each message
    # Use temp file to avoid subshell (dash doesn't support here-strings)
    local ref_content="" item_body="" item_output=""
    while   read -r is_ref && \
            read -r msg_time && \
            read -r msg_sender_id && \
            read -r msg_type && \
            read -r msg_text && \
            read -r msg_image_key && \
            read -r msg_file_key && \
            read -r msg_file_name && \
            read -r msg_chat_id && \
            read -r msg_message_id && \
            read -r msg_parent_id; do
        # Get display type from the first item (if not already set by merge_forward)
        if [ -z "$ref_type_display" ]; then
            case "$msg_type" in
                text)           ref_type_display="Text" ;;
                image)          ref_type_display="Image" ;;
                file)           ref_type_display="File" ;;
                post)           ref_type_display="Post" ;;
                *)              ref_type_display="$msg_type" ;;
            esac
        fi
        # Call ___x_cmd_feishu_parse_item___ with is_ref="" to get formatted output
        item_output="$(___x_cmd_feishu_parse_item___ "" "" "$msg_time" "$msg_sender_id" "$msg_type" "$msg_text" "$msg_image_key" "$msg_file_key" "$msg_file_name" "$msg_chat_id" "$msg_message_id" "")"
        # Extract bodystr (4th tab-separated field)
        item_body="$(printf "%s" "$item_output" | cut -f4)"
        if [ -n "$ref_content" ]; then
            ref_content="${ref_content} ${item_body}"
        else
            ref_content="${item_body}"
        fi
    done < "$tmp_ref"
    rm -f "$tmp_ref"

    printf "%s\t%s" "$ref_type_display" "$ref_content"
}

___x_cmd_feishu_parse_item___(){
    local is_ref="$1"
    local bodystr="$2"
    local msg_time="$3"
    local msg_sender_id="$4"
    local msg_type="$5"
    local msg_text="$6"
    local msg_image_key="$7"
    local msg_file_key="$8"
    local msg_file_name="$9"
    local msg_chat_id="${10}"
    local msg_message_id="${11}"
    local msg_parent_id="${12}"

    local typename="Text" file_key="" default_ext="" download_type=""
    case "$msg_type" in
        text)
            bodystr="${bodystr}${msg_text}"
            ;;
        image)
            typename="Image"
            file_key="$msg_image_key"
            download_type="image"
            default_ext=".jpg"
            ;;
        file)
            typename="File"
            file_key="$msg_file_key"
            download_type="file"
            ;;
        media)
            typename="File"
            file_key="$msg_file_key"
            download_type="file"
            ;;
        post)
            typename="Post"
            bodystr="${bodystr}${msg_text} "
            if [ -n "$msg_image_key" ]; then
                file_key="$msg_image_key"
                download_type="image"
                default_ext=".jpg"
            fi
            ;;
        merge_forward)
            typename="MergeForward"
            # Fetch forwarded messages via API and parse them
            local fwd_json fwd_result fwd_content
            fwd_json="$(___x_cmd ccmd 1w -- ___x_cmd_feishu_get_ref_message "$msg_message_id")"
            fwd_result="$(___x_cmd_feishu_parse_ref_content "$fwd_json" "$msg_message_id")"
            fwd_content="${fwd_result#*	}"
            bodystr="${bodystr}${fwd_content}"
            ;;
        *)
            typename="Unknown"
            bodystr="${bodystr}[Unsupported message type: ${msg_type}]"
            ;;
    esac

    if [ "$typename" != "Unknown" ] && [ -n "$file_key" ]; then
        local filename="${file_key%"${file_key#????????????????}"}"
        local output_dir="$___X_CMD_FEISHU_BOT_DATA_DIR"
        [ -d "$output_dir" ] || ___x_cmd mkdirp "$output_dir"

        local out_file=""
        if [ -n "$msg_file_name" ]; then
            out_file="${output_dir}/${msg_file_name}"
        else
            out_file="${output_dir}/decrypted_${filename}${default_ext}"
        fi

        if [ ! -f "${out_file}" ]; then
            local x_=; ____x_cmd_tenant_token || return $?
            local cur_token="$x_"

            local tmp_file="${___X_CMD_FEISHU_TMP}/feishu_dl_${msg_message_id}"
            if ! ___x_cmd curl -s -L -X GET "https://open.feishu.cn/open-apis/im/v1/messages/${msg_message_id}/resources/${file_key}?type=${download_type}" \
                -H "Authorization: Bearer $cur_token" \
                -o "$tmp_file"; then
                feishu:error "Download failed for ${msg_message_id}"
                return 1
            fi

            [ -f "$tmp_file" ] && mv "$tmp_file" "$out_file"
        fi
        bodystr="${bodystr}${out_file}"
    fi

    if [ "$is_ref" = "1" ] && [ -n "$msg_parent_id" ]; then
        local ref_json ref_result ref_type_display ref_content
        ref_json="$(___x_cmd ccmd 1w -- ___x_cmd_feishu_get_ref_message "$msg_parent_id")"
        ref_result="$(___x_cmd_feishu_parse_ref_content "$ref_json" "$msg_parent_id")"
        ref_type_display="${ref_result%%	*}"
        ref_content="${ref_result#*	}"
        printf "%s\t%s\t%s\t[REF:%s:%s] %s\n" "$msg_time" "$msg_sender_id" "$typename" "$ref_type_display" "$ref_content" "$bodystr"
    else
        printf "%s\t%s\t%s\t%s\n" "$msg_time" "$msg_sender_id" "$typename" "$bodystr"
    fi
}