File size: 77,001 Bytes
6c982a7
 
eda7f22
6c982a7
eda7f22
6c982a7
 
 
eda7f22
 
 
 
6c982a7
 
 
5aa7215
358773d
5aa7215
 
6c982a7
 
 
eda7f22
 
 
 
 
 
 
 
 
 
 
 
6c982a7
 
 
 
 
eda7f22
 
6c982a7
eda7f22
6c982a7
 
eda7f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358773d
5aa7215
 
 
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
c99ab26
5aa7215
 
 
 
 
 
 
 
6c982a7
 
 
eda7f22
6c982a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eda7f22
 
 
 
 
358773d
 
 
 
 
 
 
 
eda7f22
 
 
 
5aa7215
 
 
 
 
 
358773d
 
 
 
 
 
eda7f22
 
 
 
 
 
5aa7215
358773d
eda7f22
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
6c982a7
 
911cc77
6c982a7
 
5aa7215
 
358773d
 
6c982a7
5aa7215
 
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
 
eda7f22
358773d
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
3900fea
5aa7215
3900fea
 
 
911cc77
3900fea
911cc77
5aa7215
 
 
358773d
 
 
3900fea
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
911cc77
 
5aa7215
 
 
 
 
911cc77
5aa7215
 
 
911cc77
 
5aa7215
 
 
 
 
 
 
 
911cc77
5aa7215
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
 
 
911cc77
5aa7215
 
 
 
 
 
 
 
 
 
 
 
358773d
 
 
 
5aa7215
 
 
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
 
 
911cc77
 
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911cc77
 
5aa7215
 
 
 
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911cc77
358773d
 
 
 
 
5aa7215
 
 
911cc77
5aa7215
 
 
 
 
 
 
 
 
 
 
 
911cc77
 
5aa7215
 
 
 
 
 
911cc77
 
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911cc77
eda7f22
911cc77
5aa7215
 
 
 
 
911cc77
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911cc77
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911cc77
 
 
 
5aa7215
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
eda7f22
6c982a7
 
 
 
 
5aa7215
3900fea
 
 
358773d
 
 
 
6c982a7
 
5aa7215
358773d
6c982a7
 
3900fea
5aa7215
 
3900fea
 
358773d
 
 
 
 
6c982a7
 
 
 
 
3900fea
358773d
 
 
 
 
 
 
 
 
 
 
3900fea
 
 
 
 
 
 
 
 
 
6c982a7
 
5aa7215
 
 
6c982a7
5aa7215
 
6c982a7
5aa7215
 
 
358773d
 
 
 
 
 
 
 
 
 
5aa7215
 
 
358773d
 
5aa7215
358773d
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
6c982a7
 
5aa7215
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c982a7
 
 
 
 
 
5aa7215
 
 
3900fea
 
 
358773d
 
 
 
 
 
6c982a7
 
 
 
 
 
 
 
 
 
 
5aa7215
358773d
6c982a7
 
358773d
 
5aa7215
 
6c982a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eda7f22
 
 
 
 
 
 
5aa7215
358773d
eda7f22
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
358773d
 
 
 
 
eda7f22
 
 
 
 
5aa7215
358773d
eda7f22
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eda7f22
 
5aa7215
 
358773d
 
eda7f22
5aa7215
358773d
 
 
 
 
 
5aa7215
 
 
 
 
 
358773d
 
 
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358773d
 
 
 
 
 
5aa7215
 
358773d
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
 
 
 
eda7f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
065c4b9
eda7f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
eda7f22
 
 
 
5aa7215
 
358773d
 
eda7f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa7215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c982a7
 
 
 
 
 
 
 
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, List, Dict
from PIL import Image
import io
import numpy as np
import os
from datetime import datetime
from pymongo import MongoClient
from huggingface_hub import InferenceClient

from embedding_service import JinaClipEmbeddingService
from qdrant_service import QdrantVectorService
from advanced_rag import AdvancedRAG
from cag_service import CAGService
from pdf_parser import PDFIndexer
from multimodal_pdf_parser import MultimodalPDFIndexer

# Initialize FastAPI app
app = FastAPI(
    title="Event Social Media Embeddings & ChatbotRAG API",
    description="API để embeddings, search và ChatbotRAG với Jina CLIP v2 + Qdrant + MongoDB + LLM",
    version="2.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize services
print("Initializing services...")
embedding_service = JinaClipEmbeddingService(model_path="jinaai/jina-clip-v2")

collection_name = os.getenv("COLLECTION_NAME", "event_social_media")
qdrant_service = QdrantVectorService(
    collection_name=collection_name,
    vector_size=embedding_service.get_embedding_dimension()
)
print(f"✓ Qdrant collection: {collection_name}")

# MongoDB connection
mongodb_uri = os.getenv("MONGODB_URI", "mongodb+srv://truongtn7122003:7KaI9OT5KTUxWjVI@truongtn7122003.xogin4q.mongodb.net/")
mongo_client = MongoClient(mongodb_uri)
db = mongo_client[os.getenv("MONGODB_DB_NAME", "chatbot_rag")]
documents_collection = db["documents"]
chat_history_collection = db["chat_history"]
print("✓ MongoDB connected")

# Hugging Face token
hf_token = os.getenv("HUGGINGFACE_TOKEN")
if hf_token:
    print("✓ Hugging Face token configured")

# Initialize Advanced RAG (Best Case 2025)
advanced_rag = AdvancedRAG(
    embedding_service=embedding_service,
    qdrant_service=qdrant_service
)
print("✓ Advanced RAG pipeline initialized (with Cross-Encoder)")

# Initialize CAG Service (Semantic Cache)
try:
    cag_service = CAGService(
        embedding_service=embedding_service,
        cache_collection="semantic_cache",
        vector_size=embedding_service.get_embedding_dimension(),
        similarity_threshold=0.9,
        ttl_hours=24
    )
    print("✓ CAG Service initialized (Semantic Caching enabled)")
except Exception as e:
    print(f"Warning: CAG Service initialization failed: {e}")
    print("Continuing without semantic caching...")
    cag_service = None

# Initialize PDF Indexer
pdf_indexer = PDFIndexer(
    embedding_service=embedding_service,
    qdrant_service=qdrant_service,
    documents_collection=documents_collection
)
print("✓ PDF Indexer initialized")

# Initialize Multimodal PDF Indexer (for PDFs with images)
multimodal_pdf_indexer = MultimodalPDFIndexer(
    embedding_service=embedding_service,
    qdrant_service=qdrant_service,
    documents_collection=documents_collection
)
print("✓ Multimodal PDF Indexer initialized")

print("✓ Services initialized successfully")


# Pydantic models for embeddings
class SearchRequest(BaseModel):
    text: Optional[str] = None
    limit: int = 10
    score_threshold: Optional[float] = None
    text_weight: float = 0.5
    image_weight: float = 0.5


class SearchResponse(BaseModel):
    id: str
    confidence: float
    metadata: dict


class IndexResponse(BaseModel):
    success: bool
    id: str
    message: str


# Pydantic models for ChatbotRAG
class ChatRequest(BaseModel):
    message: str
    use_rag: bool = True
    top_k: int = 3
    system_message: Optional[str] = """Bạn là trợ lý AI chuyên biệt cho hệ thống quản lý sự kiện và mạng xã hội. 
Vai trò của bạn là trả lời các câu hỏi CHÍNH XÁC dựa trên dữ liệu được cung cấp từ hệ thống.

Quy tắc tuyệt đối:
- CHỈ trả lời câu hỏi liên quan đến: events, social media posts, PDFs đã upload, và dữ liệu trong knowledge base
- KHÔNG trả lời câu hỏi ngoài phạm vi (tin tức, thời tiết, toán học, lập trình, tư vấn cá nhân, v.v.)
- Nếu câu hỏi nằm ngoài phạm vi: BẮT BUỘC trả lời "Chúng tôi không thể trả lời câu hỏi này vì nó nằm ngoài vùng application xử lí."
- Luôn ưu tiên thông tin từ context được cung cấp"""
    max_tokens: int = 512
    temperature: float = 0.7
    top_p: float = 0.95
    hf_token: Optional[str] = None
    # Advanced RAG options
    use_advanced_rag: bool = True
    use_query_expansion: bool = True
    use_reranking: bool = True
    use_compression: bool = True
    score_threshold: float = 0.5
    # Advanced RAG options
    use_advanced_rag: bool = True
    use_query_expansion: bool = True
    use_reranking: bool = True
    use_compression: bool = True
    score_threshold: float = 0.5


class ChatResponse(BaseModel):
    response: str
    context_used: List[Dict]
    timestamp: str
    rag_stats: Optional[Dict] = None  # Stats from advanced RAG pipeline
    rag_stats: Optional[Dict] = None  # Stats from advanced RAG pipeline


class AddDocumentRequest(BaseModel):
    text: str
    metadata: Optional[Dict] = None


class AddDocumentResponse(BaseModel):
    success: bool
    doc_id: str
    message: str


class UploadPDFResponse(BaseModel):
    success: bool
    document_id: str
    filename: str
    chunks_indexed: int
    message: str


class UploadPDFResponse(BaseModel):
    success: bool
    document_id: str
    filename: str
    chunks_indexed: int
    message: str


@app.get("/")
async def root():
    """Health check endpoint with comprehensive API documentation"""
    return {
        "status": "running",
        "service": "ChatbotRAG API - Advanced RAG with Multimodal Support",
        "version": "3.0.0",
        "service": "ChatbotRAG API - Advanced RAG with Multimodal Support",
        "version": "3.0.0",
        "vector_db": "Qdrant",
        "document_db": "MongoDB",
        "features": {
            "multiple_inputs": "Index up to 10 texts + 10 images per request",
            "advanced_rag": "Query expansion, reranking, contextual compression",
            "pdf_support": "Upload PDFs and chat about their content",
            "multimodal_pdf": "PDFs with text and image URLs - perfect for user guides",
            "chat_history": "Track conversation history",
            "hybrid_search": "Text + image search with Jina CLIP v2"
        },
        "document_db": "MongoDB",
        "features": {
            "multiple_inputs": "Index up to 10 texts + 10 images per request",
            "advanced_rag": "Query expansion, reranking, contextual compression",
            "pdf_support": "Upload PDFs and chat about their content",
            "multimodal_pdf": "PDFs with text and image URLs - perfect for user guides",
            "chat_history": "Track conversation history",
            "hybrid_search": "Text + image search with Jina CLIP v2"
        },
        "endpoints": {
            "indexing": {
                "POST /index": {
                    "description": "Index multiple texts and images (NEW: up to 10 each)",
                    "content_type": "multipart/form-data",
                    "body": {
                        "id": "string (required) - Document ID (primary)",
                        "texts": "List[string] (optional) - Up to 10 texts",
                        "images": "List[UploadFile] (optional) - Up to 10 images",
                        "id_use": "string (optional) - ID của SocialMedia hoặc EventCode",
                        "id_user": "string (optional) - ID của User"
                    },
                    "example": "curl -X POST '/index' -F 'id=doc1' -F 'id_use=social_123' -F 'id_user=user_789' -F 'texts=Text 1' -F 'images=@img1.jpg'",
            "indexing": {
                "POST /index": {
                    "description": "Index multiple texts and images (NEW: up to 10 each)",
                    "content_type": "multipart/form-data",
                    "body": {
                        "id": "string (required) - Document ID (primary)",
                        "texts": "List[string] (optional) - Up to 10 texts",
                        "images": "List[UploadFile] (optional) - Up to 10 images",
                        "id_use": "string (optional) - ID của SocialMedia hoặc EventCode",
                        "id_user": "string (optional) - ID của User"
                    },
                    "example": "curl -X POST '/index' -F 'id=doc1' -F 'id_use=social_123' -F 'id_user=user_789' -F 'texts=Text 1' -F 'images=@img1.jpg'",
                    "response": {
                        "success": True,
                        "id": "doc1",
                        "message": "Indexed successfully with 2 texts and 1 images"
                        "success": True,
                        "id": "doc1",
                        "message": "Indexed successfully with 2 texts and 1 images"
                    },
                    "use_cases": {
                        "social_media_post": {
                            "id": "post_uuid_123",
                            "id_use": "social_media_456",
                            "id_user": "user_789",
                            "description": "Link post to social media account and user"
                        },
                        "event_post": {
                            "id": "post_uuid_789",
                            "id_use": "event_code_ABC123",
                            "id_user": "user_101",
                            "description": "Link post to event and user"
                        }
                    }
                    "use_cases": {
                        "social_media_post": {
                            "id": "post_uuid_123",
                            "id_use": "social_media_456",
                            "id_user": "user_789",
                            "description": "Link post to social media account and user"
                        },
                        "event_post": {
                            "id": "post_uuid_789",
                            "id_use": "event_code_ABC123",
                            "id_user": "user_101",
                            "description": "Link post to event and user"
                        }
                    }
                },
                "POST /documents": {
                    "description": "Add text document to knowledge base",
                    "content_type": "application/json",
                    "body": {
                        "text": "string (required) - Document content",
                        "metadata": "object (optional) - Additional metadata"
                    },
                    "example": {
                        "text": "How to create event: Click 'Create Event' button...",
                        "metadata": {"category": "tutorial", "source": "user_guide"}
                    }
                },
                "POST /upload-pdf": {
                    "description": "Upload PDF file (text only)",
                    "content_type": "multipart/form-data",
                    "body": {
                        "file": "UploadFile (required) - PDF file",
                        "title": "string (optional) - Document title",
                        "category": "string (optional) - Category",
                        "description": "string (optional) - Description"
                    },
                    "example": "curl -X POST '/upload-pdf' -F 'file=@guide.pdf' -F 'title=User Guide'"
                },
                "POST /upload-pdf-multimodal": {
                    "description": "Upload PDF with text and image URLs (RECOMMENDED for user guides)",
                    "content_type": "multipart/form-data",
                    "features": [
                        "Extracts text from PDF",
                        "Detects image URLs (http://, https://)",
                        "Supports markdown: ![alt](url)",
                        "Supports HTML: <img src='url'>",
                        "Links images to text chunks",
                        "Returns images with context in chat"
                    ],
                    "body": {
                        "file": "UploadFile (required) - PDF file with image URLs",
                        "title": "string (optional) - Document title",
                        "category": "string (optional) - e.g. 'user_guide', 'tutorial'",
                        "description": "string (optional)"
                    },
                    "example": "curl -X POST '/upload-pdf-multimodal' -F 'file=@guide_with_images.pdf' -F 'category=user_guide'",
                    "description": "Add text document to knowledge base",
                    "content_type": "application/json",
                    "body": {
                        "text": "string (required) - Document content",
                        "metadata": "object (optional) - Additional metadata"
                    },
                    "example": {
                        "text": "How to create event: Click 'Create Event' button...",
                        "metadata": {"category": "tutorial", "source": "user_guide"}
                    }
                },
                "POST /upload-pdf": {
                    "description": "Upload PDF file (text only)",
                    "content_type": "multipart/form-data",
                    "body": {
                        "file": "UploadFile (required) - PDF file",
                        "title": "string (optional) - Document title",
                        "category": "string (optional) - Category",
                        "description": "string (optional) - Description"
                    },
                    "example": "curl -X POST '/upload-pdf' -F 'file=@guide.pdf' -F 'title=User Guide'"
                },
                "POST /upload-pdf-multimodal": {
                    "description": "Upload PDF with text and image URLs (RECOMMENDED for user guides)",
                    "content_type": "multipart/form-data",
                    "features": [
                        "Extracts text from PDF",
                        "Detects image URLs (http://, https://)",
                        "Supports markdown: ![alt](url)",
                        "Supports HTML: <img src='url'>",
                        "Links images to text chunks",
                        "Returns images with context in chat"
                    ],
                    "body": {
                        "file": "UploadFile (required) - PDF file with image URLs",
                        "title": "string (optional) - Document title",
                        "category": "string (optional) - e.g. 'user_guide', 'tutorial'",
                        "description": "string (optional)"
                    },
                    "example": "curl -X POST '/upload-pdf-multimodal' -F 'file=@guide_with_images.pdf' -F 'category=user_guide'",
                    "response": {
                        "success": True,
                        "document_id": "pdf_multimodal_20251029_150000",
                        "chunks_indexed": 25,
                        "message": "PDF indexed with 25 chunks and 15 images"
                        "success": True,
                        "document_id": "pdf_multimodal_20251029_150000",
                        "chunks_indexed": 25,
                        "message": "PDF indexed with 25 chunks and 15 images"
                    },
                    "use_case": "Perfect for user guides with screenshots, tutorials with diagrams"
                }
            },
            "search": {
                "POST /search": {
                    "description": "Hybrid search with text and/or image",
                    "body": {
                        "text": "string (optional) - Query text",
                        "image": "UploadFile (optional) - Query image",
                        "limit": "int (default: 10)",
                        "score_threshold": "float (optional, 0-1)",
                        "text_weight": "float (default: 0.5)",
                        "image_weight": "float (default: 0.5)"
                    }
                },
                "POST /search/text": {
                    "description": "Text-only search",
                    "body": {"text": "string", "limit": "int", "score_threshold": "float"}
                },
                "POST /search/image": {
                    "description": "Image-only search",
                    "body": {"image": "UploadFile", "limit": "int", "score_threshold": "float"}
                    "use_case": "Perfect for user guides with screenshots, tutorials with diagrams"
                }
            },
            "search": {
                "POST /search": {
                    "description": "Hybrid search with text and/or image",
                    "body": {
                        "text": "string (optional) - Query text",
                        "image": "UploadFile (optional) - Query image",
                        "limit": "int (default: 10)",
                        "score_threshold": "float (optional, 0-1)",
                        "text_weight": "float (default: 0.5)",
                        "image_weight": "float (default: 0.5)"
                    }
                },
                "POST /search/text": {
                    "description": "Text-only search",
                    "body": {"text": "string", "limit": "int", "score_threshold": "float"}
                },
                "POST /search/image": {
                    "description": "Image-only search",
                    "body": {"image": "UploadFile", "limit": "int", "score_threshold": "float"}
                },
                "POST /rag/search": {
                    "description": "Search in RAG knowledge base",
                    "body": {"query": "string", "top_k": "int (default: 5)", "score_threshold": "float (default: 0.5)"}
                }
            },
            "chat": {
                "POST /chat": {
                    "description": "Chat với Advanced RAG (Query expansion + Reranking + Compression)",
                    "content_type": "application/json",
                    "body": {
                        "message": "string (required) - User question",
                        "use_rag": "bool (default: true) - Enable RAG retrieval",
                        "use_advanced_rag": "bool (default: true) - Use advanced RAG pipeline (RECOMMENDED)",
                        "use_query_expansion": "bool (default: true) - Expand query with variations",
                        "use_reranking": "bool (default: true) - Rerank results for accuracy",
                        "use_compression": "bool (default: true) - Compress context to relevant parts",
                        "top_k": "int (default: 3) - Number of documents to retrieve",
                        "score_threshold": "float (default: 0.5) - Min relevance score (0-1)",
                        "max_tokens": "int (default: 512) - Max response tokens",
                        "temperature": "float (default: 0.7) - Creativity (0-1)",
                        "hf_token": "string (optional) - Hugging Face token"
                    },
                    "response": {
                        "response": "string - AI answer",
                        "context_used": "array - Retrieved documents with metadata",
                        "timestamp": "string",
                        "rag_stats": "object - RAG pipeline statistics (query variants, retrieval counts)"
                    },
                    "example_advanced": {
                        "message": "Làm sao để upload PDF có hình ảnh?",
                        "use_advanced_rag": True,
                        "use_reranking": True,
                        "top_k": 5,
                        "score_threshold": 0.5
                    "description": "Search in RAG knowledge base",
                    "body": {"query": "string", "top_k": "int (default: 5)", "score_threshold": "float (default: 0.5)"}
                }
            },
            "chat": {
                "POST /chat": {
                    "description": "Chat với Advanced RAG (Query expansion + Reranking + Compression)",
                    "content_type": "application/json",
                    "body": {
                        "message": "string (required) - User question",
                        "use_rag": "bool (default: true) - Enable RAG retrieval",
                        "use_advanced_rag": "bool (default: true) - Use advanced RAG pipeline (RECOMMENDED)",
                        "use_query_expansion": "bool (default: true) - Expand query with variations",
                        "use_reranking": "bool (default: true) - Rerank results for accuracy",
                        "use_compression": "bool (default: true) - Compress context to relevant parts",
                        "top_k": "int (default: 3) - Number of documents to retrieve",
                        "score_threshold": "float (default: 0.5) - Min relevance score (0-1)",
                        "max_tokens": "int (default: 512) - Max response tokens",
                        "temperature": "float (default: 0.7) - Creativity (0-1)",
                        "hf_token": "string (optional) - Hugging Face token"
                    },
                    "response": {
                        "response": "string - AI answer",
                        "context_used": "array - Retrieved documents with metadata",
                        "timestamp": "string",
                        "rag_stats": "object - RAG pipeline statistics (query variants, retrieval counts)"
                    },
                    "example_advanced": {
                        "message": "Làm sao để upload PDF có hình ảnh?",
                        "use_advanced_rag": True,
                        "use_reranking": True,
                        "top_k": 5,
                        "score_threshold": 0.5
                    },
                    "example_response_with_images": {
                        "response": "Để upload PDF có hình ảnh, sử dụng endpoint /upload-pdf-multimodal...",
                        "context_used": [
                            {
                                "id": "pdf_multimodal_...._p2_c1",
                                "confidence": 0.89,
                                "metadata": {
                                    "text": "Bước 1: Chuẩn bị PDF với image URLs...",
                                    "has_images": True,
                                    "image_urls": [
                                        "https://example.com/screenshot1.png",
                                        "https://example.com/diagram.jpg"
                                    ],
                                    "num_images": 2,
                                    "page": 2
                                }
                            }
                        ],
                        "rag_stats": {
                            "original_query": "Làm sao để upload PDF có hình ảnh?",
                            "expanded_queries": ["upload PDF hình ảnh", "PDF có ảnh"],
                            "initial_results": 10,
                            "after_rerank": 5,
                            "after_compression": 5
                        }
                    },
                    "notes": [
                        "Advanced RAG significantly improves answer quality",
                        "When multimodal PDF is used, images are returned in metadata",
                        "Requires HUGGINGFACE_TOKEN for actual LLM generation"
                    ]
                    "example_response_with_images": {
                        "response": "Để upload PDF có hình ảnh, sử dụng endpoint /upload-pdf-multimodal...",
                        "context_used": [
                            {
                                "id": "pdf_multimodal_...._p2_c1",
                                "confidence": 0.89,
                                "metadata": {
                                    "text": "Bước 1: Chuẩn bị PDF với image URLs...",
                                    "has_images": True,
                                    "image_urls": [
                                        "https://example.com/screenshot1.png",
                                        "https://example.com/diagram.jpg"
                                    ],
                                    "num_images": 2,
                                    "page": 2
                                }
                            }
                        ],
                        "rag_stats": {
                            "original_query": "Làm sao để upload PDF có hình ảnh?",
                            "expanded_queries": ["upload PDF hình ảnh", "PDF có ảnh"],
                            "initial_results": 10,
                            "after_rerank": 5,
                            "after_compression": 5
                        }
                    },
                    "notes": [
                        "Advanced RAG significantly improves answer quality",
                        "When multimodal PDF is used, images are returned in metadata",
                        "Requires HUGGINGFACE_TOKEN for actual LLM generation"
                    ]
                },
                "GET /history": {
                    "description": "Get chat history",
                    "query_params": {"limit": "int (default: 10)", "skip": "int (default: 0)"},
                    "response": {"history": "array", "total": "int"}
                }
            },
            "management": {
                "GET /documents/pdf": {
                    "description": "List all PDF documents",
                    "response": {"documents": "array", "total": "int"}
                },
                "DELETE /documents/pdf/{document_id}": {
                    "description": "Delete PDF and all its chunks",
                    "response": {"success": "bool", "message": "string"}
                },
                "GET /document/{doc_id}": {
                    "description": "Get document by ID",
                    "response": {"success": "bool", "data": "object"}
                },
                "DELETE /delete/{doc_id}": {
                    "description": "Delete document by ID",
                    "response": {"success": "bool", "message": "string"}
                },
                "GET /stats": {
                    "description": "Get Qdrant collection statistics",
                    "response": {"vectors_count": "int", "segments": "int", "indexed_vectors_count": "int"}
                }
            }
        },
        "quick_start": {
            "1_upload_multimodal_pdf": "curl -X POST '/upload-pdf-multimodal' -F 'file=@user_guide.pdf' -F 'title=Guide'",
            "2_verify_upload": "curl '/documents/pdf'",
            "3_chat_with_rag": "curl -X POST '/chat' -H 'Content-Type: application/json' -d '{\"message\": \"How to...?\", \"use_advanced_rag\": true}'",
            "4_see_images_in_context": "response['context_used'][0]['metadata']['image_urls']"
        },
        "use_cases": {
            "user_guide_with_screenshots": {
                "endpoint": "/upload-pdf-multimodal",
                "description": "PDFs with text instructions + image URLs for visual guidance",
                "benefits": ["Images linked to text chunks", "Chatbot returns relevant screenshots", "Perfect for step-by-step guides"]
            },
            "simple_text_docs": {
                "endpoint": "/upload-pdf",
                "description": "Simple PDFs with text only (FAQ, policies, etc.)"
            },
            "social_media_posts": {
                "endpoint": "/index",
                "description": "Index multiple posts with texts (up to 10) and images (up to 10)"
            },
            "complex_queries": {
                "endpoint": "/chat",
                "description": "Use advanced RAG for better accuracy on complex questions",
                "settings": {"use_advanced_rag": True, "use_reranking": True, "use_compression": True}
            }
        },
        "best_practices": {
            "pdf_format": [
                "Include image URLs in text (http://, https://)",
                "Use markdown format: ![alt](url) or HTML: <img src='url'>",
                "Clear structure with headings and sections",
                "Link images close to their related text"
            ],
            "chat_settings": {
                "for_accuracy": {"temperature": 0.3, "use_advanced_rag": True, "use_reranking": True},
                "for_creativity": {"temperature": 0.8, "use_advanced_rag": False},
                "for_factual_answers": {"temperature": 0.3, "use_compression": True, "score_threshold": 0.6}
            },
            "retrieval_tuning": {
                "not_finding_info": "Lower score_threshold to 0.3-0.4, increase top_k to 7-10",
                "too_much_context": "Increase score_threshold to 0.6-0.7, decrease top_k to 3-5",
                "slow_responses": "Disable compression, use basic RAG, decrease top_k"
            }
                    "description": "Get chat history",
                    "query_params": {"limit": "int (default: 10)", "skip": "int (default: 0)"},
                    "response": {"history": "array", "total": "int"}
                }
            },
            "management": {
                "GET /documents/pdf": {
                    "description": "List all PDF documents",
                    "response": {"documents": "array", "total": "int"}
                },
                "DELETE /documents/pdf/{document_id}": {
                    "description": "Delete PDF and all its chunks",
                    "response": {"success": "bool", "message": "string"}
                },
                "GET /document/{doc_id}": {
                    "description": "Get document by ID",
                    "response": {"success": "bool", "data": "object"}
                },
                "DELETE /delete/{doc_id}": {
                    "description": "Delete document by ID",
                    "response": {"success": "bool", "message": "string"}
                },
                "GET /stats": {
                    "description": "Get Qdrant collection statistics",
                    "response": {"vectors_count": "int", "segments": "int", "indexed_vectors_count": "int"}
                }
            }
        },
        "quick_start": {
            "1_upload_multimodal_pdf": "curl -X POST '/upload-pdf-multimodal' -F 'file=@user_guide.pdf' -F 'title=Guide'",
            "2_verify_upload": "curl '/documents/pdf'",
            "3_chat_with_rag": "curl -X POST '/chat' -H 'Content-Type: application/json' -d '{\"message\": \"How to...?\", \"use_advanced_rag\": true}'",
            "4_see_images_in_context": "response['context_used'][0]['metadata']['image_urls']"
        },
        "use_cases": {
            "user_guide_with_screenshots": {
                "endpoint": "/upload-pdf-multimodal",
                "description": "PDFs with text instructions + image URLs for visual guidance",
                "benefits": ["Images linked to text chunks", "Chatbot returns relevant screenshots", "Perfect for step-by-step guides"]
            },
            "simple_text_docs": {
                "endpoint": "/upload-pdf",
                "description": "Simple PDFs with text only (FAQ, policies, etc.)"
            },
            "social_media_posts": {
                "endpoint": "/index",
                "description": "Index multiple posts with texts (up to 10) and images (up to 10)"
            },
            "complex_queries": {
                "endpoint": "/chat",
                "description": "Use advanced RAG for better accuracy on complex questions",
                "settings": {"use_advanced_rag": True, "use_reranking": True, "use_compression": True}
            }
        },
        "best_practices": {
            "pdf_format": [
                "Include image URLs in text (http://, https://)",
                "Use markdown format: ![alt](url) or HTML: <img src='url'>",
                "Clear structure with headings and sections",
                "Link images close to their related text"
            ],
            "chat_settings": {
                "for_accuracy": {"temperature": 0.3, "use_advanced_rag": True, "use_reranking": True},
                "for_creativity": {"temperature": 0.8, "use_advanced_rag": False},
                "for_factual_answers": {"temperature": 0.3, "use_compression": True, "score_threshold": 0.6}
            },
            "retrieval_tuning": {
                "not_finding_info": "Lower score_threshold to 0.3-0.4, increase top_k to 7-10",
                "too_much_context": "Increase score_threshold to 0.6-0.7, decrease top_k to 3-5",
                "slow_responses": "Disable compression, use basic RAG, decrease top_k"
            }
        },
        "links": {
            "docs": "http://localhost:8000/docs",
            "redoc": "http://localhost:8000/redoc",
            "openapi": "http://localhost:8000/openapi.json",
            "guides": {
                "multimodal_pdf": "See MULTIMODAL_PDF_GUIDE.md",
                "advanced_rag": "See ADVANCED_RAG_GUIDE.md",
                "pdf_general": "See PDF_RAG_GUIDE.md",
                "quick_start": "See QUICK_START_PDF.md"
            }
        },
        "system_info": {
            "embedding_model": "Jina CLIP v2 (multimodal)",
            "vector_db": "Qdrant with HNSW index",
            "document_db": "MongoDB",
            "rag_pipeline": "Advanced RAG with query expansion, reranking, compression",
            "pdf_parser": "pypdfium2 with URL extraction",
            "max_inputs": "10 texts + 10 images per /index request"
            "openapi": "http://localhost:8000/openapi.json",
            "guides": {
                "multimodal_pdf": "See MULTIMODAL_PDF_GUIDE.md",
                "advanced_rag": "See ADVANCED_RAG_GUIDE.md",
                "pdf_general": "See PDF_RAG_GUIDE.md",
                "quick_start": "See QUICK_START_PDF.md"
            }
        },
        "system_info": {
            "embedding_model": "Jina CLIP v2 (multimodal)",
            "vector_db": "Qdrant with HNSW index",
            "document_db": "MongoDB",
            "rag_pipeline": "Advanced RAG with query expansion, reranking, compression",
            "pdf_parser": "pypdfium2 with URL extraction",
            "max_inputs": "10 texts + 10 images per /index request"
        }
    }

@app.post("/index", response_model=IndexResponse)
async def index_data(
    id: str = Form(...),
    texts: Optional[List[str]] = Form(None),
    images: Optional[List[UploadFile]] = File(None),
    id_use: Optional[str] = Form(None),
    id_user: Optional[str] = Form(None)
    texts: Optional[List[str]] = Form(None),
    images: Optional[List[UploadFile]] = File(None),
    id_use: Optional[str] = Form(None),
    id_user: Optional[str] = Form(None)
):
    """
    Index data vào vector database (hỗ trợ nhiều texts và images)
    Index data vào vector database (hỗ trợ nhiều texts và images)

    Body:
    - id: Document ID (primary ID)
    - texts: List of text contents (tiếng Việt supported) - Tối đa 10 texts
    - images: List of image files (optional) - Tối đa 10 images
    - id_use: ID của SocialMedia hoặc EventCode (optional)
    - id_user: ID của User (optional)
    - id: Document ID (primary ID)
    - texts: List of text contents (tiếng Việt supported) - Tối đa 10 texts
    - images: List of image files (optional) - Tối đa 10 images
    - id_use: ID của SocialMedia hoặc EventCode (optional)
    - id_user: ID của User (optional)

    Returns:
    - success: True/False
    - id: Document ID
    - message: Status message

    Example:
    ```bash
    curl -X POST '/index' \
      -F 'id=doc123' \
      -F 'id_use=social_media_456' \
      -F 'id_user=user_789' \
      -F 'texts=Post content 1' \
      -F 'texts=Post content 2' \
      -F 'images=@image1.jpg'
    ```

    Example:
    ```bash
    curl -X POST '/index' \
      -F 'id=doc123' \
      -F 'id_use=social_media_456' \
      -F 'id_user=user_789' \
      -F 'texts=Post content 1' \
      -F 'texts=Post content 2' \
      -F 'images=@image1.jpg'
    ```
    """
    try:
        # Validation
        if texts is None and images is None:
            raise HTTPException(status_code=400, detail="Phải cung cấp ít nhất texts hoặc images")

        if texts and len(texts) > 10:
            raise HTTPException(status_code=400, detail="Tối đa 10 texts")

        if images and len(images) > 10:
            raise HTTPException(status_code=400, detail="Tối đa 10 images")

        # Validation
        if texts is None and images is None:
            raise HTTPException(status_code=400, detail="Phải cung cấp ít nhất texts hoặc images")

        if texts and len(texts) > 10:
            raise HTTPException(status_code=400, detail="Tối đa 10 texts")

        if images and len(images) > 10:
            raise HTTPException(status_code=400, detail="Tối đa 10 images")

        # Prepare embeddings
        text_embeddings = []
        image_embeddings = []
        text_embeddings = []
        image_embeddings = []

        # Encode multiple texts (tiếng Việt)
        if texts:
            for text in texts:
                if text and text.strip():
                    text_emb = embedding_service.encode_text(text)
                    text_embeddings.append(text_emb)
        # Encode multiple texts (tiếng Việt)
        if texts:
            for text in texts:
                if text and text.strip():
                    text_emb = embedding_service.encode_text(text)
                    text_embeddings.append(text_emb)

        # Encode multiple images
        if images:
            for image in images:
                if image.filename:  # Check if image is provided
                    image_bytes = await image.read()
                    pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
                    image_emb = embedding_service.encode_image(pil_image)
                    image_embeddings.append(image_emb)
        # Encode multiple images
        if images:
            for image in images:
                if image.filename:  # Check if image is provided
                    image_bytes = await image.read()
                    pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
                    image_emb = embedding_service.encode_image(pil_image)
                    image_embeddings.append(image_emb)

        # Combine embeddings
        all_embeddings = []

        if text_embeddings:
            # Average all text embeddings
            avg_text_embedding = np.mean(text_embeddings, axis=0)
            all_embeddings.append(avg_text_embedding)

        if image_embeddings:
            # Average all image embeddings
            avg_image_embedding = np.mean(image_embeddings, axis=0)
            all_embeddings.append(avg_image_embedding)

        if not all_embeddings:
            raise HTTPException(status_code=400, detail="Không có embedding nào được tạo từ texts hoặc images")

        # Final combined embedding
        combined_embedding = np.mean(all_embeddings, axis=0)
        all_embeddings = []

        if text_embeddings:
            # Average all text embeddings
            avg_text_embedding = np.mean(text_embeddings, axis=0)
            all_embeddings.append(avg_text_embedding)

        if image_embeddings:
            # Average all image embeddings
            avg_image_embedding = np.mean(image_embeddings, axis=0)
            all_embeddings.append(avg_image_embedding)

        if not all_embeddings:
            raise HTTPException(status_code=400, detail="Không có embedding nào được tạo từ texts hoặc images")

        # Final combined embedding
        combined_embedding = np.mean(all_embeddings, axis=0)

        # Normalize
        combined_embedding = combined_embedding / np.linalg.norm(combined_embedding, axis=1, keepdims=True)

        # Index vào Qdrant
        metadata = {
            "texts": texts if texts else [],
            "text_count": len(texts) if texts else 0,
            "image_count": len(images) if images else 0,
            "image_filenames": [img.filename for img in images] if images else [],
            "id_use": id_use if id_use else None,  # ID của SocialMedia hoặc EventCode
            "id_user": id_user if id_user else None  # ID của User
            "texts": texts if texts else [],
            "text_count": len(texts) if texts else 0,
            "image_count": len(images) if images else 0,
            "image_filenames": [img.filename for img in images] if images else [],
            "id_use": id_use if id_use else None,  # ID của SocialMedia hoặc EventCode
            "id_user": id_user if id_user else None  # ID của User
        }

        result = qdrant_service.index_data(
            doc_id=id,
            embedding=combined_embedding,
            metadata=metadata
        )

        return IndexResponse(
            success=True,
            id=result["original_id"],  # Trả về MongoDB ObjectId
            message=f"Đã index thành công document {result['original_id']} với {len(texts) if texts else 0} texts và {len(images) if images else 0} images (Qdrant UUID: {result['qdrant_id']})"
            message=f"Đã index thành công document {result['original_id']} với {len(texts) if texts else 0} texts và {len(images) if images else 0} images (Qdrant UUID: {result['qdrant_id']})"
        )

    except HTTPException:
        raise
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi index: {str(e)}")


@app.post("/search", response_model=List[SearchResponse])
async def search(
    text: Optional[str] = Form(None),
    image: Optional[UploadFile] = File(None),
    limit: int = Form(10),
    score_threshold: Optional[float] = Form(None),
    text_weight: float = Form(0.5),
    image_weight: float = Form(0.5)
):
    """
    Search similar documents bằng text và/hoặc image

    Body:
    - text: Query text (tiếng Việt supported)
    - image: Query image (optional)
    - limit: Số lượng kết quả (default: 10)
    - score_threshold: Minimum confidence score (0-1)
    - text_weight: Weight cho text search (default: 0.5)
    - image_weight: Weight cho image search (default: 0.5)

    Returns:
    - List of results với id, confidence, và metadata
    """
    try:
        # Prepare query embeddings
        text_embedding = None
        image_embedding = None

        # Encode text query
        if text and text.strip():
            text_embedding = embedding_service.encode_text(text)

        # Encode image query
        if image:
            image_bytes = await image.read()
            pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
            image_embedding = embedding_service.encode_image(pil_image)

        # Validate input
        if text_embedding is None and image_embedding is None:
            raise HTTPException(status_code=400, detail="Phải cung cấp ít nhất text hoặc image để search")

        # Hybrid search với Qdrant
        results = qdrant_service.hybrid_search(
            text_embedding=text_embedding,
            image_embedding=image_embedding,
            text_weight=text_weight,
            image_weight=image_weight,
            limit=limit,
            score_threshold=score_threshold,
            ef=256  # High accuracy search
        )

        # Format response
        return [
            SearchResponse(
                id=result["id"],
                confidence=result["confidence"],
                metadata=result["metadata"]
            )
            for result in results
        ]

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi search: {str(e)}")


@app.post("/search/text", response_model=List[SearchResponse])
async def search_by_text(
    text: str = Form(...),
    limit: int = Form(10),
    score_threshold: Optional[float] = Form(None)
):
    """
    Search chỉ bằng text (tiếng Việt)

    Body:
    - text: Query text (tiếng Việt)
    - limit: Số lượng kết quả
    - score_threshold: Minimum confidence score

    Returns:
    - List of results
    """
    try:
        # Encode text
        text_embedding = embedding_service.encode_text(text)

        # Search
        results = qdrant_service.search(
            query_embedding=text_embedding,
            limit=limit,
            score_threshold=score_threshold,
            ef=256
        )

        return [
            SearchResponse(
                id=result["id"],
                confidence=result["confidence"],
                metadata=result["metadata"]
            )
            for result in results
        ]

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi search: {str(e)}")


@app.post("/search/image", response_model=List[SearchResponse])
async def search_by_image(
    image: UploadFile = File(...),
    limit: int = Form(10),
    score_threshold: Optional[float] = Form(None)
):
    """
    Search chỉ bằng image

    Body:
    - image: Query image
    - limit: Số lượng kết quả
    - score_threshold: Minimum confidence score

    Returns:
    - List of results
    """
    try:
        # Encode image
        image_bytes = await image.read()
        pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
        image_embedding = embedding_service.encode_image(pil_image)

        # Search
        results = qdrant_service.search(
            query_embedding=image_embedding,
            limit=limit,
            score_threshold=score_threshold,
            ef=256
        )

        return [
            SearchResponse(
                id=result["id"],
                confidence=result["confidence"],
                metadata=result["metadata"]
            )
            for result in results
        ]

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi search: {str(e)}")


@app.delete("/delete/{doc_id}")
async def delete_document(doc_id: str):
    """
    Delete document by ID (MongoDB ObjectId hoặc UUID)

    Args:
    - doc_id: Document ID to delete

    Returns:
    - Success message
    """
    try:
        qdrant_service.delete_by_id(doc_id)
        return {"success": True, "message": f"Đã xóa document {doc_id}"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi xóa: {str(e)}")


@app.get("/document/{doc_id}")
async def get_document(doc_id: str):
    """
    Get document by ID (MongoDB ObjectId hoặc UUID)

    Args:
    - doc_id: Document ID (MongoDB ObjectId)

    Returns:
    - Document data
    """
    try:
        doc = qdrant_service.get_by_id(doc_id)
        if doc:
            return {
                "success": True,
                "data": doc
            }
        raise HTTPException(status_code=404, detail=f"Không tìm thấy document {doc_id}")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi get document: {str(e)}")


@app.get("/stats")
async def get_stats():
    """
    Lấy thông tin thống kê collection

    Returns:
    - Collection statistics
    """
    try:
        info = qdrant_service.get_collection_info()
        return info
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi lấy stats: {str(e)}")


# ============================================
# ChatbotRAG Endpoints
# ============================================

@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    """
    Chat endpoint với Advanced RAG
    Chat endpoint với Advanced RAG

    Body:
    - message: User message
    - use_rag: Enable RAG retrieval (default: true)
    - top_k: Number of documents to retrieve (default: 3)
    - system_message: System prompt (optional)
    - max_tokens: Max tokens for response (default: 512)
    - temperature: Temperature for generation (default: 0.7)
    - hf_token: Hugging Face token (optional, sẽ dùng env nếu không truyền)
    - use_advanced_rag: Use advanced RAG pipeline (default: true)
    - use_query_expansion: Enable query expansion (default: true)
    - use_reranking: Enable reranking (default: true)
    - use_compression: Enable context compression (default: true)
    - score_threshold: Minimum relevance score (default: 0.5)
    - use_advanced_rag: Use advanced RAG pipeline (default: true)
    - use_query_expansion: Enable query expansion (default: true)
    - use_reranking: Enable reranking (default: true)
    - use_compression: Enable context compression (default: true)
    - score_threshold: Minimum relevance score (default: 0.5)

    Returns:
    - response: Generated response
    - context_used: Retrieved context documents
    - timestamp: Response timestamp
    - rag_stats: Statistics from RAG pipeline
    - rag_stats: Statistics from RAG pipeline
    """
    try:
        # ============================================
        # CAG Layer: Check Semantic Cache First
        # ============================================
        cache_hit = None
        if cag_service and request.use_rag:
            cache_hit = cag_service.check_cache(request.message)
            
            if cache_hit:
                # Cache hit! Return cached response immediately
                return ChatResponse(
                    response=cache_hit["response"],
                    context_used=cache_hit["context_used"],
                    timestamp=datetime.utcnow().isoformat(),
                    rag_stats={
                        **cache_hit.get("rag_stats", {}),
                        "cache_hit": True,
                        "cached_query": cache_hit["cached_query"],
                        "similarity_score": cache_hit["similarity_score"],
                        "cached_at": cache_hit["cached_at"]
                    }
                )
        
        # ============================================
        # RAG Pipeline (if cache miss)
        # ============================================
        # Retrieve context if RAG enabled
        context_used = []
        rag_stats = None

        rag_stats = None

        if request.use_rag:
            if request.use_advanced_rag:
                # Initialize LLM client for query expansion
                hf_client = None
                if request.hf_token or hf_token:
                    hf_client = InferenceClient(token=request.hf_token or hf_token)
                
                # Use Advanced RAG Pipeline (Best Case 2025)
                documents, stats = advanced_rag.hybrid_rag_pipeline(
                    query=request.message,
                    top_k=request.top_k,
                    score_threshold=request.score_threshold,
                    use_reranking=request.use_reranking,
                    use_compression=request.use_compression,
                    use_query_expansion=request.use_query_expansion,
                    max_context_tokens=500,
                    hf_client=hf_client
                )

                # Convert to dict format for compatibility
                context_used = [
                    {
                        "id": doc.id,
                        "confidence": doc.confidence,
                        "metadata": doc.metadata
                    }
                    for doc in documents
                ]
                rag_stats = stats

                # Format context using advanced RAG formatter
                context_text = advanced_rag.format_context_for_llm(documents)

            else:
                # Use basic RAG (original implementation)
                query_embedding = embedding_service.encode_text(request.message)

                results = qdrant_service.search(
                    query_embedding=query_embedding,
                    limit=request.top_k,
                    score_threshold=request.score_threshold
                )
                context_used = results

                # Build context text (basic format)
                context_text = "\n\nRelevant Context:\n"
                for i, doc in enumerate(context_used, 1):
                    doc_text = doc["metadata"].get("text", "")
                    confidence = doc["confidence"]
                    context_text += f"\n[{i}] (Confidence: {confidence:.2f})\n{doc_text}\n"
                # Build context text (basic format)
                context_text = "\n\nRelevant Context:\n"
                for i, doc in enumerate(context_used, 1):
                    doc_text = doc["metadata"].get("text", "")
                    confidence = doc["confidence"]
                    context_text += f"\n[{i}] (Confidence: {confidence:.2f})\n{doc_text}\n"

        # Build system message with context
        if request.use_rag and context_used:
            if request.use_advanced_rag:
                # Use advanced prompt builder
                system_message = advanced_rag.build_rag_prompt(
                    query=request.message,
                    context=context_text,
                    system_message=request.system_message
                )
            else:
                # Basic prompt
                system_message = f"{request.system_message}\n{context_text}\n\nPlease use the above context to answer the user's question when relevant."
        # Build system message with context
        if request.use_rag and context_used:
            if request.use_advanced_rag:
                # Use advanced prompt builder
                system_message = advanced_rag.build_rag_prompt(
                    query=request.message,
                    context=context_text,
                    system_message=request.system_message
                )
            else:
                # Basic prompt
                system_message = f"{request.system_message}\n{context_text}\n\nPlease use the above context to answer the user's question when relevant."
        else:
            system_message = request.system_message

        # Use token from request or fallback to env
        token = request.hf_token or hf_token
        # Generate response
        if not token:
            response = f"""[LLM Response Placeholder]

Context retrieved: {len(context_used)} documents
User question: {request.message}

To enable actual LLM generation:
1. Set HUGGINGFACE_TOKEN environment variable, OR
2. Pass hf_token in request body

Example:
{{
  "message": "Your question",
  "hf_token": "hf_xxxxxxxxxxxxx"
}}
"""
        else:
            try:
                client = InferenceClient(
                    token=hf_token,
                    model="openai/gpt-oss-20b"
                )

                # Build messages
                messages = [
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": request.message}
                ]

                # Generate response
                response = ""
                for msg in client.chat_completion(
                    messages,
                    max_tokens=request.max_tokens,
                    stream=True,
                    temperature=request.temperature,
                    top_p=request.top_p,
                ):
                    choices = msg.choices
                    if len(choices) and choices[0].delta.content:
                        response += choices[0].delta.content

            except Exception as e:
                response = f"Error generating response with LLM: {str(e)}\n\nContext was retrieved successfully, but LLM generation failed."

        # Save to history
        chat_data = {
            "user_message": request.message,
            "assistant_response": response,
            "context_used": context_used,
            "timestamp": datetime.utcnow()
        }
        chat_history_collection.insert_one(chat_data)
        
        # ============================================
        # CAG: Save to Cache (if RAG was used)
        # ============================================
        if cag_service and request.use_rag and context_used and response:
            try:
                cag_service.save_to_cache(
                    query=request.message,
                    response=response,
                    context_used=context_used,
                    rag_stats=rag_stats
                )
            except Exception as cache_error:
                print(f"Warning: Failed to save to cache: {cache_error}")

        return ChatResponse(
            response=response,
            context_used=context_used,
            timestamp=datetime.utcnow().isoformat(),
            rag_stats=rag_stats
            timestamp=datetime.utcnow().isoformat(),
            rag_stats=rag_stats
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.post("/documents", response_model=AddDocumentResponse)
async def add_document(request: AddDocumentRequest):
    """
    Add document to knowledge base

    Body:
    - text: Document text
    - metadata: Additional metadata (optional)

    Returns:
    - success: True/False
    - doc_id: MongoDB document ID
    - message: Status message
    """
    try:
        # Save to MongoDB
        doc_data = {
            "text": request.text,
            "metadata": request.metadata or {},
            "created_at": datetime.utcnow()
        }
        result = documents_collection.insert_one(doc_data)
        doc_id = str(result.inserted_id)

        # Generate embedding
        embedding = embedding_service.encode_text(request.text)

        # Index to Qdrant
        qdrant_service.index_data(
            doc_id=doc_id,
            embedding=embedding,
            metadata={
                "text": request.text,
                "source": "api",
                **(request.metadata or {})
            }
        )

        return AddDocumentResponse(
            success=True,
            doc_id=doc_id,
            message=f"Document added successfully with ID: {doc_id}"
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.post("/rag/search", response_model=List[SearchResponse])
async def rag_search(
    query: str = Form(...),
    top_k: int = Form(5),
    score_threshold: Optional[float] = Form(0.5)
):
    """
    Search in knowledge base

    Body:
    - query: Search query
    - top_k: Number of results (default: 5)
    - score_threshold: Minimum score (default: 0.5)

    Returns:
    - results: List of matching documents
    """
    try:
        # Generate query embedding
        query_embedding = embedding_service.encode_text(query)

        # Search in Qdrant
        results = qdrant_service.search(
            query_embedding=query_embedding,
            limit=top_k,
            score_threshold=score_threshold
        )

        return [
            SearchResponse(
                id=result["id"],
                confidence=result["confidence"],
                metadata=result["metadata"]
            )
            for result in results
        ]

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.get("/history")
async def get_history(limit: int = 10, skip: int = 0):
    """
    Get chat history

    Query params:
    - limit: Number of messages to return (default: 10)
    - skip: Number of messages to skip (default: 0)

    Returns:
    - history: List of chat messages
    """
    try:
        history = list(
            chat_history_collection
            .find({}, {"_id": 0})
            .sort("timestamp", -1)
            .skip(skip)
            .limit(limit)
        )

        # Convert datetime to string
        for msg in history:
            if "timestamp" in msg:
                msg["timestamp"] = msg["timestamp"].isoformat()

        return {
            "history": history,
            "total": chat_history_collection.count_documents({})
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.delete("/documents/{doc_id}")
async def delete_document_from_kb(doc_id: str):
    """
    Delete document from knowledge base

    Args:
    - doc_id: Document ID (MongoDB ObjectId)

    Returns:
    - success: True/False
    - message: Status message
    """
    try:
        # Delete from MongoDB
        result = documents_collection.delete_one({"_id": doc_id})

        # Delete from Qdrant
        if result.deleted_count > 0:
            qdrant_service.delete_by_id(doc_id)
            return {"success": True, "message": f"Document {doc_id} deleted from knowledge base"}
        else:
            raise HTTPException(status_code=404, detail=f"Document {doc_id} not found")

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.post("/upload-pdf", response_model=UploadPDFResponse)
async def upload_pdf(
    file: UploadFile = File(...),
    document_id: Optional[str] = Form(None),
    title: Optional[str] = Form(None),
    description: Optional[str] = Form(None),
    category: Optional[str] = Form(None)
):
    """
    Upload and index PDF file into knowledge base

    Body (multipart/form-data):
    - file: PDF file (required)
    - document_id: Custom document ID (optional, auto-generated if not provided)
    - title: Document title (optional)
    - description: Document description (optional)
    - category: Document category (optional, e.g., "user_guide", "faq")

    Returns:
    - success: True/False
    - document_id: Document ID
    - filename: Original filename
    - chunks_indexed: Number of chunks created
    - message: Status message

    Example:
    ```bash
    curl -X POST "http://localhost:8000/upload-pdf" \
      -F "file=@user_guide.pdf" \
      -F "title=Hướng dẫn sử dụng ChatbotRAG" \
      -F "category=user_guide"
    ```
    """
    try:
        # Validate file type
        if not file.filename.endswith('.pdf'):
            raise HTTPException(status_code=400, detail="Only PDF files are allowed")

        # Generate document ID if not provided
        if not document_id:
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            document_id = f"pdf_{timestamp}"

        # Read PDF bytes
        pdf_bytes = await file.read()

        # Prepare metadata
        metadata = {}
        if title:
            metadata['title'] = title
        if description:
            metadata['description'] = description
        if category:
            metadata['category'] = category

        # Index PDF
        result = pdf_indexer.index_pdf_bytes(
            pdf_bytes=pdf_bytes,
            document_id=document_id,
            filename=file.filename,
            document_metadata=metadata
        )

        return UploadPDFResponse(
            success=True,
            document_id=result['document_id'],
            filename=result['filename'],
            chunks_indexed=result['chunks_indexed'],
            message=f"PDF '{file.filename}' đã được index thành công với {result['chunks_indexed']} chunks"
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error uploading PDF: {str(e)}")


@app.get("/documents/pdf")
async def list_pdf_documents():
    """
    List all PDF documents in knowledge base

    Returns:
    - documents: List of PDF documents with metadata
    """
    try:
        docs = list(documents_collection.find(
            {"type": "pdf"},
            {"_id": 0}
        ))
        return {"documents": docs, "total": len(docs)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.delete("/documents/pdf/{document_id}")
async def delete_pdf_document(document_id: str):
    """
    Delete PDF document and all its chunks from knowledge base

    Args:
    - document_id: Document ID

    Returns:
    - success: True/False
    - message: Status message
    """
    try:
        # Get document info
        doc = documents_collection.find_one({"document_id": document_id, "type": "pdf"})

        if not doc:
            raise HTTPException(status_code=404, detail=f"PDF document {document_id} not found")

        # Delete all chunks from Qdrant
        chunk_ids = doc.get('chunk_ids', [])
        for chunk_id in chunk_ids:
            try:
                qdrant_service.delete_by_id(chunk_id)
            except:
                pass  # Chunk might already be deleted

        # Delete from MongoDB
        documents_collection.delete_one({"document_id": document_id})

        return {
            "success": True,
            "message": f"PDF document {document_id} and {len(chunk_ids)} chunks deleted"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.post("/upload-pdf-multimodal", response_model=UploadPDFResponse)
async def upload_pdf_multimodal(
    file: UploadFile = File(...),
    document_id: Optional[str] = Form(None),
    title: Optional[str] = Form(None),
    description: Optional[str] = Form(None),
    category: Optional[str] = Form(None)
):
    """
    Upload PDF with text and image URLs (for user guides with screenshots)

    This endpoint is optimized for PDFs containing:
    - Text instructions
    - Image URLs (http://... or https://...)
    - Markdown images: ![alt](url)
    - HTML images: <img src="url">

    The system will:
    1. Extract text from PDF
    2. Detect all image URLs in the text
    3. Link images to their corresponding text chunks
    4. Store image URLs in metadata
    5. Return images along with text during chat

    Body (multipart/form-data):
    - file: PDF file (required)
    - document_id: Custom document ID (optional, auto-generated if not provided)
    - title: Document title (optional)
    - description: Document description (optional)
    - category: Document category (optional, e.g., "user_guide", "tutorial")

    Returns:
    - success: True/False
    - document_id: Document ID
    - filename: Original filename
    - chunks_indexed: Number of chunks created
    - message: Status message (includes image count)

    Example:
    ```bash
    curl -X POST "http://localhost:8000/upload-pdf-multimodal" \
      -F "file=@user_guide_with_images.pdf" \
      -F "title=Hướng dẫn có ảnh minh họa" \
      -F "category=user_guide"
    ```

    Example Response:
    ```json
    {
      "success": true,
      "document_id": "pdf_20251029_150000",
      "filename": "user_guide_with_images.pdf",
      "chunks_indexed": 25,
      "message": "PDF 'user_guide_with_images.pdf' indexed with 25 chunks and 15 images"
    }
    ```
    """
    try:
        # Validate file type
        if not file.filename.endswith('.pdf'):
            raise HTTPException(status_code=400, detail="Only PDF files are allowed")

        # Generate document ID if not provided
        if not document_id:
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            document_id = f"pdf_multimodal_{timestamp}"

        # Read PDF bytes
        pdf_bytes = await file.read()

        # Prepare metadata
        metadata = {'type': 'multimodal'}
        if title:
            metadata['title'] = title
        if description:
            metadata['description'] = description
        if category:
            metadata['category'] = category

        # Index PDF with multimodal parser
        result = multimodal_pdf_indexer.index_pdf_bytes(
            pdf_bytes=pdf_bytes,
            document_id=document_id,
            filename=file.filename,
            document_metadata=metadata
        )

        return UploadPDFResponse(
            success=True,
            document_id=result['document_id'],
            filename=result['filename'],
            chunks_indexed=result['chunks_indexed'],
            message=f"PDF '{file.filename}' indexed successfully with {result['chunks_indexed']} chunks and {result.get('images_found', 0)} images"
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error uploading multimodal PDF: {str(e)}")


@app.post("/upload-pdf", response_model=UploadPDFResponse)
async def upload_pdf(
    file: UploadFile = File(...),
    document_id: Optional[str] = Form(None),
    title: Optional[str] = Form(None),
    description: Optional[str] = Form(None),
    category: Optional[str] = Form(None)
):
    """
    Upload and index PDF file into knowledge base

    Body (multipart/form-data):
    - file: PDF file (required)
    - document_id: Custom document ID (optional, auto-generated if not provided)
    - title: Document title (optional)
    - description: Document description (optional)
    - category: Document category (optional, e.g., "user_guide", "faq")

    Returns:
    - success: True/False
    - document_id: Document ID
    - filename: Original filename
    - chunks_indexed: Number of chunks created
    - message: Status message

    Example:
    ```bash
    curl -X POST "http://localhost:8000/upload-pdf" \
      -F "file=@user_guide.pdf" \
      -F "title=Hướng dẫn sử dụng ChatbotRAG" \
      -F "category=user_guide"
    ```
    """
    try:
        # Validate file type
        if not file.filename.endswith('.pdf'):
            raise HTTPException(status_code=400, detail="Only PDF files are allowed")

        # Generate document ID if not provided
        if not document_id:
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            document_id = f"pdf_{timestamp}"

        # Read PDF bytes
        pdf_bytes = await file.read()

        # Prepare metadata
        metadata = {}
        if title:
            metadata['title'] = title
        if description:
            metadata['description'] = description
        if category:
            metadata['category'] = category

        # Index PDF
        result = pdf_indexer.index_pdf_bytes(
            pdf_bytes=pdf_bytes,
            document_id=document_id,
            filename=file.filename,
            document_metadata=metadata
        )

        return UploadPDFResponse(
            success=True,
            document_id=result['document_id'],
            filename=result['filename'],
            chunks_indexed=result['chunks_indexed'],
            message=f"PDF '{file.filename}' đã được index thành công với {result['chunks_indexed']} chunks"
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error uploading PDF: {str(e)}")


@app.get("/documents/pdf")
async def list_pdf_documents():
    """
    List all PDF documents in knowledge base

    Returns:
    - documents: List of PDF documents with metadata
    """
    try:
        docs = list(documents_collection.find(
            {"type": "pdf"},
            {"_id": 0}
        ))
        return {"documents": docs, "total": len(docs)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.delete("/documents/pdf/{document_id}")
async def delete_pdf_document(document_id: str):
    """
    Delete PDF document and all its chunks from knowledge base

    Args:
    - document_id: Document ID

    Returns:
    - success: True/False
    - message: Status message
    """
    try:
        # Get document info
        doc = documents_collection.find_one({"document_id": document_id, "type": "pdf"})

        if not doc:
            raise HTTPException(status_code=404, detail=f"PDF document {document_id} not found")

        # Delete all chunks from Qdrant
        chunk_ids = doc.get('chunk_ids', [])
        for chunk_id in chunk_ids:
            try:
                qdrant_service.delete_by_id(chunk_id)
            except:
                pass  # Chunk might already be deleted

        # Delete from MongoDB
        documents_collection.delete_one({"document_id": document_id})

        return {
            "success": True,
            "message": f"PDF document {document_id} and {len(chunk_ids)} chunks deleted"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")


@app.post("/upload-pdf-multimodal", response_model=UploadPDFResponse)
async def upload_pdf_multimodal(
    file: UploadFile = File(...),
    document_id: Optional[str] = Form(None),
    title: Optional[str] = Form(None),
    description: Optional[str] = Form(None),
    category: Optional[str] = Form(None)
):
    """
    Upload PDF with text and image URLs (for user guides with screenshots)

    This endpoint is optimized for PDFs containing:
    - Text instructions
    - Image URLs (http://... or https://...)
    - Markdown images: ![alt](url)
    - HTML images: <img src="url">

    The system will:
    1. Extract text from PDF
    2. Detect all image URLs in the text
    3. Link images to their corresponding text chunks
    4. Store image URLs in metadata
    5. Return images along with text during chat

    Body (multipart/form-data):
    - file: PDF file (required)
    - document_id: Custom document ID (optional, auto-generated if not provided)
    - title: Document title (optional)
    - description: Document description (optional)
    - category: Document category (optional, e.g., "user_guide", "tutorial")

    Returns:
    - success: True/False
    - document_id: Document ID
    - filename: Original filename
    - chunks_indexed: Number of chunks created
    - message: Status message (includes image count)

    Example:
    ```bash
    curl -X POST "http://localhost:8000/upload-pdf-multimodal" \
      -F "file=@user_guide_with_images.pdf" \
      -F "title=Hướng dẫn có ảnh minh họa" \
      -F "category=user_guide"
    ```

    Example Response:
    ```json
    {
      "success": true,
      "document_id": "pdf_20251029_150000",
      "filename": "user_guide_with_images.pdf",
      "chunks_indexed": 25,
      "message": "PDF 'user_guide_with_images.pdf' indexed with 25 chunks and 15 images"
    }
    ```
    """
    try:
        # Validate file type
        if not file.filename.endswith('.pdf'):
            raise HTTPException(status_code=400, detail="Only PDF files are allowed")

        # Generate document ID if not provided
        if not document_id:
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            document_id = f"pdf_multimodal_{timestamp}"

        # Read PDF bytes
        pdf_bytes = await file.read()

        # Prepare metadata
        metadata = {'type': 'multimodal'}
        if title:
            metadata['title'] = title
        if description:
            metadata['description'] = description
        if category:
            metadata['category'] = category

        # Index PDF with multimodal parser
        result = multimodal_pdf_indexer.index_pdf_bytes(
            pdf_bytes=pdf_bytes,
            document_id=document_id,
            filename=file.filename,
            document_metadata=metadata
        )

        return UploadPDFResponse(
            success=True,
            document_id=result['document_id'],
            filename=result['filename'],
            chunks_indexed=result['chunks_indexed'],
            message=f"PDF '{file.filename}' indexed successfully with {result['chunks_indexed']} chunks and {result.get('images_found', 0)} images"
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error uploading multimodal PDF: {str(e)}")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        log_level="info"
    )