#!/usr/bin/env python3
"""
平台感知的记忆管理系统
支持微信和飞书并行对话，同时保持跨平台记忆共享
"""

import os
import json
from datetime import datetime
from pathlib import Path

class PlatformMemoryManager:
    def __init__(self, workspace_path="."):
        self.workspace = Path(workspace_path)
        self.memory_dir = self.workspace / "memory"
        
        # 创建目录结构
        (self.memory_dir / "wechat").mkdir(parents=True, exist_ok=True)
        (self.memory_dir / "feishu").mkdir(parents=True, exist_ok=True)
        (self.memory_dir / "cross-platform").mkdir(parents=True, exist_ok=True)
        
        # 状态文件
        self.state_file = self.workspace / "platform_context.json"
        self.load_state()
    
    def load_state(self):
        """加载平台状态"""
        if self.state_file.exists():
            with open(self.state_file, 'r', encoding='utf-8') as f:
                self.state = json.load(f)
        else:
            self.state = {
                "wechat": {
                    "current_topic": None,
                    "last_activity": None,
                    "active": False
                },
                "feishu": {
                    "current_topic": None,
                    "last_activity": None,
                    "active": False
                },
                "cross_platform_topics": []
            }
            self.save_state()
    
    def save_state(self):
        """保存平台状态"""
        with open(self.state_file, 'w', encoding='utf-8') as f:
            json.dump(self.state, f, ensure_ascii=False, indent=2)
    
    def record_conversation(self, platform, message, topic=None):
        """记录对话到对应平台"""
        today = datetime.now().strftime("%Y-%m-%d")
        
        # 更新平台状态
        self.state[platform]["current_topic"] = topic
        self.state[platform]["last_activity"] = datetime.now().isoformat()
        self.state[platform]["active"] = True
        
        # 记录到平台专属记忆
        platform_file = self.memory_dir / platform / f"{today}.md"
        with open(platform_file, 'a', encoding='utf-8') as f:
            timestamp = datetime.now().strftime("%H:%M:%S")
            f.write(f"\n**[{timestamp}] {platform.upper()}**: {message}\n")
            if topic:
                f.write(f"*话题: {topic}*\n")
        
        # 记录到跨平台共享记忆（重要内容）
        if self.is_important_message(message):
            cross_file = self.memory_dir / "cross-platform" / f"{today}.md"
            with open(cross_file, 'a', encoding='utf-8') as f:
                f.write(f"\n**[{timestamp}] {platform.upper()}**: {message}\n")
        
        self.save_state()
        return platform_file
    
    def is_important_message(self, message):
        """判断是否为重要消息（需要跨平台共享）"""
        important_keywords = [
            "重要", "紧急", "记住", "备忘", "任务", "待办",
            "决定", "选择", "偏好", "设置", "配置"
        ]
        message_lower = message.lower()
        return any(keyword in message_lower for keyword in important_keywords)
    
    def get_context_for_platform(self, platform):
        """获取指定平台的上下文"""
        today = datetime.now().strftime("%Y-%m-%d")
        
        context = []
        
        # 1. 当前平台今天的对话
        platform_file = self.memory_dir / platform / f"{today}.md"
        if platform_file.exists():
            with open(platform_file, 'r', encoding='utf-8') as f:
                context.append(f"=== {platform.upper()} 今日对话 ===\n{f.read()}")
        
        # 2. 跨平台共享记忆（最近3天）
        for days_ago in range(3):
            date = (datetime.now() - timedelta(days=days_ago)).strftime("%Y-%m-%d")
            cross_file = self.memory_dir / "cross-platform" / f"{date}.md"
            if cross_file.exists():
                with open(cross_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    if content.strip():
                        context.append(f"=== 跨平台共享记忆 ({date}) ===\n{content}")
        
        # 3. 其他平台状态
        other_platform = "feishu" if platform == "wechat" else "wechat"
        other_state = self.state[other_platform]
        if other_state["active"]:
            context.append(
                f"=== {other_platform.upper()} 状态 ===\n"
                f"当前话题: {other_state['current_topic'] or '无'}\n"
                f"最后活动: {other_state['last_activity']}\n"
                f"状态: 活跃中"
            )
        
        return "\n\n".join(context)
    
    def get_other_platform_summary(self, current_platform):
        """获取另一个平台的摘要"""
        other = "feishu" if current_platform == "wechat" else "wechat"
        state = self.state[other]
        
        if not state["active"]:
            return f"{other.upper()} 当前无活跃对话"
        
        summary = [
            f"{other.upper()} 正在讨论: {state['current_topic'] or '未指定话题'}",
            f"最后活动: {state['last_activity']}",
        ]
        
        # 获取最近的重要消息
        today = datetime.now().strftime("%Y-%m-%d")
        cross_file = self.memory_dir / "cross-platform" / f"{today}.md"
        if cross_file.exists():
            with open(cross_file, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                recent_from_other = [
                    line for line in lines[-5:]  # 最近5条
                    if other.upper() in line
                ]
                if recent_from_other:
                    summary.append("最近重要消息:")
                    summary.extend(recent_from_other[-3:])  # 最近3条
        
        return "\n".join(summary)


# 使用示例
if __name__ == "__main__":
    manager = PlatformMemoryManager()
    
    # 模拟微信对话
    manager.record_conversation("wechat", "我想学习Python编程", "学习计划")
    
    # 模拟飞书对话  
    manager.record_conversation("feishu", "需要准备下周的会议材料", "工作安排")
    
    # 获取微信上下文
    print("=== 微信上下文 ===")
    print(manager.get_context_for_platform("wechat"))
    
    print("\n=== 飞书摘要 ===")
    print(manager.get_other_platform_summary("wechat"))