"""Chat API endpoints for AI chatbot.""" from typing import Optional from uuid import UUID from fastapi import APIRouter, HTTPException, Query, status from .deps import DBSession, CurrentUser from .models.chat import ( ChatRequest, ChatResponse, ToolCallInfo, MessageRead, ConversationRead, ConversationListResponse, ConversationMessagesResponse, ) from ..services.chatbot import ChatbotService router = APIRouter(prefix="/api/chat", tags=["chat"]) @router.post("", response_model=ChatResponse) async def send_chat_message( request: ChatRequest, session: DBSession, current_user: CurrentUser, ) -> ChatResponse: """ Send a message to the AI chatbot. The chatbot can: - Add, list, complete, update, and delete tasks via natural language - Answer identity queries ("Who am I?") - Chain multiple operations in a single message Optionally provide conversation_id to continue an existing conversation. If not provided, a new conversation will be created. """ # Parse conversation_id if provided conversation_id: Optional[UUID] = None if request.conversation_id: try: conversation_id = UUID(request.conversation_id) except ValueError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid conversation_id format", ) # Get user info user_uuid = UUID(current_user.user_id) user_email = current_user.email # Create chatbot service and process message chatbot = ChatbotService( session=session, user_id=user_uuid, user_email=user_email, ) try: result = await chatbot.chat( message=request.message, conversation_id=conversation_id, ) except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Chat service error: {str(e)}", ) return ChatResponse( conversation_id=result["conversation_id"], response=result["response"], tool_calls=[ToolCallInfo(**tc) for tc in result.get("tool_calls", [])], ) @router.get("/conversations", response_model=ConversationListResponse) async def list_conversations( session: DBSession, current_user: CurrentUser, limit: int = Query(default=50, le=100, ge=1), offset: int = Query(default=0, ge=0), ) -> ConversationListResponse: """ List the user's chat conversations. Returns conversations ordered by most recent first. """ user_uuid = UUID(current_user.user_id) chatbot = ChatbotService( session=session, user_id=user_uuid, user_email=current_user.email, ) conversations = await chatbot.get_conversations(limit=limit, offset=offset) return ConversationListResponse( conversations=[ ConversationRead( id=str(c.id), user_id=str(c.user_id), title=c.title, created_at=c.created_at, updated_at=c.updated_at, ) for c in conversations ], total=len(conversations), ) @router.get("/conversations/{conversation_id}/messages", response_model=ConversationMessagesResponse) async def get_conversation_messages( conversation_id: str, session: DBSession, current_user: CurrentUser, ) -> ConversationMessagesResponse: """ Get messages for a specific conversation. Returns messages in chronological order. """ try: conv_uuid = UUID(conversation_id) except ValueError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid conversation_id format", ) user_uuid = UUID(current_user.user_id) chatbot = ChatbotService( session=session, user_id=user_uuid, user_email=current_user.email, ) messages = await chatbot.get_conversation_messages(conv_uuid) if not messages: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found or you don't have access", ) return ConversationMessagesResponse( conversation_id=conversation_id, messages=[ MessageRead( id=str(m.id), conversation_id=str(m.conversation_id), role=m.role.value, content=m.content, created_at=m.created_at, ) for m in messages ], )