"""
向量数据库抽象层
"""
from abc import ABC, abstractmethod
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime


@dataclass
class VectorMemory:
    """向量记忆项"""
    id: str
    user_id: str
    content: str
    embedding: List[float]
    importance: float
    timestamp: datetime
    metadata: Dict
    access_count: int = 0
    last_access: Optional[datetime] = None
    
    def to_dict(self) -> Dict:
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'content': self.content,
            'embedding': self.embedding,
            'importance': self.importance,
            'timestamp': self.timestamp.isoformat(),
            'metadata': self.metadata,
            'access_count': self.access_count,
            'last_access': self.last_access.isoformat() if self.last_access else None
        }
    
    @classmethod
    def from_dict(cls, data: Dict) -> 'VectorMemory':
        """从字典创建"""
        return cls(
            id=data['id'],
            user_id=data['user_id'],
            content=data['content'],
            embedding=data['embedding'],
            importance=data['importance'],
            timestamp=datetime.fromisoformat(data['timestamp']),
            metadata=data.get('metadata', {}),
            access_count=data.get('access_count', 0),
            last_access=datetime.fromisoformat(data['last_access']) if data.get('last_access') else None
        )


class VectorStore(ABC):
    """向量存储抽象基类"""
    
    @abstractmethod
    async def add(
        self,
        id: str,
        user_id: str,
        content: str,
        embedding: List[float],
        importance: float,
        metadata: Optional[Dict] = None
    ) -> bool:
        """添加记忆"""
        pass
    
    @abstractmethod
    async def search(
        self,
        user_id: str,
        query_embedding: List[float],
        limit: int = 5,
        min_importance: float = 0.3
    ) -> List[VectorMemory]:
        """搜索相似记忆"""
        pass
    
    @abstractmethod
    async def get_by_importance(
        self,
        user_id: str,
        limit: int = 5,
        min_importance: float = 0.3
    ) -> List[VectorMemory]:
        """按重要性获取记忆"""
        pass
    
    @abstractmethod
    async def update_access(self, memory_id: str) -> bool:
        """更新访问记录"""
        pass
    
    @abstractmethod
    async def delete(self, memory_id: str) -> bool:
        """删除记忆"""
        pass
    
    @abstractmethod
    async def get_all(self, user_id: str) -> List[VectorMemory]:
        """获取用户所有记忆"""
        pass
    
    @abstractmethod
    async def clear_user(self, user_id: str) -> bool:
        """清除用户所有记忆"""
        pass
    
    @abstractmethod
    async def close(self):
        """关闭连接"""
        pass
