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 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# ============================================================================
# backend/app/services/conversation_service.py
# ============================================================================


"""
Conversation Service - Business Logic Layer (UPDATED)

OPTIMIZED:
- Better error handling
- Smart title generation with fallbacks
- Async LLM title generation (optional)
- User verification in all operations
"""

import re
from typing import Optional, Dict, Any
from datetime import datetime

from app.db.repositories.conversation_repository import conversation_repository
from app.models.conversation import (
    Conversation,
    Message,
    ConversationListResult,
    CreateConversationRequest,
    UpdateConversationRequest
)


# ============================================================================
# CONVERSATION SERVICE
# ============================================================================

class ConversationService:
    """
    Business logic for conversation management.
    
    Handles validation, auto-titles, and business rules.
    """
    
    def __init__(self):
        """Initialize service"""
        self.repository = conversation_repository
        print("✅ ConversationService initialized")
    
    # ========================================================================
    # AUTO-TITLE GENERATION
    # ========================================================================
    
    def generate_title_from_message(
        self,
        message: str,
        max_length: int = 50
    ) -> str:
        """
        Generate conversation title from first user message.
        
        Optimized with better truncation logic.
        
        Args:
            message: First user message
            max_length: Maximum title length
        
        Returns:
            str: Generated title
        """
        message = message.strip()
        
        if not message:
            return "New Conversation"
        
        # Remove extra whitespace
        message = re.sub(r'\s+', ' ', message)
        
        # Try first sentence
        sentences = re.split(r'[.!?]+', message)
        first_sentence = sentences[0].strip()
        
        # Use more if first sentence too short
        if len(first_sentence) < 15 and len(sentences) > 1:
            first_sentence = f"{first_sentence}. {sentences[1].strip()}"
        
        # Truncate smartly
        if len(first_sentence) > max_length:
            title = first_sentence[:max_length].strip()
            # Break at word boundary
            last_space = title.rfind(' ')
            if last_space > max_length * 0.6:
                title = title[:last_space]
            title += "..."
        else:
            title = first_sentence
        
        # Capitalize
        if title:
            title = title[0].upper() + title[1:]
        
        # Remove trailing punctuation before ellipsis
        title = re.sub(r'[,;:]\.\.\.$', '...', title)
        
        return title if title else "New Conversation"
    
    async def generate_smart_title(
        self,
        first_message: str,
        llm_manager = None
    ) -> str:
        """
        Generate smart title using LLM (optional).
        
        Falls back gracefully if LLM unavailable.
        
        Args:
            first_message: First user message
            llm_manager: Optional LLM manager
        
        Returns:
            str: Generated title
        """
        # Try LLM generation if available
        if llm_manager:
            try:
                prompt = f"""Generate a concise title (max 50 chars) for this banking query:

"{first_message}"

Requirements:
- Clear and descriptive
- Banking/finance focused
- No quotes or formatting
- Maximum 50 characters

Title:"""
                
                # Use simple generation (not full chat)
                title = await llm_manager.generate_simple_response(
                    prompt=prompt,
                    max_tokens=15,
                    temperature=0.3
                )
                
                # Clean and validate
                title = title.strip().strip('"\'`')
                title = re.sub(r'\s+', ' ', title)
                
                if 5 < len(title) <= 60:
                    return title
            
            except Exception as e:
                print(f"⚠️ Smart title generation failed: {e}")
        
        # Fallback to simple generation
        return self.generate_title_from_message(first_message)
    
    # ========================================================================
    # CREATE
    # ========================================================================
    
    async def create_conversation(
        self,
        user_id: str,
        request: CreateConversationRequest = None,
        llm_manager = None
    ) -> Conversation:
        """
        Create a new conversation with optional first message.
        
        OPTIMIZED: Better title generation + error handling
        
        Args:
            user_id: User ID
            request: Optional create request
            llm_manager: Optional LLM manager
        
        Returns:
            Conversation: Created conversation (full object)
        """
        if request is None:
            request = CreateConversationRequest()
        
        # Determine title
        if request.title:
            title = request.title
        elif request.first_message:
            # Auto-generate from message
            title = await self.generate_smart_title(
                request.first_message,
                llm_manager
            )
        else:
            title = f"New Chat - {datetime.now().strftime('%b %d, %H:%M')}"
        
        # Create conversation (returns ID string)
        conversation_id = await self.repository.create_conversation(
            user_id=user_id,
            title=title,
            first_message=request.first_message
        )
        
        # Fetch full conversation
        conversation = await self.repository.get_conversation_by_id(
            conversation_id,
            user_id
        )
        
        if not conversation:
            raise ValueError("Failed to create conversation")
        
        return conversation
    
    # ========================================================================
    # READ
    # ========================================================================
    
    async def get_conversation(
        self,
        conversation_id: str,
        user_id: str
    ) -> Optional[Conversation]:
        """
        Get conversation with user verification.
        
        Args:
            conversation_id: Conversation ID
            user_id: User ID (must match owner)
        
        Returns:
            Conversation or None
        """
        return await self.repository.get_conversation_by_id(
            conversation_id,
            user_id
        )
    
    async def list_conversations(
        self,
        user_id: str,
        page: int = 1,
        page_size: int = 20,
        include_archived: bool = False
    ) -> ConversationListResult:
        """
        List conversations for user with pagination.
        
        Args:
            user_id: User ID
            page: Page number (1-indexed)
            page_size: Items per page
            include_archived: Include archived?
        
        Returns:
            ConversationListResult: Paginated list
        """
        # Validate pagination
        page = max(1, page)
        page_size = min(max(1, page_size), 100)  # Cap at 100
        
        return await self.repository.list_conversations(
            user_id=user_id,
            page=page,
            page_size=page_size,
            include_archived=include_archived
        )
    
    async def search_conversations(
        self,
        user_id: str,
        query: str,
        page: int = 1,
        page_size: int = 20
    ) -> ConversationListResult:
        """
        Search conversations by title/content.
        
        Args:
            user_id: User ID
            query: Search query
            page: Page number
            page_size: Items per page
        
        Returns:
            ConversationListResult: Search results
        """
        # Validate query
        if not query or len(query.strip()) < 2:
            # Return empty results for invalid query
            return ConversationListResult(
                conversations=[],
                total=0,
                page=page,
                page_size=page_size,
                has_more=False
            )
        
        return await self.repository.search_conversations(
            user_id=user_id,
            query=query.strip(),
            page=page,
            page_size=page_size
        )
    
    # ========================================================================
    # UPDATE
    # ========================================================================
    
    async def add_message_to_conversation(
        self,
        conversation_id: str,
        user_id: str,
        role: str,
        content: str,
        metadata: Optional[Dict[str, Any]] = None
    ) -> Optional[Conversation]:
        """
        Add message to conversation with validation.
        
        Args:
            conversation_id: Conversation ID
            user_id: User ID (must match owner)
            role: 'user' or 'assistant'
            content: Message content
            metadata: Optional metadata
        
        Returns:
            Updated Conversation or None
        """
        # Validate role
        if role not in ['user', 'assistant']:
            raise ValueError(f"Invalid role: {role}")
        
        # Validate content
        if not content or not content.strip():
            raise ValueError("Message content cannot be empty")
        
        # Verify ownership
        conversation = await self.get_conversation(conversation_id, user_id)
        if not conversation:
            return None
        
        # Create message
        message = Message(
            role=role,
            content=content.strip(),
            timestamp=datetime.utcnow(),
            metadata=metadata
        )
        
        # Add to repository
        success = await self.repository.add_message(
            conversation_id,
            message.dict()
        )
        
        if success:
            return await self.get_conversation(conversation_id, user_id)
        return None
    
    async def update_conversation(
        self,
        conversation_id: str,
        user_id: str,
        request: UpdateConversationRequest
    ) -> Optional[Conversation]:
        """
        Update conversation properties.
        
        Args:
            conversation_id: Conversation ID
            user_id: User ID (must match owner)
            request: Update request
        
        Returns:
            Updated Conversation or None
        """
        update_data = {}
        
        if request.title is not None:
            # Validate title
            title = request.title.strip()
            if not title:
                raise ValueError("Title cannot be empty")
            if len(title) > 100:
                raise ValueError("Title too long (max 100 chars)")
            update_data["title"] = title
        
        if request.is_archived is not None:
            update_data["is_archived"] = request.is_archived
        
        if not update_data:
            # Nothing to update
            return await self.get_conversation(conversation_id, user_id)
        
        return await self.repository.update_conversation(
            conversation_id,
            user_id,
            update_data
        )
    
    async def rename_conversation(
        self,
        conversation_id: str,
        user_id: str,
        new_title: str
    ) -> Optional[Conversation]:
        """
        Rename conversation with validation.
        
        Args:
            conversation_id: Conversation ID
            user_id: User ID
            new_title: New title
        
        Returns:
            Updated Conversation or None
        """
        # Validate title
        new_title = new_title.strip()
        if not new_title:
            raise ValueError("Title cannot be empty")
        if len(new_title) > 100:
            raise ValueError("Title too long (max 100 chars)")
        
        return await self.repository.rename_conversation(
            conversation_id,
            user_id,
            new_title
        )
    
    async def archive_conversation(
        self,
        conversation_id: str,
        user_id: str
    ) -> Optional[Conversation]:
        """Archive a conversation."""
        return await self.repository.archive_conversation(
            conversation_id,
            user_id,
            archived=True
        )
    
    async def unarchive_conversation(
        self,
        conversation_id: str,
        user_id: str
    ) -> Optional[Conversation]:
        """Unarchive a conversation."""
        return await self.repository.archive_conversation(
            conversation_id,
            user_id,
            archived=False
        )
    
    # ========================================================================
    # DELETE
    # ========================================================================
    
    async def delete_conversation(
        self,
        conversation_id: str,
        user_id: str,
        permanent: bool = False
    ) -> bool:
        """
        Delete conversation (with ownership verification).
        
        Args:
            conversation_id: Conversation ID
            user_id: User ID (must match owner)
            permanent: Hard delete if True
        
        Returns:
            bool: True if deleted
        """
        # Verify ownership first
        conversation = await self.get_conversation(conversation_id, user_id)
        if not conversation:
            return False
        
        return await self.repository.delete_conversation(
            conversation_id,
            soft_delete=not permanent
        )
    
    # ========================================================================
    # UTILITY
    # ========================================================================
    
    async def get_conversation_stats(
        self,
        user_id: str
    ) -> Dict[str, int]:
        """
        Get conversation statistics.
        
        Args:
            user_id: User ID
        
        Returns:
            dict: Stats with total, active, archived
        """
        return await self.repository.get_conversation_count(user_id)


# ============================================================================
# GLOBAL SERVICE INSTANCE
# ============================================================================

conversation_service = ConversationService()