#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定时保存对话记忆到向量记忆系统
每天 23:40 自动执行
"""

import os
import sys
import json
from datetime import datetime, timedelta

# 添加项目路径
sys.path.insert(0, os.path.expanduser("~/openclaw-memory-vector"))

from vector_memory import VectorMemorySystem


def save_openclaw_sessions():
    """获取 OpenClaw 主会话关键内容"""
    print("💬 正在读取 OpenClaw 会话...")
    
    sessions_dir = os.path.expanduser("~/.openclaw/agents/main/sessions")
    memories = []
    seen_content = set()
    
    if not os.path.exists(sessions_dir):
        print("   ⚠️ 会话目录不存在")
        return memories
    
    # 获取最近一天的会话文件
    yesterday = datetime.now() - timedelta(days=1)
    
    for f in os.listdir(sessions_dir):
        if not f.endswith('.jsonl') or '.deleted.' in f or '.reset.' in f:
            continue
        
        filepath = os.path.join(sessions_dir, f)
        mtime = datetime.fromtimestamp(os.path.getmtime(filepath))
        
        # 只读取昨天修改过的文件
        if mtime > yesterday:
            try:
                with open(filepath, 'r', encoding='utf-8') as file:
                    lines = file.readlines()
                    # 取最近 20 条
                    recent_lines = lines[-20:] if len(lines) > 20 else lines
                    
                    for line in recent_lines:
                        if not line.strip():
                            continue
                        try:
                            data = json.loads(line)
                            # 提取用户消息
                            if data.get('role') == 'user':
                                content = data.get('content', '')
                                # 简化内容
                                if content and len(content) > 10 and len(content) < 500:
                                    # 取前100字
                                    short = content[:100]
                                    if short not in seen_content:
                                        seen_content.add(short)
                                        memories.append(short)
                        except:
                            pass
            except Exception as e:
                print(f"   ⚠️ 读取失败: {e}")
    
    # 去重
    unique_memories = list(seen_content)[:10]  # 最多10条
    
    print(f"   ✅ 提取了 {len(unique_memories)} 条独特对话")
    return unique_memories


def main():
    """主函数"""
    print(f"\n{'='*60}")
    print(f"💾 对话记忆保存任务")
    print(f"⏰ 执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'='*60}")
    
    # 获取 API Key
    api_key = os.getenv("SILICONFLOW_API_KEY", "sk-fpjdtxbxrhtekshircjhegstloxaodriekotjdyzzktyegcl")
    
    # 初始化向量记忆
    vm = VectorMemorySystem(api_key=api_key)
    
    # 获取 OpenClaw 会话
    sessions = save_openclaw_sessions()
    
    # 添加到记忆
    if sessions:
        count = 0
        for msg in sessions:
            vm.add_memory(
                content=f"[对话记录] {msg}...",
                metadata={"source": "auto_save", "type": "conversation"},
                importance=3
            )
            count += 1
        print(f"\n✅ 已保存 {count} 条对话记忆")
    else:
        print("\n📝 暂无新对话记录")
    
    # 记录任务执行
    vm.add_memory(
        content=f"定时任务: {datetime.now().strftime('%Y-%m-%d %H:%M')} 对话记忆保存",
        metadata={"source": "cron", "type": "task"},
        importance=2
    )
    
    print(f"\n{'='*60}")
    print("✅ 任务完成!")
    print("=" * 60)


if __name__ == "__main__":
    main()
