"""Conversation-state service — create conversations, store messages, fetch history.""" from datetime import datetime from sqlalchemy.ext.asyncio import AsyncSession from sqlmodel import select from ..core.logging import get_logger from ..models.conversation import Conversation, Message logger = get_logger(__name__) async def create_conversation(session: AsyncSession, user_id: str) -> Conversation: """Insert a new Conversation row and return it.""" conv = Conversation(user_id=user_id) session.add(conv) await session.commit() await session.refresh(conv) logger.info("Conversation created: id=%d user_id=%s", conv.id, user_id) return conv async def get_conversation( session: AsyncSession, conversation_id: int, user_id: str ) -> Conversation | None: """Fetch a conversation by ID, scoped to the requesting user.""" logger.debug("Fetching conversation id=%d for user_id=%s", conversation_id, user_id) result = await session.execute( select(Conversation).where( Conversation.id == conversation_id, Conversation.user_id == user_id, ) ) return result.scalar_one_or_none() async def store_message( session: AsyncSession, conversation_id: int, user_id: str, role: str, content: str, ) -> Message: """Persist a message and bump the parent conversation's updated_at.""" msg = Message( conversation_id=conversation_id, user_id=user_id, role=role, content=content, ) session.add(msg) # Bump conversation timestamp conv_result = await session.execute( select(Conversation).where(Conversation.id == conversation_id) ) conv = conv_result.scalar_one_or_none() if conv: conv.updated_at = datetime.utcnow() session.add(conv) await session.commit() await session.refresh(msg) logger.info("Message stored: role=%s conversation_id=%d", role, conversation_id) return msg async def list_conversations(session: AsyncSession, user_id: str, limit: int = 30) -> list[Conversation]: """Return most-recently-updated conversations for a user.""" result = await session.execute( select(Conversation) .where(Conversation.user_id == user_id) .order_by(Conversation.updated_at.desc()) .limit(limit) ) return list(result.scalars().all()) async def get_history(session: AsyncSession, conversation_id: int) -> list[Message]: """Return all messages in a conversation, oldest first.""" logger.debug("Fetching history for conversation_id=%d", conversation_id) result = await session.execute( select(Message) .where(Message.conversation_id == conversation_id) .order_by(Message.created_at.asc()) ) msgs = list(result.scalars().all()) logger.debug("Fetched %d history messages for conversation_id=%d", len(msgs), conversation_id) return msgs