File size: 10,303 Bytes
676582c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""Conversations API endpoints for managing chat conversations."""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlmodel import Session
from typing import Dict, Any, List
import logging

from src.core.database import get_session
from src.core.security import get_current_user
from src.services.conversation_service import ConversationService
from src.schemas.conversation import (
    ConversationListResponse,
    ConversationSummary,
    MessageListResponse,
    MessageResponse,
    UpdateConversationRequest,
    UpdateConversationResponse
)

# Configure logging
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api", tags=["conversations"])


@router.get("/{user_id}/conversations", response_model=ConversationListResponse)
async def list_conversations(
    user_id: int,
    limit: int = Query(50, ge=1, le=100, description="Maximum number of conversations to return"),
    db: Session = Depends(get_session),
    current_user: Dict[str, Any] = Depends(get_current_user)
) -> ConversationListResponse:
    """List all conversations for a user.

    Args:
        user_id: ID of the user
        limit: Maximum number of conversations to return (default: 50, max: 100)
        db: Database session
        current_user: Authenticated user from JWT token

    Returns:
        ConversationListResponse with list of conversations

    Raises:
        HTTPException 401: If user is not authenticated or user_id doesn't match
    """
    # Verify user authorization
    if current_user["id"] != user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authorized to access this user's conversations"
        )

    try:
        conversation_service = ConversationService(db)
        conversations = conversation_service.get_user_conversations(user_id, limit=limit)

        # Build conversation summaries with message count and preview
        summaries: List[ConversationSummary] = []
        for conv in conversations:
            # Get messages for this conversation
            messages = conversation_service.get_conversation_messages(conv.id)
            message_count = len(messages)

            # Get last message preview
            last_message_preview = None
            if messages:
                last_msg = messages[-1]
                # Take first 100 characters of the last message
                last_message_preview = last_msg.content[:100]
                if len(last_msg.content) > 100:
                    last_message_preview += "..."

            summaries.append(ConversationSummary(
                id=conv.id,
                title=conv.title,
                created_at=conv.created_at,
                updated_at=conv.updated_at,
                message_count=message_count,
                last_message_preview=last_message_preview
            ))

        return ConversationListResponse(
            conversations=summaries,
            total=len(summaries)
        )

    except Exception as e:
        logger.exception(f"Failed to list conversations for user {user_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve conversations. Please try again."
        )


@router.get("/{user_id}/conversations/{conversation_id}/messages", response_model=MessageListResponse)
async def get_conversation_messages(
    user_id: int,
    conversation_id: int,
    offset: int = Query(0, ge=0, description="Number of messages to skip"),
    limit: int = Query(50, ge=1, le=200, description="Maximum number of messages to return"),
    db: Session = Depends(get_session),
    current_user: Dict[str, Any] = Depends(get_current_user)
) -> MessageListResponse:
    """Get message history for a conversation.

    Args:
        user_id: ID of the user
        conversation_id: ID of the conversation
        offset: Number of messages to skip (for pagination)
        limit: Maximum number of messages to return (default: 50, max: 200)
        db: Database session
        current_user: Authenticated user from JWT token

    Returns:
        MessageListResponse with list of messages

    Raises:
        HTTPException 401: If user is not authenticated or user_id doesn't match
        HTTPException 404: If conversation not found or user doesn't have access
    """
    # Verify user authorization
    if current_user["id"] != user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authorized to access this user's conversations"
        )

    try:
        conversation_service = ConversationService(db)

        # Verify conversation exists and belongs to user
        conversation = conversation_service.get_conversation(conversation_id, user_id)
        if not conversation:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Conversation {conversation_id} not found or you don't have access to it"
            )

        # Get all messages (we'll handle pagination manually)
        all_messages = conversation_service.get_conversation_messages(conversation_id)
        total = len(all_messages)

        # Apply pagination
        paginated_messages = all_messages[offset:offset + limit]

        # Convert to response format
        message_responses = [
            MessageResponse(
                id=msg.id,
                role=msg.role,
                content=msg.content,
                timestamp=msg.timestamp,
                token_count=msg.token_count
            )
            for msg in paginated_messages
        ]

        return MessageListResponse(
            conversation_id=conversation_id,
            messages=message_responses,
            total=total
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.exception(f"Failed to get messages for conversation {conversation_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve messages. Please try again."
        )


@router.patch("/{user_id}/conversations/{conversation_id}", response_model=UpdateConversationResponse)
async def update_conversation(
    user_id: int,
    conversation_id: int,
    request: UpdateConversationRequest,
    db: Session = Depends(get_session),
    current_user: Dict[str, Any] = Depends(get_current_user)
) -> UpdateConversationResponse:
    """Update a conversation's title.

    Args:
        user_id: ID of the user
        conversation_id: ID of the conversation
        request: UpdateConversationRequest with new title
        db: Database session
        current_user: Authenticated user from JWT token

    Returns:
        UpdateConversationResponse with updated conversation

    Raises:
        HTTPException 401: If user is not authenticated or user_id doesn't match
        HTTPException 404: If conversation not found or user doesn't have access
    """
    # Verify user authorization
    if current_user["id"] != user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authorized to access this user's conversations"
        )

    try:
        conversation_service = ConversationService(db)

        # Verify conversation exists and belongs to user
        conversation = conversation_service.get_conversation(conversation_id, user_id)
        if not conversation:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Conversation {conversation_id} not found or you don't have access to it"
            )

        # Update the title
        from datetime import datetime
        conversation.title = request.title
        conversation.updated_at = datetime.utcnow()
        db.add(conversation)
        db.commit()
        db.refresh(conversation)

        return UpdateConversationResponse(
            id=conversation.id,
            title=conversation.title,
            updated_at=conversation.updated_at
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.exception(f"Failed to update conversation {conversation_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to update conversation. Please try again."
        )


@router.delete("/{user_id}/conversations/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_conversation(
    user_id: int,
    conversation_id: int,
    db: Session = Depends(get_session),
    current_user: Dict[str, Any] = Depends(get_current_user)
) -> None:
    """Delete a conversation and all its messages.

    Args:
        user_id: ID of the user
        conversation_id: ID of the conversation
        db: Database session
        current_user: Authenticated user from JWT token

    Returns:
        None (204 No Content)

    Raises:
        HTTPException 401: If user is not authenticated or user_id doesn't match
        HTTPException 404: If conversation not found or user doesn't have access
    """
    # Verify user authorization
    if current_user["id"] != user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authorized to access this user's conversations"
        )

    try:
        conversation_service = ConversationService(db)

        # Delete the conversation (service method handles authorization check)
        deleted = conversation_service.delete_conversation(conversation_id, user_id)

        if not deleted:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Conversation {conversation_id} not found or you don't have access to it"
            )

        # Return 204 No Content (no response body)
        return None

    except HTTPException:
        raise
    except Exception as e:
        logger.exception(f"Failed to delete conversation {conversation_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to delete conversation. Please try again."
        )