"""
智能体模型
"""
from sqlalchemy import Column, String, Text, Float, Integer, Boolean, JSON, Index

from app.base_model import BaseModel


class Agent(BaseModel):
    """
    智能体定义
    
    智能体是一个能够自主决策、调用工具、多轮推理的 AI 实体
    支持两种模式：
    - autonomous: 自主规划模式 - Agent 自动拆解任务并执行
    - dialog_flow: 对话流模式 - 按预定义流程与用户交互
    """
    __tablename__ = "ai_agent"
    
    application_id = Column(String(21), nullable=True, index=True, comment="所属应用ID（逻辑外键关联core_application）")
    is_global = Column(Boolean, default=False, comment="是否在子应用中可见")
    name = Column(String(100), nullable=False, comment="智能体名称")
    code = Column(String(100), unique=True, nullable=False, comment="智能体编码")
    description = Column(Text, default="", comment="智能体描述")
    avatar = Column(String(500), default="", comment="头像 URL")
    mode = Column(String(20), default="autonomous", comment="运行模式: autonomous/dialog_flow")
    status = Column(String(20), default="draft", comment="状态: draft/published/disabled")
    persona = Column(JSON, default=dict, comment="人设配置")
    system_prompt = Column(Text, default="", comment="系统提示词")
    model_id = Column(String(21), nullable=True, index=True, comment="默认模型ID（逻辑外键关联ai_llm_model）")
    temperature = Column(Float, default=0.7, comment="温度参数（0-2）")
    top_p = Column(Float, default=1.0, comment="top_p 参数")
    max_tokens = Column(Integer, default=4096, comment="最大输出 Token")
    max_iterations = Column(Integer, default=10, comment="最大推理轮数")
    welcome_message = Column(Text, default="", comment="开场白")
    suggested_questions = Column(JSON, default=list, comment="推荐问题列表")
    workflow_id = Column(String(21), nullable=True, index=True, comment="关联工作流ID（逻辑外键关联ai_workflow）")
    enable_memory = Column(Boolean, default=False, comment="是否启用对话记忆")
    memory_window = Column(Integer, default=10, comment="记忆窗口大小（最近 N 轮对话）")
    enable_streaming = Column(Boolean, default=True, comment="是否启用流式输出（自主规划模式）")
    knowledge_base_ids = Column(JSON, default=list, comment="关联的知识库ID列表")
    knowledge_config = Column(JSON, default=dict, comment="知识库检索配置(top_k/score_threshold/retrieval_mode等)")
    is_public = Column(Boolean, default=False, comment="是否公开")
    conversation_count = Column(Integer, default=0, comment="对话数量")
    message_count = Column(Integer, default=0, comment="消息数量")
    total_tokens = Column(Integer, default=0, comment="总 Token 消耗")


class AgentConversation(BaseModel):
    """
    智能体对话
    """
    __tablename__ = "ai_agent_conversation"
    
    agent_id = Column(String(21), nullable=False, index=True, comment="智能体ID（逻辑外键关联ai_agent）")
    user_id = Column(String(21), nullable=True, index=True, comment="用户ID（逻辑外键关联core_user）")
    title = Column(String(200), default="", comment="对话标题")
    summary = Column(Text, default="", comment="对话摘要")
    workflow_run_id = Column(String(21), nullable=True, comment="工作流运行实例ID（逻辑外键关联ai_workflow_run）")
    waiting_node_id = Column(String(100), default="", comment="等待输入的节点 ID")
    extra_data = Column(JSON, default=dict, comment="元数据")
    message_count = Column(Integer, default=0, comment="消息数量")
    total_tokens = Column(Integer, default=0, comment="总 Token 消耗")
    
    __table_args__ = (
        Index("ix_ai_agent_conversation_agent_user", "agent_id", "user_id"),
    )


class AgentMessage(BaseModel):
    """
    智能体消息
    
    记录对话中的每条消息，包括用户消息、助手回复、工具调用等
    """
    __tablename__ = "ai_agent_message"
    
    conversation_id = Column(String(21), nullable=False, index=True, comment="对话ID（逻辑外键关联ai_agent_conversation）")
    role = Column(String(20), nullable=False, comment="角色: user/assistant/tool/system")
    content = Column(Text, default="", comment="消息内容")
    attachments = Column(JSON, default=list, comment="附件列表 [{id, type, name, url, mime_type, size}]")
    status = Column(String(20), default="completed", comment="状态: pending/completed/failed")
    reasoning_steps = Column(JSON, default=list, comment="推理步骤")
    tool_calls = Column(JSON, default=list, comment="工具调用记录")
    prompt_tokens = Column(Integer, default=0, comment="提示 Token")
    completion_tokens = Column(Integer, default=0, comment="生成 Token")
    total_tokens = Column(Integer, default=0, comment="总 Token")
    elapsed_time = Column(Integer, default=0, comment="耗时（毫秒）")
    error_message = Column(Text, default="", comment="错误信息")
    feedback = Column(String(20), default="", comment="用户反馈（like/dislike）")
    feedback_content = Column(Text, default="", comment="反馈内容")
    
    __table_args__ = (
        Index("ix_ai_agent_message_conversation_role", "conversation_id", "role"),
    )
