#!/bin/bash
# 任务名称：飞书用户反馈每分钟同步（时间倒序，全量覆盖）
# 执行时间：* * * * * 每分钟执行
# 归属 Agent：小葵 xiaokui

set +e

# 环境配置
export PATH=/root/.nvm/versions/node/v24.14.0/bin:$PATH
LOG_FILE="/var/log/sync_feedback_minutely.log"
WORKSPACE="/root/.openclaw/workspace-xiaokui"
TMP_DATA="$WORKSPACE/tmp/all_feedback_sorted.json"

# 源表格配置
SOURCE_SPREADSHEET_TOKEN="E8vFsCmPBhT4SCtNmnJchqeJnJe"
SOURCE_SHEET_ID="7bce8f"

# 目标表格配置
TARGET_SPREADSHEET_TOKEN="AOxbsifk3hybRZteGowcMxNnnqc"
TARGET_SHEET_ID="f17380"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

log "=== 同步任务开始 ==="

# 1. 读取源表格所有数据
log "读取源表格数据..."
SOURCE_RAW=$(LARKSUITE_CLI_CONFIG_DIR=/root/.openclaw/credentials/xiaokui lark-cli sheets +read --spreadsheet-token "$SOURCE_SPREADSHEET_TOKEN" --range "$SOURCE_SHEET_ID!A:D" --as bot)
SOURCE_DATA=$(echo "$SOURCE_RAW" | jq -r '.data.valueRange.values | .[1:] | map(select(.[0] != null and .[0] != ""))')

if [ -z "$SOURCE_DATA" ] || [ "$SOURCE_DATA" == "null" ]; then
    log "源表格无有效数据，退出"
    exit 0
fi

# 2. 转换格式并按时间倒序排列
SORTED_DATA=$(echo "$SOURCE_DATA" | jq '
    sort_by(.[0]) | reverse | to_entries | map(
        .key as $idx |
        .value as $row |
        {
            id: ($idx + 1),
            time: $row[0],
            submitter: $row[1],
            type: $row[2],
            content: ($row[3] | if type == "array" then .[0].link else . end)
        } |
        [
            (.id | tostring),
            "",
            "",
            "",
            .time,
            "飞书群",
            .submitter,
            "",
            "",
            (if .type == "文本" then .content else "" end),
            (if .type == "图片" then .content else "" end),
            (if .type | test("视频") then .content else "" end),
            "",
            "待确认",
            ""
        ]
    )')

ROW_COUNT=$(echo "$SORTED_DATA" | jq length)
log "共获取到 $ROW_COUNT 条反馈记录，按时间倒序排列完成"

# 3. 清空目标表格原有数据（保留表头）
log "清空目标表格原有数据..."
EMPTY_DATA=$(printf '[]%.0s' {1..200} | jq -s '.')
LARKSUITE_CLI_CONFIG_DIR=/root/.openclaw/credentials/xiaokui lark-cli sheets +write \
    --spreadsheet-token "$TARGET_SPREADSHEET_TOKEN" \
    --range "$TARGET_SHEET_ID!A2:O201" \
    --values "$EMPTY_DATA" \
    --as bot >/dev/null 2>&1

# 4. 写入排序后的数据
echo "$SORTED_DATA" > "$TMP_DATA"
END_ROW=$((ROW_COUNT + 1))

log "写入数据到目标表格..."
LARKSUITE_CLI_CONFIG_DIR=/root/.openclaw/credentials/xiaokui lark-cli sheets +write \
    --spreadsheet-token "$TARGET_SPREADSHEET_TOKEN" \
    --range "$TARGET_SHEET_ID!A2:O$END_ROW" \
    --values "$(cat $TMP_DATA)" \
    --as bot

log "✅ 同步完成，共写入 $ROW_COUNT 条记录，最新反馈已排在最上方"

# 清理临时文件
rm -f "$TMP_DATA"

log "=== 同步任务完成 ==="
exit 0
