#!/bin/bash
# 每日8点总结执行脚本
WORKSPACE="/root/.openclaw/workspace-xiaoban"
DATE=$(date +%Y%m%d)
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)

# 1. 生成过去24小时关键经验总结
echo "=== 每日总结 $DATE ===" > $WORKSPACE/tmp_daily_summary.md
echo "## 昨日关键进展" >> $WORKSPACE/tmp_daily_summary.md
# 读取昨日记忆文件内容
if [ -f "$WORKSPACE/memory/$YESTERDAY.md" ]; then
  grep -E "(完成|新增|修复|优化|升级|重要)" $WORKSPACE/memory/$YESTERDAY.md >> $WORKSPACE/tmp_daily_summary.md
else
  echo "无昨日记忆记录" >> $WORKSPACE/tmp_daily_summary.md
fi

# 2. 提交更新到git仓库
cd $WORKSPACE
git add .
git commit -m "每日总结更新 $DATE"
git push origin main

# 3. 更新飞书个人说明文档
# 调用飞书文档更新接口，将总结追加到个人说明文档末尾
# 文档token从MEMORY.md获取：Tn23wQkUQilduAkvgwscTGhgnUd
curl -X POST "https://open.feishu.cn/open-apis/docx/v1/documents/Tn23wQkUQilduAkvgwscTGhgnUd/blocks" \
  -H "Authorization: Bearer $(cat $WORKSPACE/.feishu_token)" \
  -H "Content-Type: application/json" \
  -d "{
    \"block_type\": 3,
    \"children\": [
      {
        \"block_type\": 2,
        \"text\": {
          \"content\": \"### 每日更新 $DATE\n$(cat $WORKSPACE/tmp_daily_summary.md | sed 's/"/\\"/g')\"
        }
      }
    ]
  }"

# 4. 发送通知给李若松（使用 user_id + curl）
APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaoban/config.json)
APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaoban/config.json)
TOKEN=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" \
  -H "Content-Type: application/json" \
  -d "{\"app_id\":\"$APP_ID\",\"app_secret\":\"$APP_SECRET\"}" \
  | jq -r '.tenant_access_token')

SUMMARY_TEXT=$(cat $WORKSPACE/tmp_daily_summary.md | tr '\n' ' ' | sed 's/"/\\"/g')
curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"receive_id\":\"4aagb443\",\"msg_type\":\"text\",\"content\":\"{\\\"text\\\":\\\"✅ 每日8点总结任务已完成，飞书文档已更新，git仓库已同步。\\\"}\"}" > /dev/null 2>&1

# 清理临时文件
rm $WORKSPACE/tmp_daily_summary.md
