from sqlalchemy import (
    Column,
    String,
    Text,
    Integer,
    Float,
    ForeignKey,
    Boolean,
    DateTime,
    Enum as SQLEnum,
    JSON,
)
from app.models.base import BaseModel, utc_now


class MemorySummary(BaseModel):
    """
    对话摘要 — 中期记忆
    当一段对话超过阈值轮数时，自动生成摘要存入此表
    """

    __tablename__ = "memory_summaries"

    user_id = Column(String(36), ForeignKey("users.id"), nullable=False, index=True)
    conversation_id = Column(String(36), ForeignKey("conversations.id"), nullable=False, index=True)
    summary_text = Column(Text, nullable=False)  # 摘要内容
    turn_count = Column(Integer, default=0)  # 摘要时累计轮数
    summary_at = Column(DateTime, default=utc_now, nullable=False)


class UserMemory(BaseModel):
    """
    用户画像记忆 — 长期记忆
    从对话中提取的用户事实、偏好、目标
    """

    __tablename__ = "user_memories"

    user_id = Column(String(36), ForeignKey("users.id"), nullable=False, index=True)
    memory_type = Column(String(50), nullable=False)  # fact | preference | goal | habit | other
    content = Column(Text, nullable=False)  # 记忆内容
    importance = Column(Integer, default=5)  # 重要程度 1-10 (legacy, replaced by importance_score)
    is_recalled = Column(Boolean, default=False)  # 是否在当前对话中被召回
    recall_count = Column(Integer, default=0)  # 被召回次数
    source_conversation_id = Column(String(36), nullable=True)  # 来源对话
    extracted_at = Column(DateTime, default=utc_now, nullable=False)
    last_recalled_at = Column(DateTime, nullable=True)
    # M.1: 重要性评分系统
    frequency_count = Column(
        Integer, default=0
    )  # 被召回次数 (duplicate of recall_count, for scoring clarity)
    emotion_tags = Column(JSON, nullable=True)  # List of emotion keywords
    importance_score = Column(Float, default=0.5)  # 重要性分数 0.0-1.0
    importance_level = Column(String(20), default="medium")  # high | medium | low
    associated_topics = Column(JSON, nullable=True)  # List of topic strings
    # M.2: 遗忘曲线系统
    decay_score = Column(Float, default=1.0)  # 0.0-1.0, higher=more remembered
    is_archived = Column(Boolean, default=False)  # 是否已归档到冷存储
    last_accessed_at = Column(DateTime, nullable=True)  # 上次访问时间（用于遗忘计算）
    archive_at = Column(DateTime, nullable=True)  # 归档时间
