File size: 28,251 Bytes
8275526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
from flask import Blueprint, request, jsonify
import logging
from bson.objectid import ObjectId
from models.conversation_model import Conversation
from models.user_model import User
from flask_jwt_extended import jwt_required, get_jwt_identity

# Cấu hình logging
logger = logging.getLogger(__name__)

# Tạo blueprint
history_routes = Blueprint('history', __name__)

# Hàm đơn giản để tạo tiêu đề từ tin nhắn
def create_title_from_message(message, max_length=50):
    """Tạo tiêu đề cuộc trò chuyện từ tin nhắn đầu tiên của người dùng"""
    # Loại bỏ ký tự xuống dòng và khoảng trắng thừa
    message = message.strip().replace('\n', ' ')
    
    # Nếu tin nhắn đủ ngắn, sử dụng làm tiêu đề luôn
    if len(message) <= max_length:
        return message
    
    # Nếu tin nhắn quá dài, cắt ngắn và thêm dấu "..."
    return message[:max_length-3] + "..."

@history_routes.route('/conversations', methods=['GET'])
@jwt_required()
def get_conversations():
    """API endpoint để lấy danh sách cuộc hội thoại của người dùng"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy tham số phân trang từ query string
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 50))  # ✅ TĂNG default per_page
        include_archived = request.args.get('include_archived', 'false').lower() == 'true'
        
        # Tính toán offset
        skip = (page - 1) * per_page
        
        logger.info(f"🔍 Getting conversations for user {user_id}, page {page}, per_page {per_page}, include_archived {include_archived}")
        
        # Lấy danh sách cuộc hội thoại
        conversations = Conversation.find_by_user(
            user_id=user_id,
            limit=per_page,
            skip=skip,
            include_archived=include_archived
        )
        
        # Đếm tổng số cuộc hội thoại
        total_count = Conversation.count_by_user(
            user_id=user_id,
            include_archived=include_archived
        )
        
        logger.info(f"📊 Found {len(conversations)} conversations, total: {total_count}")
        
        # Chuẩn bị dữ liệu phản hồi
        result = []
        for conversation in conversations:
            # Chỉ lấy tin nhắn mới nhất để hiển thị xem trước
            last_message = conversation.messages[-1]["content"] if conversation.messages else ""
            message_count = len(conversation.messages)
            
            result.append({
                "id": str(conversation.conversation_id),
                "title": conversation.title,
                "created_at": conversation.created_at.isoformat(),
                "updated_at": conversation.updated_at.isoformat(),
                "age_context": conversation.age_context,
                "is_archived": conversation.is_archived,
                "last_message": last_message[:100] + "..." if len(last_message) > 100 else last_message,
                "message_count": message_count
            })
        
        logger.info(f"✅ Returning {len(result)} conversations")
        
        # Tạo phản hồi với thông tin phân trang
        return jsonify({
            "success": True,
            "conversations": result,
            "pagination": {
                "page": page,
                "per_page": per_page,
                "total": total_count,
                "pages": (total_count + per_page - 1) // per_page  # Ceiling division
            }
        })
        
    except Exception as e:
        logger.error(f"❌ Lỗi khi lấy danh sách cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>', methods=['GET'])
@jwt_required()
def get_conversation_detail(conversation_id):
    """API endpoint để lấy chi tiết một cuộc hội thoại"""
    try:
        user_id = get_jwt_identity()
        
        def safe_datetime_to_string(dt_obj):
            """Safely convert datetime object to ISO string"""
            if dt_obj is None:
                return None
            # Nếu đã là string, return nguyên
            if isinstance(dt_obj, str):
                return dt_obj
            # Nếu là datetime object, convert sang string
            if hasattr(dt_obj, 'isoformat'):
                return dt_obj.isoformat()
            # Fallback: convert to string
            return str(dt_obj)
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền truy cập cuộc hội thoại này"
            }), 403
        
        conversation_data = {
            "id": str(conversation.conversation_id),
            "title": conversation.title,
            "created_at": safe_datetime_to_string(conversation.created_at),
            "updated_at": safe_datetime_to_string(conversation.updated_at), 
            "age_context": conversation.age_context,
            "is_archived": conversation.is_archived,
            "messages": []
        }
        
        for message in conversation.messages:
            message_data = {
                "id": str(message["_id"]),
                "_id": str(message["_id"]),
                "role": message["role"],
                "content": message["content"],
                "timestamp": safe_datetime_to_string(message.get("timestamp")),
                "current_version": message.get("current_version", 1),
                "is_edited": message.get("is_edited", False) 
            }
            
            if "versions" in message and message["versions"]:
                message_data["versions"] = []
                for version in message["versions"]:
                    version_data = {
                        "content": version["content"],
                        "timestamp": safe_datetime_to_string(version.get("timestamp")),
                        "version": version["version"]
                    }
                    
                    # Thêm sources cho version nếu có
                    if "sources" in version:
                        version_data["sources"] = version["sources"]
                    
                    # Thêm metadata cho version nếu có  
                    if "metadata" in version:
                        version_data["metadata"] = version["metadata"]
                    
                    # conversation_snapshot chỉ dùng để restore, không cần trả về frontend
                    message_data["versions"].append(version_data)
            else:
                # Nếu không có versions, tạo default version
                message_data["versions"] = [{
                    "content": message["content"],
                    "timestamp": safe_datetime_to_string(message.get("timestamp")),
                    "version": 1
                }]
            
            # Thêm sources nếu có
            if "sources" in message:
                message_data["sources"] = message["sources"]
                
            # Thêm metadata nếu có
            if "metadata" in message:
                message_data["metadata"] = message["metadata"]
                
            conversation_data["messages"].append(message_data)
        
        return jsonify({
            "success": True,
            "conversation": conversation_data
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi lấy chi tiết cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations', methods=['POST'])
@jwt_required()
def create_conversation():
    """API endpoint để tạo cuộc hội thoại mới"""
    try:
        data = request.json
        user_id = get_jwt_identity()
            
        # Lấy thông tin user
        user = User.find_by_id(user_id)
        if not user:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy thông tin người dùng"
            }), 404
            
        # Tạo cuộc hội thoại mới
        title = data.get('title', 'Cuộc trò chuyện mới')
        age_context = data.get('age_context')
        
        # ✅ SỬA: Sử dụng Conversation.create thay vì khởi tạo trực tiếp
        conversation_id = Conversation.create(
            user_id=user_id,
            title=title,
            age_context=age_context
        )
        
        logger.info(f"✅ Created new conversation {conversation_id} for user {user_id}")
        
        return jsonify({
            "success": True,
            "message": "Đã tạo cuộc hội thoại mới",
            "conversation_id": str(conversation_id)
        })
        
    except Exception as e:
        logger.error(f"❌ Lỗi khi tạo cuộc hội thoại mới: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>', methods=['PUT'])
@jwt_required()
def update_conversation(conversation_id):
    """API endpoint để cập nhật thông tin cuộc hội thoại"""
    try:
        data = request.json
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền cập nhật cuộc hội thoại này"
            }), 403
        
        # Cập nhật thông tin
        if 'title' in data:
            conversation.title = data['title']
            
        if 'age_context' in data:
            conversation.age_context = data['age_context']
            
        if 'is_archived' in data:
            conversation.is_archived = data['is_archived']
        
        # Lưu thay đổi
        conversation.save()
        
        logger.info(f"✅ Updated conversation {conversation_id}")
        
        return jsonify({
            "success": True,
            "message": "Đã cập nhật thông tin cuộc hội thoại"
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi cập nhật thông tin cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>', methods=['DELETE'])
@jwt_required()
def delete_conversation(conversation_id):
    """API endpoint để xóa cuộc hội thoại"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền xóa cuộc hội thoại này"
            }), 403
        
        # Xóa cuộc hội thoại
        conversation.delete()
        
        logger.info(f"✅ Deleted conversation {conversation_id}")
        
        return jsonify({
            "success": True,
            "message": "Đã xóa cuộc hội thoại"
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi xóa cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>/archive', methods=['POST'])
@jwt_required()
def archive_conversation(conversation_id):
    """API endpoint để lưu trữ cuộc hội thoại"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền lưu trữ cuộc hội thoại này"
            }), 403
        
        # Lưu trữ cuộc hội thoại
        conversation.is_archived = True
        conversation.save()
        
        return jsonify({
            "success": True,
            "message": "Đã lưu trữ cuộc hội thoại"
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi lưu trữ cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>/unarchive', methods=['POST'])
@jwt_required()
def unarchive_conversation(conversation_id):
    """API endpoint để hủy lưu trữ cuộc hội thoại"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền hủy lưu trữ cuộc hội thoại này"
            }), 403
        
        # Hủy lưu trữ cuộc hội thoại
        conversation.is_archived = False
        conversation.save()
        
        return jsonify({
            "success": True,
            "message": "Đã hủy lưu trữ cuộc hội thoại"
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi hủy lưu trữ cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/search', methods=['GET'])
@jwt_required()
def search_conversations():
    """API endpoint để tìm kiếm cuộc hội thoại theo nội dung"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy tham số từ query string
        query = request.args.get('q', '')
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        
        # Tính toán offset
        skip = (page - 1) * per_page
        
        # Kiểm tra từ khóa tìm kiếm
        if not query:
            return jsonify({
                "success": False,
                "error": "Vui lòng nhập từ khóa tìm kiếm"
            }), 400
            
        # Tìm kiếm cuộc hội thoại
        conversations = Conversation.search_by_content(
            user_id=user_id,
            query=query,
            limit=per_page,
            skip=skip
        )
        
        # Chuẩn bị dữ liệu phản hồi
        result = []
        for conversation in conversations:
            # Tìm tin nhắn chứa từ khóa tìm kiếm
            matching_messages = [m for m in conversation.messages if query.lower() in m["content"].lower()]
            
            result.append({
                "id": str(conversation.conversation_id),
                "title": conversation.title,
                "created_at": conversation.created_at.isoformat(),
                "updated_at": conversation.updated_at.isoformat(),
                "age_context": conversation.age_context,
                "is_archived": conversation.is_archived,
                "message_count": len(conversation.messages),
                "matching_messages": len(matching_messages),
                "preview": matching_messages[0]["content"][:100] + "..." if matching_messages else ""
            })
        
        return jsonify({
            "success": True,
            "conversations": result,
            "query": query
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi tìm kiếm cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>/messages', methods=['POST'])
@jwt_required()
def add_message(conversation_id):
    """API endpoint để thêm tin nhắn mới vào cuộc hội thoại"""
    try:
        data = request.json
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền thêm tin nhắn vào cuộc hội thoại này"
            }), 403
        
        # Lấy thông tin tin nhắn
        role = data.get('role')
        content = data.get('content')
        sources = data.get('sources')
        metadata = data.get('metadata')
        
        # Kiểm tra dữ liệu
        if not role or not content:
            return jsonify({
                "success": False,
                "error": "Vui lòng cung cấp role và content cho tin nhắn"
            }), 400
            
        # Kiểm tra role hợp lệ
        if role not in ["user", "bot"]:
            return jsonify({
                "success": False,
                "error": "Role không hợp lệ, chỉ chấp nhận 'user' hoặc 'bot'"
            }), 400
        
        # Thêm tin nhắn mới
        message_id = conversation.add_message(
            role=role,
            content=content,
            sources=sources,
            metadata=metadata
        )
        
        return jsonify({
            "success": True,
            "message": "Đã thêm tin nhắn mới",
            "message_id": str(message_id)
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi thêm tin nhắn mới: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/stats', methods=['GET'])
@jwt_required()
def get_user_conversation_stats():
    """API endpoint để lấy thống kê cuộc hội thoại của người dùng"""
    try:
        user_id = get_jwt_identity()
            
        # Lấy tổng số cuộc hội thoại
        total_conversations = Conversation.count_by_user(
            user_id=user_id,
            include_archived=True
        )
        
        # Lấy số cuộc hội thoại đã lưu trữ
        archived_conversations = Conversation.count_by_user(
            user_id=user_id,
            include_archived=True
        ) - Conversation.count_by_user(
            user_id=user_id,
            include_archived=False
        )
        
        # Lấy danh sách cuộc hội thoại để tính số tin nhắn
        all_conversations = Conversation.find_by_user(
            user_id=user_id,
            limit=100,  # Giới hạn 100 cuộc hội thoại gần nhất để tính thống kê
            skip=0,
            include_archived=True
        )
        
        # Tính số tin nhắn và số ngày
        total_messages = 0
        messages_by_date = {}
        
        for conversation in all_conversations:
            total_messages += len(conversation.messages)
            
            # Đếm số tin nhắn theo ngày
            for message in conversation.messages:
                date_str = message["timestamp"].strftime("%Y-%m-%d")
                if date_str not in messages_by_date:
                    messages_by_date[date_str] = 0
                messages_by_date[date_str] += 1
        
        # Sắp xếp ngày và lấy 7 ngày gần nhất
        sorted_dates = sorted(messages_by_date.keys(), reverse=True)[:7]
        recent_activity = {date: messages_by_date[date] for date in sorted_dates}
        
        # Tính trung bình số tin nhắn mỗi cuộc hội thoại
        avg_messages = total_messages / total_conversations if total_conversations > 0 else 0
        
        return jsonify({
            "success": True,
            "stats": {
                "total_conversations": total_conversations,
                "archived_conversations": archived_conversations,
                "total_messages": total_messages,
                "avg_messages_per_conversation": round(avg_messages, 1),
                "recent_activity": recent_activity
            }
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi lấy thống kê cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>/export', methods=['GET'])
@jwt_required()
def export_conversation(conversation_id):
    """API endpoint để xuất cuộc hội thoại dưới dạng JSON"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền xuất cuộc hội thoại này"
            }), 403
        
        # Chuẩn bị dữ liệu xuất
        export_data = {
            "id": str(conversation.conversation_id),
            "title": conversation.title,
            "created_at": conversation.created_at.isoformat(),
            "updated_at": conversation.updated_at.isoformat(),
            "age_context": conversation.age_context,
            "messages": []
        }
        
        # Chuẩn bị danh sách tin nhắn
        for message in conversation.messages:
            message_data = {
                "role": message["role"],
                "content": message["content"],
                "timestamp": message["timestamp"].isoformat()
            }
            
            # Thêm sources nếu có
            if "sources" in message:
                message_data["sources"] = message["sources"]
                
            export_data["messages"].append(message_data)
        
        return jsonify(export_data)
        
    except Exception as e:
        logger.error(f"Lỗi khi xuất cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/bulk-delete', methods=['POST'])
@jwt_required()
def bulk_delete_conversations():
    """API endpoint để xóa nhiều cuộc hội thoại cùng lúc"""
    try:
        data = request.json
        user_id = get_jwt_identity()
        
        conversation_ids = data.get('conversation_ids', [])
        
        if not conversation_ids:
            return jsonify({
                "success": False,
                "error": "Vui lòng cung cấp danh sách IDs cuộc hội thoại"
            }), 400
        
        # Duyệt qua từng ID và xóa
        deleted_count = 0
        failed_ids = []
        
        for conv_id in conversation_ids:
            try:
                # Lấy thông tin cuộc hội thoại
                conversation = Conversation.find_by_id(conv_id)
                
                # Kiểm tra quyền truy cập và xóa nếu hợp lệ
                if conversation and str(conversation.user_id) == user_id:
                    conversation.delete()
                    deleted_count += 1
                else:
                    failed_ids.append(conv_id)
            except Exception:
                failed_ids.append(conv_id)
                continue
        
        return jsonify({
            "success": True,
            "message": f"Đã xóa {deleted_count}/{len(conversation_ids)} cuộc hội thoại",
            "deleted_count": deleted_count,
            "failed_ids": failed_ids
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi xóa nhiều cuộc hội thoại: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@history_routes.route('/conversations/<conversation_id>/generate-title', methods=['POST'])
@jwt_required()
def generate_title_for_conversation(conversation_id):
    """API endpoint để tạo tự động tiêu đề cho cuộc hội thoại dựa trên nội dung"""
    try:
        user_id = get_jwt_identity()
        
        # Lấy thông tin cuộc hội thoại
        conversation = Conversation.find_by_id(conversation_id)
        
        if not conversation:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy cuộc hội thoại"
            }), 404
        
        # Kiểm tra quyền truy cập
        if str(conversation.user_id) != user_id:
            return jsonify({
                "success": False,
                "error": "Bạn không có quyền cập nhật cuộc hội thoại này"
            }), 403
            
        # Kiểm tra số lượng tin nhắn
        if len(conversation.messages) < 2:
            return jsonify({
                "success": False,
                "error": "Cuộc hội thoại cần ít nhất 2 tin nhắn để tạo tiêu đề"
            }), 400
        
        # Lấy nội dung tin nhắn đầu tiên của người dùng
        first_user_message = None
        for message in conversation.messages:
            if message["role"] == "user":
                first_user_message = message["content"]
                break
                
        if not first_user_message:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy tin nhắn của người dùng"
            }), 400
            
        # Tạo tiêu đề từ nội dung
        title = create_title_from_message(first_user_message)
            
        # Cập nhật tiêu đề
        conversation.title = title
        conversation.save()
        
        return jsonify({
            "success": True,
            "message": "Đã tạo tiêu đề mới",
            "title": title
        })
        
    except Exception as e:
        logger.error(f"Lỗi khi tạo tiêu đề: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500