#!/bin/bash
# 每日学习总结脚本
# 每天凌晨3点执行，回顾当天聊天内容，总结学习记录

LOG_FILE="/root/.openclaw/workspace-assistant/logs/daily_learning.log"
MEMORY_FILE="/root/.openclaw/workspace-assistant/memory/daily_learning.md"
SESSION_FILE="/root/.openclaw/agents/dingtalk-assistant/sessions/e89452e7-59d0-46a3-9dec-983cb7863ac5.jsonl"

echo "=== $(date '+%Y-%m-%d %H:%M:%S') 每日学习总结开始 ===" >> "$LOG_FILE"

# 提取聊天记录中的关键内容
python3 << 'PYEOF' >> "$LOG_FILE"
import sys
import json
from datetime import datetime, timezone, timedelta

LOG_FILE = "/root/.openclaw/workspace-assistant/logs/daily_learning.log"
SESSION_FILE = "/root/.openclaw/agents/dingtalk-assistant/sessions/e89452e7-59d0-46a3-9dec-983cb7863ac5.jsonl"

# 北京时区
bj_tz = timezone(timedelta(hours=8))
# 计算24小时前的时间
one_day_ago = datetime.now(bj_tz).timestamp() - 86400

messages = []
try:
    with open(SESSION_FILE, 'r') as f:
        for line in f:
            try:
                obj = json.loads(line.strip())
                if obj.get('type') == 'message' and obj.get('timestamp'):
                    ts_str = obj.get('timestamp', '')
                    try:
                        if 'T' in ts_str:
                            ts = datetime.fromisoformat(ts_str.replace('Z', '+00:00')).timestamp()
                        else:
                            ts = float(ts_str)
                    except:
                        continue
                    
                    if ts > one_day_ago:
                        msg = obj.get('message', {})
                        role = msg.get('role', '')
                        content = msg.get('content', [])
                        if isinstance(content, list):
                            for c in content:
                                if isinstance(c, dict) and c.get('type') == 'text':
                                    text = c.get('text', '')[:500]
                                    if text:
                                        if 'HEARTBEAT_OK' not in text and 'System:' not in text[:50] and 'Exec completed' not in text[:50] and 'conversation' not in text[:50].lower():
                                            messages.append(f'[{role}] {text[:300]}')
            except:
                pass
except Exception as e:
    print(f"Error: {e}")

# 去重
seen = set()
unique_messages = []
for m in messages:
    key = m[:100]
    if key not in seen:
        seen.add(key)
        unique_messages.append(m)

if not unique_messages:
    print("没有发现新的聊天内容")
else:
    print(f"发现 {len(unique_messages)} 条消息")
    
    # 检测关键主题
    topics = []
    keywords = ['mcp', 'api', 'skill', '脚本', '配置', '钉钉', '邮件', '日程', '日历', '语音', 'whisper', 'tts', '日志', '周报', '待办', '文档', '审批']
    
    for m in unique_messages:
        lower = m.lower()
        for kw in keywords:
            if kw in lower and kw not in topics:
                topics.append(kw)
    
    today = datetime.now().strftime('%Y-%m-%d')
    
    summary = f"""
## 每日学习总结 - {today}

### 涉及的主题
{', '.join(topics) if topics else '无特定主题'}

### 关键对话记录
"""
    for m in unique_messages[:50]:
        summary += m[:200] + "\n\n"
    
    # 输出到日志
    print(summary)
    
    # 保存到记忆文件
    MEMORY_FILE = "/root/.openclaw/workspace-assistant/memory/daily_learning.md"
    try:
        with open(MEMORY_FILE, 'r') as f:
            existing = f.read()
    except:
        existing = ''
    
    if today not in existing:
        with open(MEMORY_FILE, 'a') as f:
            f.write('\n' + summary)
        print("\n已更新学习记录")
    else:
        print("\n今日已记录，跳过")
PYEOF

echo "=== 完成 ===" >> "$LOG_FILE"
echo "完成！"
