File size: 61,925 Bytes
7333afe
292eb86
2329f67
 
61cecf9
03a5156
 
61cecf9
2329f67
61cecf9
2329f67
 
8a72544
7333afe
64b3386
 
 
10c877a
 
 
64b3386
 
03a5156
50e05f5
 
4e1e6ae
 
03a5156
f293d04
 
 
f9851ce
 
 
 
292eb86
03a5156
292eb86
 
 
 
 
 
 
 
9f3cc4f
03a5156
f9851ce
03a5156
 
041398a
03a5156
50ec00d
b877222
 
 
 
 
 
 
 
 
ce57518
 
 
50ec00d
 
b877222
50ec00d
b877222
 
50ec00d
ce57518
50ec00d
 
 
ce57518
 
 
 
 
50ec00d
 
 
ce57518
 
 
 
 
 
 
50ec00d
 
 
b877222
50ec00d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b877222
 
 
 
 
 
 
50ec00d
 
 
b877222
 
 
 
 
 
 
50ec00d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b877222
50ec00d
 
 
 
 
 
 
 
 
 
 
 
 
 
b877222
 
 
 
50ec00d
 
 
 
b877222
7ef7c2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ec00d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499ee3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97533e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ec00d
b877222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219a4c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b877222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292eb86
03a5156
292eb86
 
 
 
 
 
03a5156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44d3a72
10c877a
f4fbfef
292eb86
 
 
f4fbfef
292eb86
f4fbfef
292eb86
f4fbfef
 
f9851ce
 
 
 
292eb86
f4fbfef
 
292eb86
f4fbfef
 
 
292eb86
f4fbfef
292eb86
f4fbfef
 
 
35cf712
292eb86
44d3a72
292eb86
 
 
35cf712
292eb86
 
 
35cf712
292eb86
35cf712
 
f9851ce
 
 
 
 
 
 
292eb86
35cf712
 
 
 
515209f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab15d2
292eb86
 
 
6ab15d2
292eb86
6ab15d2
292eb86
6ab15d2
 
 
 
 
 
 
 
f61c1a4
b5ab699
 
 
 
292eb86
b5ab699
 
 
292eb86
f61c1a4
f777bc6
 
 
 
 
292eb86
b5ab699
f61c1a4
 
 
292eb86
f61c1a4
 
 
292eb86
f61c1a4
b5ab699
 
292eb86
f61c1a4
 
 
 
 
b5ab699
f61c1a4
292eb86
 
10c877a
f61c1a4
 
292eb86
10c877a
 
292eb86
b5ab699
 
10c877a
 
 
292eb86
10c877a
 
 
 
292eb86
10c877a
 
292eb86
10c877a
 
 
 
 
292eb86
b5ab699
 
 
 
 
10c877a
 
b5ab699
 
 
 
 
10c877a
292eb86
10c877a
 
292eb86
10c877a
 
292eb86
b5ab699
10c877a
 
 
 
 
292eb86
f61c1a4
 
 
 
 
b5ab699
292eb86
f61c1a4
 
 
 
 
b5ab699
 
 
 
 
 
 
 
 
 
f61c1a4
292eb86
f61c1a4
 
 
292eb86
b5ab699
292eb86
b5ab699
 
 
 
292eb86
b5ab699
292eb86
 
f61c1a4
 
292eb86
b5ab699
 
 
 
 
 
 
292eb86
f61c1a4
b5ab699
 
 
f777bc6
 
 
 
b5ab699
292eb86
2aceabb
31e950a
2aceabb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31e950a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a62598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5ab699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1118663
292eb86
61e7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1957e91
292eb86
 
 
1957e91
 
 
292eb86
1957e91
8ea261f
 
292eb86
1957e91
 
 
292eb86
1957e91
 
 
292eb86
1957e91
 
 
 
 
292eb86
1957e91
 
 
 
 
292eb86
1957e91
 
 
 
 
 
 
 
292eb86
1957e91
 
8ea261f
2bd9b5d
 
61e7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7333afe
292eb86
 
 
 
 
 
 
 
7333afe
56c8e59
09d4055
7333afe
0f519bc
028c9cb
7333afe
2bd9b5d
0f519bc
10c877a
 
 
0f519bc
 
10c877a
 
2bd9b5d
8c249d6
4571b33
65fc39c
 
fccb2e5
311a114
fccb2e5
 
 
 
 
 
 
65fc39c
 
 
fccb2e5
 
 
 
 
 
 
 
 
 
292eb86
8c249d6
 
939f85b
0f519bc
cbeca91
 
 
 
 
 
 
 
 
 
 
 
 
 
2329f67
 
0f519bc
 
914b163
2329f67
8c249d6
2329f67
 
7333afe
4571b33
7333afe
 
 
 
292eb86
 
03a5156
7333afe
292eb86
 
 
 
 
 
 
 
 
 
7333afe
 
59815da
7333afe
 
 
59815da
7333afe
 
 
 
 
 
292eb86
03a5156
59815da
7333afe
292eb86
 
 
 
 
 
7333afe
 
59815da
7333afe
 
 
 
 
292eb86
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
# utils/database.py

# Update the imports first
from langchain_community.chat_models import ChatOpenAI
from langchain_core.messages import (
    HumanMessage,
    AIMessage,
    SystemMessage,
    BaseMessage
)
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnablePassthrough
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
from langchain.agents import AgentExecutor, Tool, create_openai_tools_agent
from langchain.agents.format_scratchpad.tools import format_to_tool_messages
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
from langchain.vectorstores import FAISS
import os
import streamlit as st
import sqlite3
import traceback
import time
import io
import tempfile
from sqlite3 import Error
from threading import Lock
from typing import Dict, List, Optional, Any
from datetime import datetime
from threading import Lock

# Create a lock for database connection
conn_lock = Lock()

def create_connection(db_file):
    """
    Create a database connection to the SQLite database.

    Args:
        db_file (str): Path to the SQLite database file.
    Returns:
        sqlite3.Connection: Database connection object or None if an error occurs.
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file, check_same_thread=False)
        return conn
    except Error as e:
        st.error("Failed to connect to database. Please try again or contact support.")
    return None
    
def create_connection(db_file: str) -> Optional[sqlite3.Connection]:
    """Create a database connection."""
    try:
        conn = sqlite3.connect(db_file, check_same_thread=False)
        return conn
    except sqlite3.Error as e:
        st.error(f"Error connecting to database: {e}")
        return None

# utils/database.py
# Add this version of create_tables (replacing the existing one)

# utils/database.py

def create_tables(conn: sqlite3.Connection) -> None:
    """Create all necessary tables in the database."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            
            # Force create collections tables first
            collections_tables = [
                '''
                CREATE TABLE IF NOT EXISTS collections (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL UNIQUE,
                    description TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
                ''',
                '''
                CREATE TABLE IF NOT EXISTS document_collections (
                    document_id INTEGER,
                    collection_id INTEGER,
                    added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    PRIMARY KEY (document_id, collection_id),
                    FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE,
                    FOREIGN KEY (collection_id) REFERENCES collections (id) ON DELETE CASCADE
                )
                '''
            ]
            
            # Execute collections tables creation separately
            for table_sql in collections_tables:
                try:
                    cursor.execute(table_sql)
                    conn.commit()
                except sqlite3.Error as e:
                    st.error(f"Error creating collections table: {e}")
                    st.error(f"SQL that failed: {table_sql}")
                    raise
            
            # Create other tables
            other_tables = [
                '''
                CREATE TABLE IF NOT EXISTS documents (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    content TEXT NOT NULL,
                    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
                ''',
                '''
                CREATE TABLE IF NOT EXISTS queries (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    query TEXT NOT NULL,
                    response TEXT NOT NULL,
                    document_id INTEGER,
                    query_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE
                )
                ''',
                '''
                CREATE TABLE IF NOT EXISTS annotations (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    document_id INTEGER NOT NULL,
                    annotation TEXT NOT NULL,
                    page_number INTEGER,
                    annotation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE
                )
                '''
            ]
            
            # Execute other tables creation
            for table_sql in other_tables:
                try:
                    cursor.execute(table_sql)
                    conn.commit()
                except sqlite3.Error as e:
                    st.error(f"Error creating table: {e}")
                    st.error(f"SQL that failed: {table_sql}")
                    raise
            
            # Create indices
            indices = [
                'CREATE INDEX IF NOT EXISTS idx_doc_name ON documents(name)',
                'CREATE INDEX IF NOT EXISTS idx_collection_name ON collections(name)',
                'CREATE INDEX IF NOT EXISTS idx_doc_collections ON document_collections(collection_id)'
            ]
            
            # Execute indices creation
            for index_sql in indices:
                try:
                    cursor.execute(index_sql)
                    conn.commit()
                except sqlite3.Error as e:
                    st.error(f"Error creating index: {e}")
                    st.error(f"SQL that failed: {index_sql}")
            
            # Verify collections table was created
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='collections'")
            if not cursor.fetchone():
                st.error("Failed to create collections table despite no errors")
                raise Exception("Collections table creation failed silently")
            
            conn.commit()
            
    except sqlite3.Error as e:
        st.error(f"Error in create_tables: {e}")
        raise
    except Exception as e:
        st.error(f"Unexpected error in create_tables: {e}")
        raise
def search_documents_in_collection(conn: sqlite3.Connection, collection_id: int, query: str) -> List[Dict]:
    """Search for documents within a collection."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT d.* 
                FROM documents d
                JOIN document_collections dc ON d.id = dc.document_id
                WHERE dc.collection_id = ?
                AND (d.name LIKE ? OR d.content LIKE ?)
            ''', (collection_id, f'%{query}%', f'%{query}%'))
            
            return [dict(row) for row in cursor.fetchall()]
            
    except sqlite3.Error as e:
        st.error(f"Error searching documents: {e}")
        return []
def force_recreate_collections_tables(conn: sqlite3.Connection) -> bool:
    """Force recreate collections tables if they're missing."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            
            # Drop existing tables if they exist
            cursor.execute("DROP TABLE IF EXISTS document_collections")
            cursor.execute("DROP TABLE IF EXISTS collections")
            
            # Create collections table
            cursor.execute('''
                CREATE TABLE collections (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL UNIQUE,
                    description TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # Create document_collections table
            cursor.execute('''
                CREATE TABLE document_collections (
                    document_id INTEGER,
                    collection_id INTEGER,
                    added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    PRIMARY KEY (document_id, collection_id),
                    FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE,
                    FOREIGN KEY (collection_id) REFERENCES collections (id) ON DELETE CASCADE
                )
            ''')
            
            # Create indices
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_collection_name ON collections(name)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_doc_collections ON document_collections(collection_id)')
            
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error recreating collections tables: {e}")
        return False


def get_existing_vector_store(document_ids: List[int]) -> Optional[FAISS]:
    """Retrieve existing vector store if available."""
    try:
        if st.session_state.get('vector_store'):
            current_docs = set(document_ids)
            stored_docs = set(
                metadata['document_id'] 
                for metadata in st.session_state.vector_store.docstore.get_all_metadatas()
            )
            
            # If the document sets match, reuse existing vector store
            if current_docs == stored_docs:
                return st.session_state.vector_store
                
        return None
    except Exception as e:
        st.error(f"Error checking vector store: {e}")
        return None
        
def get_uncategorized_documents(conn: sqlite3.Connection) -> List[Dict]:
    """Get documents that aren't in any collection."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date
                FROM documents d
                LEFT JOIN document_collections dc ON d.id = dc.document_id
                WHERE dc.collection_id IS NULL
                ORDER BY d.upload_date DESC
            ''')
            
            return [{
                'id': row[0],
                'name': row[1],
                'content': row[2],
                'upload_date': row[3],
                'collections': []
            } for row in cursor.fetchall()]
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving uncategorized documents: {e}")
        return []

def get_documents_for_chat(conn: sqlite3.Connection, collection_id: Optional[int] = None) -> List[Dict]:
    """Get documents for chat, either from a collection or all documents."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            
            if collection_id:
                cursor.execute('''
                    SELECT 
                        d.id,
                        d.name,
                        d.content,
                        d.upload_date
                    FROM documents d
                    JOIN document_collections dc ON d.id = dc.document_id
                    WHERE dc.collection_id = ?
                    ORDER BY d.upload_date DESC
                ''', (collection_id,))
            else:
                cursor.execute('''
                    SELECT 
                        d.id,
                        d.name,
                        d.content,
                        d.upload_date
                    FROM documents d
                    ORDER BY d.upload_date DESC
                ''')
            
            return [{
                'id': row[0],
                'name': row[1],
                'content': row[2],
                'upload_date': row[3]
            } for row in cursor.fetchall()]
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving documents for chat: {e}")
        return []

def get_all_documents(conn: sqlite3.Connection) -> List[Dict]:
    """Get all documents with their metadata and collections."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date,
                    GROUP_CONCAT(c.name) as collections
                FROM documents d
                LEFT JOIN document_collections dc ON d.id = dc.document_id
                LEFT JOIN collections c ON dc.collection_id = c.id
                GROUP BY d.id
                ORDER BY d.upload_date DESC
            ''')
            
            documents = []
            for row in cursor.fetchall():
                documents.append({
                    'id': row[0],
                    'name': row[1],
                    'content': row[2],
                    'upload_date': row[3],
                    'collections': row[4].split(',') if row[4] else []
                })
            return documents
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving documents: {e}")
        return []

def get_document_queries(conn: sqlite3.Connection, document_id: int) -> List[Dict]:
    """Get all queries associated with a document."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT id, query, response, query_date
                FROM queries
                WHERE document_id = ?
                ORDER BY query_date DESC
            ''', (document_id,))
            
            queries = []
            for row in cursor.fetchall():
                queries.append({
                    'id': row[0],
                    'query': row[1],
                    'response': row[2],
                    'query_date': row[3]
                })
            return queries
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving document queries: {e}")
        return []

def add_query(conn: sqlite3.Connection, query: str, response: str, document_id: Optional[int] = None) -> bool:
    """Add a new query and its response."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO queries (query, response, document_id)
                VALUES (?, ?, ?)
            ''', (query, response, document_id))
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error adding query: {e}")
        return False

# Add to utils/database.py

import sqlite3
from typing import List, Dict, Optional
from datetime import datetime
from langchain_core.messages import HumanMessage, AIMessage
import streamlit as st

def create_chat_tables(conn: sqlite3.Connection) -> None:
    """Create necessary tables for chat management."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            
            # Create chats table
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS chats (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    collection_id INTEGER,
                    FOREIGN KEY (collection_id) REFERENCES collections (id) ON DELETE SET NULL
                )
            ''')
            
            # Create chat messages table
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS chat_messages (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    chat_id INTEGER NOT NULL,
                    role TEXT NOT NULL,
                    content TEXT NOT NULL,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    metadata TEXT,  -- Store metadata as JSON string
                    FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE
                )
            ''')
            
            conn.commit()
            
    except sqlite3.Error as e:
        st.error(f"Error creating chat tables: {e}")
        raise

def create_new_chat(conn: sqlite3.Connection, title: str, collection_id: Optional[int] = None) -> Optional[int]:
    """Create a new chat session."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO chats (title, collection_id, created_at, last_updated)
                VALUES (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
            ''', (title, collection_id))
            
            conn.commit()
            return cursor.lastrowid
            
    except sqlite3.Error as e:
        st.error(f"Error creating new chat: {e}")
        return None

def save_chat_message(conn: sqlite3.Connection, 
                     chat_id: int, 
                     role: str, 
                     content: str, 
                     metadata: Optional[Dict] = None) -> Optional[int]:
    """Save a chat message to the database."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            
            # Convert metadata to JSON string if present
            metadata_str = json.dumps(metadata) if metadata else None
            
            # Insert message
            cursor.execute('''
                INSERT INTO chat_messages (chat_id, role, content, metadata, timestamp)
                VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
            ''', (chat_id, role, content, metadata_str))
            
            # Update chat last_updated timestamp
            cursor.execute('''
                UPDATE chats 
                SET last_updated = CURRENT_TIMESTAMP 
                WHERE id = ?
            ''', (chat_id,))
            
            conn.commit()
            return cursor.lastrowid
            
    except sqlite3.Error as e:
        st.error(f"Error saving chat message: {e}")
        return None

def get_all_chats(conn: sqlite3.Connection) -> List[Dict]:
    """Retrieve all chat sessions."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    c.id,
                    c.title,
                    c.created_at,
                    c.last_updated,
                    c.collection_id,
                    COUNT(m.id) as message_count,
                    MAX(m.timestamp) as last_message
                FROM chats c
                LEFT JOIN chat_messages m ON c.id = m.chat_id
                GROUP BY c.id
                ORDER BY c.last_updated DESC
            ''')
            
            chats = []
            for row in cursor.fetchall():
                chats.append({
                    'id': row[0],
                    'title': row[1],
                    'created_at': row[2],
                    'last_updated': row[3],
                    'collection_id': row[4],
                    'message_count': row[5],
                    'last_message': row[6]
                })
            return chats
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving chats: {e}")
        return []

def get_chat_messages(conn: sqlite3.Connection, chat_id: int) -> List[Dict]:
    """Retrieve all messages for a specific chat."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT id, role, content, metadata, timestamp
                FROM chat_messages
                WHERE chat_id = ?
                ORDER BY timestamp
            ''', (chat_id,))
            
            messages = []
            for row in cursor.fetchall():
                # Parse metadata JSON if present
                metadata = json.loads(row[3]) if row[3] else None
                
                # Convert to appropriate message type
                if row[1] == 'human':
                    message = HumanMessage(content=row[2])
                else:
                    message = AIMessage(content=row[2], additional_kwargs={'metadata': metadata})
                
                messages.append(message)
            
            return messages
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving chat messages: {e}")
        return []

def delete_chat(conn: sqlite3.Connection, chat_id: int) -> bool:
    """Delete a chat session and all its messages."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            # Messages will be automatically deleted due to CASCADE
            cursor.execute('DELETE FROM chats WHERE id = ?', (chat_id,))
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error deleting chat: {e}")
        return False

def update_chat_title(conn: sqlite3.Connection, chat_id: int, new_title: str) -> bool:
    """Update the title of a chat session."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                UPDATE chats 
                SET title = ?, last_updated = CURRENT_TIMESTAMP 
                WHERE id = ?
            ''', (new_title, chat_id))
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error updating chat title: {e}")
        return False

def get_chat_by_id(conn: sqlite3.Connection, chat_id: int) -> Optional[Dict]:
    """Retrieve a specific chat session by ID."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    c.id,
                    c.title,
                    c.created_at,
                    c.last_updated,
                    c.collection_id,
                    COUNT(m.id) as message_count
                FROM chats c
                LEFT JOIN chat_messages m ON c.id = m.chat_id
                WHERE c.id = ?
                GROUP BY c.id
            ''', (chat_id,))
            
            row = cursor.fetchone()
            if row:
                return {
                    'id': row[0],
                    'title': row[1],
                    'created_at': row[2],
                    'last_updated': row[3],
                    'collection_id': row[4],
                    'message_count': row[5]
                }
            return None
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving chat: {e}")
        return None

def export_chat_history(conn: sqlite3.Connection, chat_id: int) -> Optional[Dict]:
    """Export a chat session with all its messages."""
    try:
        chat = get_chat_by_id(conn, chat_id)
        if not chat:
            return None
            
        messages = get_chat_messages(conn, chat_id)
        
        return {
            'chat_info': chat,
            'messages': [
                {
                    'role': 'human' if isinstance(msg, HumanMessage) else 'assistant',
                    'content': msg.content,
                    'metadata': msg.additional_kwargs.get('metadata') if isinstance(msg, AIMessage) else None
                }
                for msg in messages
            ]
        }
            
    except Exception as e:
        st.error(f"Error exporting chat history: {e}")
        return None

def import_chat_history(conn: sqlite3.Connection, chat_data: Dict) -> Optional[int]:
    """Import a chat session from exported data."""
    try:
        with conn_lock:
            # Create new chat
            chat_id = create_new_chat(
                conn,
                chat_data['chat_info']['title'],
                chat_data['chat_info'].get('collection_id')
            )
            
            if not chat_id:
                return None
                
            # Import messages
            for msg in chat_data['messages']:
                save_chat_message(
                    conn,
                    chat_id,
                    msg['role'],
                    msg['content'],
                    msg.get('metadata')
                )
                
            return chat_id
            
    except Exception as e:
        st.error(f"Error importing chat history: {e}")
        return None


# utils/database.py
def create_chat_tables(conn):
    """Create tables for chat management."""
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS chats (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS chat_messages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            chat_id INTEGER,
            role TEXT NOT NULL,
            content TEXT NOT NULL,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE
        )
    ''')
    conn.commit()

def save_chat(conn, chat_title: str, messages: List[Dict]):
    """Save chat history."""
    cursor = conn.cursor()
    cursor.execute('INSERT INTO chats (title) VALUES (?)', (chat_title,))
    chat_id = cursor.lastrowid
    
    for msg in messages:
        cursor.execute('''
            INSERT INTO chat_messages (chat_id, role, content)
            VALUES (?, ?, ?)
        ''', (chat_id, msg['role'], msg['content']))
    
    conn.commit()
    return chat_id

# components/chat.py
def display_chat_manager():
    """Display chat management interface."""
    st.sidebar.markdown("### Chat Management")
    
    # New chat button
    if st.sidebar.button("New Chat"):
        st.session_state.messages = []
        st.session_state.current_chat_id = None
    
    # Save current chat
    if st.session_state.messages and st.sidebar.button("Save Chat"):
        chat_title = st.sidebar.text_input("Chat Title", 
                                         value=f"Chat {datetime.now().strftime('%Y-%m-%d %H:%M')}")
        if chat_title:
            save_chat(st.session_state.db_conn, chat_title, st.session_state.messages)
            st.sidebar.success("Chat saved!")
    
    # Load previous chats
    chats = get_all_chats(st.session_state.db_conn)
    if chats:
        st.sidebar.markdown("### Previous Chats")
        for chat in chats:
            if st.sidebar.button(f"📜 {chat['title']}", key=f"chat_{chat['id']}"):
                st.session_state.messages = get_chat_messages(st.session_state.db_conn, chat['id'])
                st.session_state.current_chat_id = chat['id']
                st.rerun()
def add_annotation(conn: sqlite3.Connection, document_id: int, annotation: str, page_number: Optional[int] = None) -> bool:
    """Add an annotation to a document."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO annotations (document_id, annotation, page_number)
                VALUES (?, ?, ?)
            ''', (document_id, annotation, page_number))
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error adding annotation: {e}")
        return False

def create_tables(conn):
    """
    Create necessary tables in the database.

    Args:
        conn (sqlite3.Connection): SQLite database connection.
    """
    try:
        sql_create_documents_table = '''
        CREATE TABLE IF NOT EXISTS documents (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            content TEXT NOT NULL,
            upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
        '''

        sql_create_queries_table = '''
        CREATE TABLE IF NOT EXISTS queries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            query TEXT NOT NULL,
            response TEXT NOT NULL,
            document_id INTEGER,
            query_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (document_id) REFERENCES documents (id)
        );
        '''

        sql_create_annotations_table = '''
        CREATE TABLE IF NOT EXISTS annotations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            document_id INTEGER NOT NULL,
            annotation TEXT NOT NULL,
            page_number INTEGER,
            annotation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (document_id) REFERENCES documents (id)
        );
        '''

        conn.execute(sql_create_documents_table)
        conn.execute(sql_create_queries_table)
        conn.execute(sql_create_annotations_table)
    except Error as e:
        st.error(f"Error: {e}")


def get_documents(conn):
    """
    Retrieve all documents from the database.

    Args:
        conn (sqlite3.Connection): SQLite database connection.
    Returns:
        tuple: (list of document contents, list of document names).
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute("SELECT content, name FROM documents")
            results = cursor.fetchall()

        if not results:
            return [], []

        # Separate contents and names
        document_contents = [row[0] for row in results]
        document_names = [row[1] for row in results]

        return document_contents, document_names

    except Error as e:
        st.error(f"Error retrieving documents: {e}")
        return [], []


def insert_document(conn, name, content):
    """
    Insert a new document into the database.

    Args:
        conn (sqlite3.Connection): SQLite database connection.
        name (str): Name of the document.
        content (str): Content of the document.
    Returns:
        int: ID of the inserted document, or None if insertion failed.
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            sql = '''INSERT INTO documents (name, content)
                    VALUES (?, ?)'''
            cursor.execute(sql, (name, content))
            conn.commit()
            return cursor.lastrowid

    except Error as e:
        st.error(f"Error inserting document: {e}")
        return None

def verify_database_tables(conn):
    """Verify that all required tables exist."""
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = [table[0] for table in cursor.fetchall()]
        
        # If collections table doesn't exist, force recreate it
        if 'collections' not in tables:
            if not force_recreate_collections_tables(conn):
                st.error("Failed to recreate collections tables!")
            
        return 'collections' in tables
            
    except Exception as e:
        st.error(f"Error verifying tables: {e}")
        return False
        
def verify_vector_store(vector_store):
    """
    Verify that the vector store has documents loaded.

    Args:
        vector_store (FAISS): FAISS vector store instance.
    Returns:
        bool: True if vector store is properly initialized with documents.
    """
    try:
        # Try to perform a simple similarity search
        test_results = vector_store.similarity_search("test", k=1)
        return len(test_results) > 0
    except Exception as e:
        st.error(f"Vector store verification failed: {e}")
        return False

def handle_document_upload(uploaded_files, **kwargs):
    """
    Handle document upload with progress tracking and collection support.
    
    Args:
        uploaded_files (list): List of uploaded files
        **kwargs: Additional arguments including:
            - collection_id (int, optional): ID of the collection to add documents to
    """
    try:
        # Initialize session state variables if they don't exist
        if 'qa_system' not in st.session_state:
            st.session_state.qa_system = None
        if 'vector_store' not in st.session_state:
            st.session_state.vector_store = None

        # Create progress containers
        progress_container = st.empty()
        status_container = st.empty()
        details_container = st.empty()

        # Initialize progress bar
        progress_bar = progress_container.progress(0)
        status_container.info("🔄 Initializing document processing...")

        # Reset existing states
        st.session_state.vector_store = None
        st.session_state.qa_system = None

        # Initialize embeddings (10% progress)
        status_container.info("🔄 Initializing embeddings model...")
        embeddings = get_embeddings_model()
        if not embeddings:
            status_container.error("❌ Failed to initialize embeddings model")
            return False
        progress_bar.progress(10)

        # Process documents
        all_chunks = []
        documents = []
        document_names = []

        progress_per_file = 70 / len(uploaded_files)
        current_progress = 10

        collection_id = kwargs.get('collection_id')

        for idx, uploaded_file in enumerate(uploaded_files):
            file_name = uploaded_file.name
            status_container.info(f"🔄 Processing document {idx + 1}/{len(uploaded_files)}: {file_name}")

            # Create temporary file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
                tmp_file.write(uploaded_file.getvalue())
                tmp_file.flush()

                # Process document with chunking
                chunks, content = process_document(tmp_file.name)

                # Store in database
                doc_id = insert_document(st.session_state.db_conn, file_name, content)
                if not doc_id:
                    status_container.error(f"❌ Failed to store document: {file_name}")
                    continue

                # Add to collection if specified
                if collection_id:
                    if not add_document_to_collection(st.session_state.db_conn, doc_id, collection_id):
                        status_container.warning(f"⚠️ Failed to add document to collection: {file_name}")

                # Add chunks with metadata
                for chunk in chunks:
                    chunk.metadata.update({
                        "source": file_name,
                        "document_id": doc_id,
                        "collection_id": collection_id if collection_id else None
                    })
                all_chunks.extend(chunks)

                documents.append(content)
                document_names.append(file_name)

            current_progress += progress_per_file
            progress_bar.progress(int(current_progress))

        # Initialize vector store with chunks
        status_container.info("🔄 Initializing vector store...")
        vector_store = FAISS.from_documents(
            all_chunks,
            embeddings
        )

        # Verify vector store
        status_container.info("🔄 Verifying document indexing...")
        details_container.text("✨ Performing final checks...")
        if not verify_vector_store(vector_store):
            status_container.error("❌ Vector store verification failed")
            return False

        # Initialize QA system (90-100% progress)
        status_container.info("🔄 Setting up QA system...")
        qa_system = initialize_qa_system(vector_store)
        if not qa_system:
            status_container.error("❌ Failed to initialize QA system")
            return False

        # Store in session state
        if collection_id:
            if 'vector_stores' not in st.session_state:
                st.session_state.vector_stores = {}
            st.session_state.vector_stores[collection_id] = vector_store
        else:
            st.session_state.vector_store = vector_store
        
        st.session_state.qa_system = qa_system

        # Complete!
        progress_bar.progress(100)
        status_container.success("✅ Documents processed successfully!")
        details_container.markdown(
            f"""
            🎉 **Ready to chat!**
            - Documents processed: {len(documents)}
            - Total content size: {sum(len(doc) for doc in documents) / 1024:.2f} KB
            - {"Added to collection" if collection_id else "Processed as standalone documents"}
            
            You can now start asking questions about your documents!
            """
        )

        # Add notification
        st.balloons()

        # Clean up progress display after 3 seconds
        time.sleep(3)
        progress_container.empty()
        status_container.empty()
        details_container.empty()

        return True

    except Exception as e:
        st.error(f"❌ Error processing documents: {str(e)}")
        if status_container:
            status_container.error(traceback.format_exc())
        # Reset states on error
        st.session_state.vector_store = None
        st.session_state.qa_system = None
        st.session_state.chat_ready = False
        return False

# Add these to your database.py file

def remove_from_collection(conn: sqlite3.Connection, document_id: int, collection_id: int) -> bool:
    """
    Remove a document from a collection.
    
    Args:
        conn (sqlite3.Connection): Database connection
        document_id (int): ID of the document to remove
        collection_id (int): ID of the collection
        
    Returns:
        bool: True if successful
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                DELETE FROM document_collections 
                WHERE document_id = ? AND collection_id = ?
            ''', (document_id, collection_id))
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error removing document from collection: {e}")
        return False

def update_collection(conn: sqlite3.Connection, collection_id: int, name: Optional[str] = None, 
                     description: Optional[str] = None) -> bool:
    """
    Update collection details.
    
    Args:
        conn (sqlite3.Connection): Database connection
        collection_id (int): ID of the collection to update
        name (Optional[str]): New name for the collection
        description (Optional[str]): New description for the collection
        
    Returns:
        bool: True if successful
    """
    try:
        with conn_lock:
            updates = []
            params = []
            
            if name is not None:
                updates.append("name = ?")
                params.append(name)
            if description is not None:
                updates.append("description = ?")
                params.append(description)
                
            if not updates:
                return True  # Nothing to update
                
            params.append(collection_id)
            
            cursor = conn.cursor()
            cursor.execute(f'''
                UPDATE collections 
                SET {", ".join(updates)}
                WHERE id = ?
            ''', params)
            
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error updating collection: {e}")
        return False

def search_documents(conn: sqlite3.Connection, query: str, 
                    collection_id: Optional[int] = None, 
                    filters: Optional[Dict] = None) -> List[Dict]:
    """
    Search documents using fuzzy matching and filters.
    
    Args:
        conn (sqlite3.Connection): Database connection
        query (str): Search query
        collection_id (Optional[int]): Filter by collection
        filters (Optional[Dict]): Additional filters
        
    Returns:
        List[Dict]: List of matching documents
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            
            # Base query
            sql = """
                SELECT DISTINCT
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date,
                    GROUP_CONCAT(c.name) as collections
                FROM documents d
                LEFT JOIN document_collections dc ON d.id = dc.document_id
                LEFT JOIN collections c ON dc.collection_id = c.id
            """
            
            params = []
            where_clauses = []
            
            # Add collection filter if specified
            if collection_id:
                where_clauses.append("dc.collection_id = ?")
                params.append(collection_id)
            
            # Add date filters if specified
            if filters and 'date_range' in filters:
                start_date, end_date = filters['date_range']
                where_clauses.append("d.upload_date BETWEEN ? AND ?")
                params.extend([start_date, end_date])
            
            # Add text search
            if query:
                where_clauses.append("(d.name LIKE ? OR d.content LIKE ?)")
                search_term = f"%{query}%"
                params.extend([search_term, search_term])
            
            # Combine WHERE clauses
            if where_clauses:
                sql += " WHERE " + " AND ".join(where_clauses)
            
            sql += " GROUP BY d.id ORDER BY d.upload_date DESC"
            
            # Execute query
            cursor.execute(sql, params)
            
            documents = []
            for row in cursor.fetchall():
                documents.append({
                    'id': row[0],
                    'name': row[1],
                    'content': row[2],
                    'upload_date': row[3],
                    'collections': row[4].split(',') if row[4] else []
                })
            
            return documents
            
    except sqlite3.Error as e:
        st.error(f"Error searching documents: {e}")
        return []

def get_all_documents(conn: sqlite3.Connection) -> List[Dict]:
    """
    Get all documents with their metadata and collection info.
    
    Args:
        conn (sqlite3.Connection): Database connection
        
    Returns:
        List[Dict]: List of documents with their metadata
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date,
                    GROUP_CONCAT(c.name) as collections
                FROM documents d
                LEFT JOIN document_collections dc ON d.id = dc.document_id
                LEFT JOIN collections c ON dc.collection_id = c.id
                GROUP BY d.id
                ORDER BY d.upload_date DESC
            ''')
            
            documents = []
            for row in cursor.fetchall():
                documents.append({
                    'id': row[0],
                    'name': row[1],
                    'content': row[2],
                    'upload_date': row[3],
                    'collections': row[4].split(',') if row[4] else []
                })
            return documents
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving documents: {e}")
        return []

def get_document_by_id(conn: sqlite3.Connection, document_id: int) -> Optional[Dict]:
    """
    Get a single document by its ID.
    
    Args:
        conn (sqlite3.Connection): Database connection
        document_id (int): ID of the document to retrieve
        
    Returns:
        Optional[Dict]: Document data if found, None otherwise
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date,
                    GROUP_CONCAT(c.name) as collections
                FROM documents d
                LEFT JOIN document_collections dc ON d.id = dc.document_id
                LEFT JOIN collections c ON dc.collection_id = c.id
                WHERE d.id = ?
                GROUP BY d.id
            ''', (document_id,))
            
            row = cursor.fetchone()
            if row:
                return {
                    'id': row[0],
                    'name': row[1],
                    'content': row[2],
                    'upload_date': row[3],
                    'collections': row[4].split(',') if row[4] else []
                }
            return None
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving document: {e}")
        return None

def get_recent_documents(conn: sqlite3.Connection, limit: int = 5) -> List[Dict]:
    """
    Get most recently uploaded documents.
    
    Args:
        conn (sqlite3.Connection): Database connection
        limit (int): Maximum number of documents to return
        
    Returns:
        List[Dict]: List of recent documents
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date,
                    GROUP_CONCAT(c.name) as collections
                FROM documents d
                LEFT JOIN document_collections dc ON d.id = dc.document_id
                LEFT JOIN collections c ON dc.collection_id = c.id
                GROUP BY d.id
                ORDER BY d.upload_date DESC
                LIMIT ?
            ''', (limit,))
            
            documents = []
            for row in cursor.fetchall():
                documents.append({
                    'id': row[0],
                    'name': row[1],
                    'content': row[2],
                    'upload_date': row[3],
                    'collections': row[4].split(',') if row[4] else []
                })
            return documents
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving recent documents: {e}")
        return []

def get_collections(conn: sqlite3.Connection) -> List[Dict]:
    """
    Get all collections with their document counts.
    
    Args:
        conn (sqlite3.Connection): Database connection
        
    Returns:
        List[Dict]: List of collections with metadata
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    c.id,
                    c.name,
                    c.description,
                    c.created_at,
                    COUNT(DISTINCT dc.document_id) as doc_count
                FROM collections c
                LEFT JOIN document_collections dc ON c.id = dc.collection_id
                GROUP BY c.id
                ORDER BY c.name
            ''')
            
            collections = []
            for row in cursor.fetchall():
                collections.append({
                    'id': row[0],
                    'name': row[1],
                    'description': row[2],
                    'created_at': row[3],
                    'doc_count': row[4]
                })
            return collections
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving collections: {e}")
        return []

def get_collection_documents(conn: sqlite3.Connection, collection_id: int) -> List[Dict]:
    """
    Get all documents in a specific collection.
    
    Args:
        conn (sqlite3.Connection): Database connection
        collection_id (int): ID of the collection
        
    Returns:
        List[Dict]: List of documents in the collection
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT 
                    d.id,
                    d.name,
                    d.content,
                    d.upload_date
                FROM documents d
                JOIN document_collections dc ON d.id = dc.document_id
                WHERE dc.collection_id = ?
                ORDER BY d.upload_date DESC
            ''', (collection_id,))
            
            documents = []
            for row in cursor.fetchall():
                documents.append({
                    'id': row[0],
                    'name': row[1],
                    'content': row[2],
                    'upload_date': row[3]
                })
            return documents
            
    except sqlite3.Error as e:
        st.error(f"Error retrieving collection documents: {e}")
        return []

def create_collection(conn: sqlite3.Connection, name: str, description: str = "") -> Optional[int]:
    """
    Create a new collection.
    
    Args:
        conn (sqlite3.Connection): Database connection
        name (str): Name of the collection
        description (str): Optional description
        
    Returns:
        Optional[int]: ID of the created collection if successful
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO collections (name, description)
                VALUES (?, ?)
            ''', (name, description))
            conn.commit()
            return cursor.lastrowid
            
    except sqlite3.Error as e:
        st.error(f"Error creating collection: {e}")
        return None

def add_document_to_collection(conn: sqlite3.Connection, document_id: int, collection_id: int) -> bool:
    """
    Add a document to a collection.
    
    Args:
        conn (sqlite3.Connection): Database connection
        document_id (int): ID of the document
        collection_id (int): ID of the collection
        
    Returns:
        bool: True if successful
    """
    try:
        with conn_lock:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT OR IGNORE INTO document_collections (document_id, collection_id)
                VALUES (?, ?)
            ''', (document_id, collection_id))
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error adding document to collection: {e}")
        return False

def process_document(file_path):
    """
    Process a PDF document with proper chunking.
    
    Args:
        file_path (str): Path to the PDF file
        
    Returns:
        tuple: (list of document chunks, full content of the document)
    """
    # Load PDF
    loader = PyPDFLoader(file_path)
    documents = loader.load()

    # Create text splitter
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=1000,
        chunk_overlap=200,
        length_function=len,
        separators=["\n\n", "\n", " ", ""]
    )

    # Split documents into chunks
    chunks = text_splitter.split_documents(documents)

    # Extract full content for database storage
    full_content = "\n".join(doc.page_content for doc in documents)

    return chunks, full_content


def delete_collection(conn: sqlite3.Connection, collection_id: int) -> bool:
    """Delete a collection and its associations."""
    try:
        with conn_lock:
            cursor = conn.cursor()
            # Delete the collection's document associations first
            cursor.execute('''
                DELETE FROM document_collections 
                WHERE collection_id = ?
            ''', (collection_id,))
            
            # Then delete the collection itself
            cursor.execute('''
                DELETE FROM collections 
                WHERE id = ?
            ''', (collection_id,))
            
            conn.commit()
            return True
            
    except sqlite3.Error as e:
        st.error(f"Error deleting collection: {e}")
        return False

def display_vector_store_info():
    """
    Display information about the current vector store state.
    """
    if 'vector_store' not in st.session_state:
        st.info("ℹ️ No documents loaded yet.")
        return

    try:
        # Get the vector store from session state
        vector_store = st.session_state.vector_store

        # Get basic stats
        test_query = vector_store.similarity_search("test", k=1)
        doc_count = len(test_query)

        # Create an expander for detailed info
        with st.expander("📊 Knowledge Base Status"):
            col1, col2 = st.columns(2)

            with col1:
                st.metric(
                    label="Documents Loaded",
                    value=doc_count
                )

            with col2:
                st.metric(
                    label="System Status",
                    value="Ready" if verify_vector_store(vector_store) else "Not Ready"
                )

            # Display sample queries
            if verify_vector_store(vector_store):
                st.markdown("### 🔍 Sample Document Snippets")
                sample_docs = vector_store.similarity_search("", k=3)
                for i, doc in enumerate(sample_docs, 1):
                    with st.container():
                        st.markdown(f"**Snippet {i}:**")
                        st.text(doc.page_content[:200] + "...")

    except Exception as e:
        st.error(f"Error displaying vector store info: {e}")
        st.error(traceback.format_exc())


def process_and_store_document(uploaded_file) -> Optional[int]:
    """
    Process an uploaded document and store it in the database.
    
    Args:
        uploaded_file: Streamlit's UploadedFile object
        
    Returns:
        Optional[int]: The ID of the stored document if successful, None otherwise
    """
    try:
        # Create a temporary file to store the uploaded content
        with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
            tmp_file.write(uploaded_file.getvalue())
            tmp_file.flush()
            
            # Load and process the PDF
            loader = PyPDFLoader(tmp_file.name)
            documents = loader.load()
            
            # Create text splitter for processing
            text_splitter = RecursiveCharacterTextSplitter(
                chunk_size=1000,
                chunk_overlap=200,
                length_function=len,
                separators=["\n\n", "\n", " ", ""]
            )
            
            # Split documents into chunks
            chunks = text_splitter.split_documents(documents)
            
            # Extract full content for database storage
            full_content = "\n".join(doc.page_content for doc in documents)
            
            # Store in database
            with st.session_state.db_conn as conn:
                cursor = conn.cursor()
                
                # Insert document
                cursor.execute('''
                    INSERT INTO documents (name, content, upload_date)
                    VALUES (?, ?, ?)
                ''', (uploaded_file.name, full_content, datetime.now()))
                
                # Get the document ID
                document_id = cursor.lastrowid
                
                conn.commit()
                
                return document_id
                
    except Exception as e:
        st.error(f"Error processing document {uploaded_file.name}: {str(e)}")
        import traceback
        st.error(traceback.format_exc())
        return None
    finally:
        # Clean up temporary file
        import os
        try:
            os.unlink(tmp_file.name)
        except:
            pass

def get_document_content(conn: sqlite3.Connection, document_id: int) -> Optional[str]:
    """
    Retrieve the content of a specific document.
    
    Args:
        conn: Database connection
        document_id: ID of the document to retrieve
        
    Returns:
        Optional[str]: The document content if found, None otherwise
    """
    try:
        cursor = conn.cursor()
        cursor.execute('''
            SELECT content
            FROM documents
            WHERE id = ?
        ''', (document_id,))
        
        result = cursor.fetchone()
        return result[0] if result else None
        
    except sqlite3.Error as e:
        st.error(f"Error retrieving document content: {e}")
        return None

def initialize_qa_system(vector_store):
    """
    Initialize QA system with optimized retrieval.

    Args:
        vector_store (FAISS): FAISS vector store instance.
    Returns:
        dict: QA system chain or None if initialization fails.
    """
    try:
        llm = ChatOpenAI(
            temperature=0.5,
            model_name="gpt-4",
            max_tokens=4000,
            api_key=os.environ.get("OPENAI_API_KEY")
        )

        # Optimize retriever settings and add source tracking
        retriever = vector_store.as_retriever(
            search_kwargs={
                "k": 3,  # Retrieve fewer, more relevant chunks
                "fetch_k": 5,  # Consider more candidates before selecting top k
                "include_metadata": True  # Enable source tracking
            }
        )

        # Create a template that enforces clean formatting
        prompt = ChatPromptTemplate.from_messages([
            ("system", """
You are an expert consultant specializing in analyzing Request for Proposal (RFP) documents. Your goal is to assist users by providing clear, concise, and professional insights based on the content provided. Please adhere to the following guidelines when crafting your responses:

Begin with a summary that highlights the key findings or answers the main query.

Structured Format: Use clear and descriptive section headers to organize the information logically.

Bullet Points: Utilize bullet points for lists or complex information to enhance readability.

Source Attribution: Cite specific sections or page numbers from the RFP document when referencing information.

Professional Formatting: Maintain a clean and professional layout using Markdown formatting, such as headings, bullet points, bold, italics, and tables where appropriate.

Use Markdown Syntax: Ensure the response is fully formatted using Markdown for optimal readability in the chat.

Focused Content: Keep your responses concise and directly related to the user's query, avoiding unnecessary information.

Scope Awareness: If a query falls outside the provided information or context, politely acknowledge this and suggest consulting the relevant sections or additional sources.

Confidentiality: Respect the confidentiality of the information provided and avoid sharing any sensitive data beyond the scope of the query.

Tone and Language: Use formal and professional language, ensuring clarity and precision in your responses.

Accuracy: Double-check all information for accuracy and completeness before providing it to the user.
"""),
            MessagesPlaceholder(variable_name="chat_history"),
            ("human", "{input}\n\nContext: {context}")
        ])
        
        def get_chat_history(inputs):
            chat_history = inputs.get("chat_history", [])
            if not isinstance(chat_history, list):
                return []
            return [msg for msg in chat_history if isinstance(msg, BaseMessage)]

        def get_context(inputs):
            docs = retriever.get_relevant_documents(inputs["input"])
            context_parts = []
            for doc in docs:
                source = doc.metadata.get('source', 'Unknown source')
                context_parts.append(f"\nFrom {source}:\n{doc.page_content}")
            return "\n".join(context_parts)

        chain = (
            {
                "context": lambda x: get_context_with_sources(retriever, x["input"]),
                "chat_history": lambda x: format_chat_history(x["chat_history"]),
                "input": lambda x: x["input"]
            }
            | prompt
            | llm
        )

        return chain

    except Exception as e:
        st.error(f"Error initializing QA system: {e}")
        return None


# FAISS vector store initialization
def initialize_faiss(embeddings, documents, document_names):
    """
    Initialize FAISS vector store.

    Args:
        embeddings (Embeddings): Embeddings model to use.
        documents (list): List of document contents.
        document_names (list): List of document names.
    Returns:
        FAISS: FAISS vector store instance or None if initialization fails.
    """
    try:
        from langchain.vectorstores import FAISS

        vector_store = FAISS.from_texts(
            documents,
            embeddings,
            metadatas=[{"source": name} for name in document_names],
        )
        return vector_store
    except Exception as e:
        st.error(f"Error initializing FAISS: {e}")
        return None


# Embeddings model retrieval
@st.cache_resource
def get_embeddings_model():
    """
    Get the embeddings model.

    Returns:
        Embeddings: Embeddings model instance or None if loading fails.
    """
    try:
        from langchain.embeddings import HuggingFaceEmbeddings

        model_name = "sentence-transformers/all-MiniLM-L6-v2"
        embeddings = HuggingFaceEmbeddings(model_name=model_name)
        return embeddings
    except Exception as e:
        st.error(f"Error loading embeddings model: {e}")
        return None