"""
Memory Manager - 记忆管理器
"""
from typing import Dict, List, Optional
from app.agent.memory.working import WorkingMemory
from app.agent.memory.session import SessionMemory
from app.agent.memory.persistent import PersistentMemory


class MemoryManager:
    """记忆管理器 - 统一接口"""

    def __init__(self, agent_id: int):
        self.agent_id = agent_id
        self.working = WorkingMemory()
        self.session = SessionMemory(agent_id)
        self.persistent = PersistentMemory(agent_id)

    async def load_context(self, query: str, user_id: int, session_id: str) -> Dict[str, str]:
        """
        加载上下文记忆

        优化：跳过耗时的向量搜索，提升响应速度
        生产环境可以加回来

        Args:
            query: 查询内容
            user_id: 用户 ID
            session_id: 会话 ID

        Returns:
            Dict: 包含 summary, knowledge 等
        """
        # 1. Working Memory (内存，最快)
        working_context = self.working.get()

        # 2. Session Memory (Redis) - 暂时跳过，减少延迟
        # session_context = await self.session.get_summary(user_id, session_id)
        session_context = ""

        # 3. Persistent Memory (向量库) - 暂时跳过，减少延迟
        # persistent_context = await self.persistent.search(query, user_id, top_k=3)
        persistent_context = []

        return {
            'working': working_context.get('recent_messages', []),
            'session': session_context,
            'persistent': persistent_context,
            'summary': "",  # 简化
            'knowledge': ""
        }

    async def save(self, user_input: str, response: str, user_id: int, session_id: str):
        """
        保存记忆

        Args:
            user_input: 用户输入
            response: 智能体回复
            user_id: 用户 ID
            session_id: 会话 ID
        """
        # 1. 写入 Working
        self.working.add(user_input, response)

        # 2. 写入 Session (定期摘要)
        await self.session.add(user_input, response, user_id, session_id)

        # 3. 提取关键信息写入 Persistent (定期)
        if self.working.size() >= 5:
            await self._extract_and_persist(user_input, response, user_id)

    def _build_summary(self, session_context: str, persistent_context: List[str]) -> str:
        """构建记忆摘要"""
        parts = []

        if session_context:
            parts.append(f"会话记忆: {session_context}")

        if persistent_context:
            parts.append(f"长期记忆: {'; '.join(persistent_context[:3])}")

        return "\n".join(parts) if parts else "无相关记忆"

    async def _extract_and_persist(self, user_input: str, response: str, user_id: int):
        """提取并持久化关键信息"""
        # 提取关键信息（简化版：取前100字符作为摘要）
        key_points = []

        # 简化：直接保存重要交互
        if len(response) > 50:  # 只保存有意义的回复
            summary = response[:100] + "..."
            key_points.append(summary)

        for point in key_points:
            await self.persistent.add(point, user_id, memory_type="conversation")

        # 重置 Working Memory
        self.working.clear()
