from datetime import datetime from sqlalchemy import JSON, Column, DateTime, ForeignKey, Integer, String, Text from sqlalchemy.orm import relationship from app.database import Base class Conversation(Base): """One AI Mode thread, belonging to one learner.""" __tablename__ = "conversations" id = Column(Integer, primary_key=True, index=True) user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True) title = Column(String(200), nullable=False, default="New chat") created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) messages = relationship("ConversationMessage", back_populates="conversation", cascade="all, delete-orphan", order_by="ConversationMessage.id") class ConversationMessage(Base): """A turn in a thread. `citations` holds what the answer was allowed to cite *after* the server filtered it, so reopening a thread shows the same links it showed at the time — not a fresh retrieval that may now rank differently. """ __tablename__ = "conversation_messages" id = Column(Integer, primary_key=True, index=True) conversation_id = Column(Integer, ForeignKey("conversations.id", ondelete="CASCADE"), nullable=False, index=True) role = Column(String(16), nullable=False) # user | assistant content = Column(Text, nullable=False) citations = Column(JSON, nullable=False, default=list) created_at = Column(DateTime, default=datetime.utcnow) conversation = relationship("Conversation", back_populates="messages")