"""
对话模型
"""
from sqlalchemy import Column, String, Text, Float, Integer, Boolean, Index

from app.base_model import BaseModel


class Conversation(BaseModel):
    """
    对话
    """
    __tablename__ = "ai_conversation"
    
    app_id = Column(String(21), nullable=False, index=True, comment="所属应用ID（逻辑外键关联ai_app）")
    user_id = Column(String(21), nullable=False, index=True, comment="用户ID（逻辑外键关联core_user）")
    title = Column(String(200), default="", comment="对话标题")
    model_override_id = Column(String(21), nullable=True, comment="覆盖模型ID（逻辑外键关联ai_llm_model）")
    temperature_override = Column(Float, nullable=True, comment="覆盖温度参数")
    message_count = Column(Integer, default=0, comment="消息数量")
    total_tokens = Column(Integer, default=0, comment="总 Token 数")
    is_pinned = Column(Boolean, default=False, comment="是否置顶")
    
    __table_args__ = (
        Index("ix_ai_conversation_user_app", "user_id", "app_id"),
    )


class Message(BaseModel):
    """
    消息
    """
    __tablename__ = "ai_message"
    
    conversation_id = Column(String(21), nullable=False, index=True, comment="所属对话ID（逻辑外键关联ai_conversation）")
    role = Column(String(20), nullable=False, comment="角色: system/user/assistant")
    content = Column(Text, nullable=False, comment="消息内容")
    status = Column(String(20), default="completed", comment="状态: pending/completed/failed/stopped")
    prompt_tokens = Column(Integer, default=0, comment="提示 Token 数")
    completion_tokens = Column(Integer, default=0, comment="补全 Token 数")
    total_tokens = Column(Integer, default=0, comment="总 Token 数")
    model_name = Column(String(100), default="", comment="使用的模型名称")
    latency = Column(Integer, default=0, comment="响应耗时（毫秒）")
    error_message = Column(Text, default="", comment="错误信息")
    parent_message_id = Column(String(21), nullable=True, comment="父消息ID（逻辑外键关联自身）")
    feedback = Column(String(20), default="", comment="用户反馈: like/dislike")
    
    __table_args__ = (
        Index("ix_ai_message_conversation_created", "conversation_id", "sys_create_datetime"),
    )
