""" Chat ORM Models. Stores HedgeAI chat sessions and messages for conversation persistence. """ from __future__ import annotations from datetime import datetime from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, func from sqlalchemy.orm import Mapped, mapped_column, relationship from app.database import Base class ChatSession(Base): __tablename__ = "chat_sessions" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True) title: Mapped[str] = mapped_column(String(255), nullable=False, default="New Chat") created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False ) # Relationships user = relationship("User", back_populates="chat_sessions") messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan", order_by="ChatMessage.created_at") def __repr__(self) -> str: return f"" class ChatMessage(Base): __tablename__ = "chat_messages" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) session_id: Mapped[int] = mapped_column(Integer, ForeignKey("chat_sessions.id", ondelete="CASCADE"), nullable=False, index=True) role: Mapped[str] = mapped_column(String(20), nullable=False) # 'user' or 'assistant' content: Mapped[str] = mapped_column(Text, nullable=False) intent: Mapped[str] = mapped_column(String(50), nullable=True) actions_json: Mapped[str] = mapped_column(Text, nullable=True) # JSON string of actions created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) # Relationships session = relationship("ChatSession", back_populates="messages") def __repr__(self) -> str: return f""