"""
Persistent Memory - 长期记忆（向量存储）
"""
from typing import List, Optional


class PersistentMemory:
    """长期记忆，向量存储"""

    def __init__(self, agent_id: int, vector_store=None):
        """
        初始化长期记忆

        Args:
            agent_id: 智能体 ID
            vector_store: 向量存储客户端（可选）
        """
        self.agent_id = agent_id
        self.vector_store = vector_store
        self.use_vector = vector_store is not None

    async def add(self, content: str, user_id: int, memory_type: str = "experience"):
        """
        添加长期记忆

        Args:
            content: 记忆内容
            user_id: 用户 ID
            memory_type: 记忆类型 (experience/preference/conversation)
        """
        if not self.use_vector:
            return self._add_memory(content, user_id, memory_type)

        # 生成向量并存储
        embedding = await self._get_embedding(content)
        # TODO: 调用向量存储 API

    async def search(self, query: str, user_id: int, top_k: int = 3) -> List[str]:
        """
        搜索相关记忆

        Args:
            query: 查询内容
            user_id: 用户 ID
            top_k: 返回数量

        Returns:
            List[str]: 相关的记忆列表
        """
        if not self.use_vector:
            return self._search_memory(query, user_id, top_k)

        # 生成查询向量
        query_embedding = await self._get_embedding(query)

        # TODO: 调用向量搜索 API
        # results = await self.vector_store.search(
        #     agent_id=self.agent_id,
        #     user_id=user_id,
        #     embedding=query_embedding,
        #     top_k=top_k
        # )

        return []

    async def _get_embedding(self, text: str) -> List[float]:
        """
        获取文本向量

        Args:
            text: 文本

        Returns:
            List[float]: 向量
        """
        # TODO: 实现向量生成
        # 可以使用 OpenAI Embedding API 或本地模型
        import hashlib
        # 简化：使用文本哈希模拟
        h = hashlib.md5(text.encode()).digest()
        return [float(b) / 255.0 for b in h[:16]] + [0.0] * 16

    # === 内存模拟（无向量存储时使用）===
    _memory_store = {}

    def _add_memory(self, content: str, user_id: int, memory_type: str):
        """内存模拟 - 添加"""
        key = f"{self.agent_id}:{user_id}"
        if key not in self._memory_store:
            self._memory_store[key] = []

        self._memory_store[key].append({
            "content": content,
            "type": memory_type
        })

    def _search_memory(self, query: str, user_id: int, top_k: int) -> List[str]:
        """内存模拟 - 搜索（简化版：关键词匹配）"""
        key = f"{self.agent_id}:{user_id}"
        if key not in self._memory_store:
            return []

        # 简化：包含查询词的记忆
        results = []
        for mem in self._memory_store[key]:
            if query.lower() in mem["content"].lower():
                results.append(mem["content"])

        return results[:top_k]
