"""
AI 对话模型
- ChatSession: 对话会话（按用户隔离）
- ChatMessage: 对话消息
"""
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, func
from app.db import Base


class ChatSession(Base):
    """对话会话表 — 每个用户可以有多个对话"""
    __tablename__ = "chat_sessions"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
    username = Column(String(64), nullable=False, index=True)
    title = Column(String(200), default="新对话")       # 对话标题（取首条消息摘要）
    active_skill_id = Column(String(80), nullable=True)
    workflow_state = Column(Text, nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())


class ChatMessage(Base):
    """对话消息表"""
    __tablename__ = "chat_messages"

    id = Column(Integer, primary_key=True, index=True)
    session_id = Column(Integer, ForeignKey("chat_sessions.id", ondelete="CASCADE"), nullable=False, index=True)
    role = Column(String(20), nullable=False)             # user / assistant / system
    content = Column(Text, nullable=False)                # 消息内容
    tool_calls = Column(Text, nullable=True)              # 工具调用 JSON（预留）
    created_at = Column(DateTime(timezone=True), server_default=func.now())
