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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66a2900
 
 
639f0d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66a2900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
# SQLite_DB.py
#########################################
# SQLite_DB Library
# This library is used to perform any/all DB operations related to SQLite.
#
####
import configparser
####################
# Function List
# FIXME - UPDATE Function Arguments
# 1. get_connection(self)
# 2. execute_query(self, query: str, params: Tuple = ())
# 3. create_tables()
# 4. add_keyword(keyword: str)
# 5. delete_keyword(keyword: str)
# 6. add_media_with_keywords(url, title, media_type, content, keywords, prompt, summary, transcription_model, author, ingestion_date)
# 7. fetch_all_keywords()
# 8. keywords_browser_interface()
# 9. display_keywords()
# 10. export_keywords_to_csv()
# 11. browse_items(search_query, search_type)
# 12. fetch_item_details(media_id: int)
# 13. add_media_version(media_id: int, prompt: str, summary: str)
# 14. search_db(search_query: str, search_fields: List[str], keywords: str, page: int = 1, results_per_page: int = 10)
# 15. search_and_display(search_query, search_fields, keywords, page)
# 16. display_details(index, results)
# 17. get_details(index, dataframe)
# 18. format_results(results)
# 19. export_to_csv(search_query: str, search_fields: List[str], keyword: str, page: int = 1, results_per_file: int = 1000)
# 20. is_valid_url(url: str) -> bool
# 21. is_valid_date(date_string: str) -> bool
# 22. add_media_to_database(url, info_dict, segments, summary, keywords, custom_prompt_input, whisper_model)
# 23. create_prompts_db()
# 24. add_prompt(name, details, system, user=None)
# 25. fetch_prompt_details(name)
# 26. list_prompts()
# 27. insert_prompt_to_db(title, description, system_prompt, user_prompt)
# 28. update_media_content(media_id: int, content: str, prompt: str, summary: str)
# 29. search_media_database(query: str) -> List[Tuple[int, str, str]]
# 30. load_media_content(media_id: int)
# 31.
# 32.
#
#
#####################
#
# Import necessary libraries
import csv
import html
import logging
import os
import queue
import re
import shutil
import sqlite3
import traceback
from datetime import datetime, timedelta
from typing import List, Tuple, Dict, Any, Optional
# Local Libraries
from App_Function_Libraries.Utils.Utils import get_project_relative_path, get_database_path, \
    get_database_dir
from App_Function_Libraries.Chunk_Lib import chunk_options, chunk_text
#
# Third-Party Libraries
import gradio as gr
import pandas as pd
import yaml
#
#######################################################################################################################
# Function Definitions
#

def ensure_database_directory():
    os.makedirs(get_database_dir(), exist_ok=True)

ensure_database_directory()

# Set up logging
logger = logging.getLogger(__name__)

# FIXME - Setup properly and test/add documentation for its existence...
# Construct the path to the config file
config_path = get_project_relative_path('Config_Files/config.txt')

# Read the config file
config = configparser.ConfigParser()
config.read(config_path)

# Get the SQLite path from the config, or use the default if not specified
sqlite_path = config.get('Database', 'sqlite_path', fallback=get_database_path('media_summary.db'))

# Get the backup path from the config, or use the default if not specified
backup_path = config.get('Database', 'backup_path', fallback='database_backups')
backup_path = get_project_relative_path(backup_path)

# Set the final paths
db_path = sqlite_path
backup_dir = backup_path

print(f"Database path: {db_path}")
print(f"Backup directory: {backup_dir}")
#create_automated_backup(db_path, backup_dir)

# FIXME - Setup properly and test/add documentation for its existence...
#backup_file = create_automated_backup(db_path, backup_dir)
#upload_to_s3(backup_file, 'your-s3-bucket-name', f"database_backups/{os.path.basename(backup_file)}")

# FIXME - Setup properly and test/add documentation for its existence...
#create_incremental_backup(db_path, backup_dir)

# FIXME - Setup properly and test/add documentation for its existence...
#rotate_backups(backup_dir)

#
#
#######################################################################################################################


#######################################################################################################################
#
# Backup-related functions

def create_incremental_backup(db_path, backup_dir):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # Get the page count of the database
    cursor.execute("PRAGMA page_count")
    page_count = cursor.fetchone()[0]

    # Create a new backup file
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_file = os.path.join(backup_dir, f"incremental_backup_{timestamp}.sqlib")

    # Perform the incremental backup
    conn.execute(f"VACUUM INTO '{backup_file}'")

    conn.close()
    print(f"Incremental backup created: {backup_file}")
    return backup_file


def create_automated_backup(db_path, backup_dir):
    # Ensure backup directory exists
    os.makedirs(backup_dir, exist_ok=True)

    # Create a timestamped backup file name
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_file = os.path.join(backup_dir, f"media_db_backup_{timestamp}.db")

    # Copy the database file
    shutil.copy2(db_path, backup_file)

    print(f"Backup created: {backup_file}")
    return backup_file

# FIXME - boto3 aint getting installed by default....
# def upload_to_s3(file_path, bucket_name, s3_key):
#     import boto3
#     s3 = boto3.client('s3')
#     try:
#         s3.upload_file(file_path, bucket_name, s3_key)
#         print(f"File uploaded to S3: {s3_key}")
#     except Exception as e:
#         print(f"Error uploading to S3: {str(e)}")


def rotate_backups(backup_dir, max_backups=10):
    backups = sorted(
        [f for f in os.listdir(backup_dir) if f.endswith('.db')],
        key=lambda x: os.path.getmtime(os.path.join(backup_dir, x)),
        reverse=True
    )

    while len(backups) > max_backups:
        old_backup = backups.pop()
        os.remove(os.path.join(backup_dir, old_backup))
        print(f"Removed old backup: {old_backup}")

#
#
#######################################################################################################################


#######################################################################################################################
#
# DB-Integrity Check Functions

def check_database_integrity(db_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute("PRAGMA integrity_check")
    result = cursor.fetchone()

    conn.close()

    if result[0] == "ok":
        print("Database integrity check passed.")
        return True
    else:
        print("Database integrity check failed:", result[0])
        return False

#check_database_integrity(db_path)

#
# End of DB-Integrity Check functions
#######################################################################################################################


#######################################################################################################################
#
# DB Setup Functions

class DatabaseError(Exception):
    pass

class InputError(Exception):
    pass

class Database:
    def __init__(self, db_name='media_summary.db'):
        self.db_path = get_database_path(db_name)
        self.timeout = 60.0  # 60 seconds timeout

    def get_connection(self):
        return sqlite3.connect(self.db_path, timeout=self.timeout)

    def execute_query(self, query: str, params: Tuple = ()) -> None:
        with self.get_connection() as conn:
            try:
                cursor = conn.cursor()
                cursor.execute(query, params)
                conn.commit()
            except sqlite3.Error as e:
                logging.error(f"Database error: {e}, Query: {query}")
                raise DatabaseError(f"Database error: {e}, Query: {query}")

    def execute_many(self, query: str, params_list: List[Tuple]) -> None:
        with self.get_connection() as conn:
            try:
                cursor = conn.cursor()
                cursor.executemany(query, params_list)
                conn.commit()
            except sqlite3.Error as e:
                logging.error(f"Database error: {e}, Query: {query}")
                raise DatabaseError(f"Database error: {e}, Query: {query}")

db = Database()

def instantiate_sqlite_db():
    global sqlite_db
    sqlite_db = Database()


# Function to create tables with the new media schema
def create_tables(db) -> None:
    table_queries = [
        # CREATE TABLE statements
        '''

        CREATE TABLE IF NOT EXISTS Media (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            url TEXT,

            title TEXT NOT NULL,

            type TEXT NOT NULL,

            content TEXT,

            author TEXT,

            ingestion_date TEXT,

            prompt TEXT,

            summary TEXT,

            transcription_model TEXT,

            is_trash BOOLEAN DEFAULT 0,

            trash_date DATETIME,

            vector_embedding BLOB,

            chunking_status TEXT DEFAULT 'pending'

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS Keywords (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            keyword TEXT NOT NULL UNIQUE

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS MediaKeywords (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER NOT NULL,

            keyword_id INTEGER NOT NULL,

            FOREIGN KEY (media_id) REFERENCES Media(id),

            FOREIGN KEY (keyword_id) REFERENCES Keywords(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS MediaVersion (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER NOT NULL,

            version INTEGER NOT NULL,

            prompt TEXT,

            summary TEXT,

            created_at TEXT NOT NULL,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS MediaModifications (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER NOT NULL,

            prompt TEXT,

            summary TEXT,

            modification_date TEXT,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS ChatConversations (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER,

            media_name TEXT,

            conversation_name TEXT,

            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS ChatMessages (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            conversation_id INTEGER,

            sender TEXT,

            message TEXT,

            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            FOREIGN KEY (conversation_id) REFERENCES ChatConversations(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS Transcripts (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER,

            whisper_model TEXT,

            transcription TEXT,

            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS MediaChunks (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER,

            chunk_text TEXT,

            start_index INTEGER,

            end_index INTEGER,

            chunk_id TEXT,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )''',
        '''

        CREATE TABLE IF NOT EXISTS UnvectorizedMediaChunks (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER NOT NULL,

            chunk_text TEXT NOT NULL,

            chunk_index INTEGER NOT NULL,

            start_char INTEGER NOT NULL,

            end_char INTEGER NOT NULL,

            chunk_type TEXT,

            creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            is_processed BOOLEAN DEFAULT FALSE,

            metadata TEXT,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''',
        '''

        CREATE TABLE IF NOT EXISTS DocumentVersions (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER NOT NULL,

            version_number INTEGER NOT NULL,

            content TEXT,

            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''',
    ]

    index_queries = [
        # CREATE INDEX statements
        'CREATE INDEX IF NOT EXISTS idx_media_title ON Media(title)',
        'CREATE INDEX IF NOT EXISTS idx_media_type ON Media(type)',
        'CREATE INDEX IF NOT EXISTS idx_media_author ON Media(author)',
        'CREATE INDEX IF NOT EXISTS idx_media_ingestion_date ON Media(ingestion_date)',
        'CREATE INDEX IF NOT EXISTS idx_keywords_keyword ON Keywords(keyword)',
        'CREATE INDEX IF NOT EXISTS idx_mediakeywords_media_id ON MediaKeywords(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_mediakeywords_keyword_id ON MediaKeywords(keyword_id)',
        'CREATE INDEX IF NOT EXISTS idx_media_version_media_id ON MediaVersion(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_mediamodifications_media_id ON MediaModifications(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_chatconversations_media_id ON ChatConversations(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_chatmessages_conversation_id ON ChatMessages(conversation_id)',
        'CREATE INDEX IF NOT EXISTS idx_media_is_trash ON Media(is_trash)',
        'CREATE INDEX IF NOT EXISTS idx_mediachunks_media_id ON MediaChunks(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_unvectorized_media_chunks_media_id ON UnvectorizedMediaChunks(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_unvectorized_media_chunks_is_processed ON UnvectorizedMediaChunks(is_processed)',
        'CREATE INDEX IF NOT EXISTS idx_unvectorized_media_chunks_chunk_type ON UnvectorizedMediaChunks(chunk_type)',
        # CREATE UNIQUE INDEX statements
        'CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_media_url ON Media(url)',
        'CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_media_keyword ON MediaKeywords(media_id, keyword_id)',
        'CREATE INDEX IF NOT EXISTS idx_document_versions_media_id ON DocumentVersions(media_id)',
        'CREATE INDEX IF NOT EXISTS idx_document_versions_version_number ON DocumentVersions(version_number)',
    ]

    virtual_table_queries = [
        # CREATE VIRTUAL TABLE statements
        'CREATE VIRTUAL TABLE IF NOT EXISTS media_fts USING fts5(title, content)',
        'CREATE VIRTUAL TABLE IF NOT EXISTS keyword_fts USING fts5(keyword)'
    ]

    all_queries = table_queries + index_queries + virtual_table_queries

    for query in all_queries:
        try:
            db.execute_query(query)
        except Exception as e:
            logging.error(f"Error executing query: {query}")
            logging.error(f"Error details: {str(e)}")
            raise

    logging.info("All tables, indexes, and virtual tables created successfully.")

create_tables(db)


def check_media_exists(title: str, url: str) -> Optional[int]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            query = 'SELECT id FROM Media WHERE title = ? AND url = ?'
            cursor.execute(query, (title, url))
            result = cursor.fetchone()
            logging.debug(f"check_media_exists query: {query}")
            logging.debug(f"check_media_exists params: title={title}, url={url}")
            logging.debug(f"check_media_exists result: {result}")
            return result[0] if result else None
    except Exception as e:
        logging.error(f"Error checking if media exists: {str(e)}")
        logging.error(f"Exception details: {traceback.format_exc()}")
        return None


def check_media_and_whisper_model(title=None, url=None, current_whisper_model=None):
    """

    Check if media exists in the database and compare the whisper model used.



    :param title: Title of the media (optional)

    :param url: URL of the media (optional)

    :param current_whisper_model: The whisper model currently selected for use

    :return: Tuple (bool, str) - (should_download, reason)

    """
    if not title and not url:
        return True, "No title or URL provided"

    with db.get_connection() as conn:
        cursor = conn.cursor()

        # First, find the media_id
        query = "SELECT id FROM Media WHERE "
        params = []

        if title:
            query += "title = ?"
            params.append(title)

        if url:
            if params:
                query += " OR "
            query += "url = ?"
            params.append(url)

        cursor.execute(query, tuple(params))
        result = cursor.fetchone()

        if not result:
            return True, "Media not found in database"

        media_id = result[0]

        # Now, get the latest transcript for this media
        cursor.execute("""

            SELECT transcription 

            FROM Transcripts 

            WHERE media_id = ? 

            ORDER BY created_at DESC 

            LIMIT 1

        """, (media_id,))

        transcript_result = cursor.fetchone()

        if not transcript_result:
            return True, f"No transcript found for media (ID: {media_id})"

        transcription = transcript_result[0]

        # Extract the whisper model from the transcription
        match = re.search(r"This text was transcribed using whisper model: (.+)$", transcription, re.MULTILINE)
        if not match:
            return True, f"Whisper model information not found in transcript (Media ID: {media_id})"

        db_whisper_model = match.group(1).strip()

        if not current_whisper_model:
            return False, f"Media found in database (ID: {media_id})"

        if db_whisper_model != current_whisper_model:
            return True, f"Different whisper model (DB: {db_whisper_model}, Current: {current_whisper_model})"

        return False, f"Media found with same whisper model (ID: {media_id})"


def add_media_chunk(media_id: int, chunk_text: str, start_index: int, end_index: int, chunk_id: str):
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO MediaChunks (media_id, chunk_text, start_index, end_index, chunk_id) VALUES (?, ?, ?, ?, ?)",
            (media_id, chunk_text, start_index, end_index, chunk_id)
        )
        conn.commit()

def sqlite_update_fts_for_media(db, media_id: int):
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("INSERT OR REPLACE INTO media_fts (rowid, title, content) SELECT id, title, content FROM Media WHERE id = ?", (media_id,))
        conn.commit()


def sqlite_get_unprocessed_media(db):
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT id, content, type FROM Media WHERE id NOT IN (SELECT DISTINCT media_id FROM MediaChunks)")
        return cursor.fetchall()

def get_next_media_id():
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT MAX(media_id) FROM media")
        max_id = cursor.fetchone()[0]
        return (max_id or 0) + 1
    finally:
        conn.close()

#
# End of Media-related Functions
#######################################################################################################################


#######################################################################################################################
# Keyword-related Functions
#

# Function to add a keyword
def add_keyword(keyword: str) -> int:
    keyword = keyword.strip().lower()
    with db.get_connection() as conn:
        cursor = conn.cursor()
        try:
            cursor.execute('INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)', (keyword,))
            cursor.execute('SELECT id FROM Keywords WHERE keyword = ?', (keyword,))
            keyword_id = cursor.fetchone()[0]
            cursor.execute('INSERT OR IGNORE INTO keyword_fts (rowid, keyword) VALUES (?, ?)', (keyword_id, keyword))
            logging.info(f"Keyword '{keyword}' added to keyword_fts with ID: {keyword_id}")
            conn.commit()
            return keyword_id
        except sqlite3.IntegrityError as e:
            logging.error(f"Integrity error adding keyword: {e}")
            raise DatabaseError(f"Integrity error adding keyword: {e}")
        except sqlite3.Error as e:
            logging.error(f"Error adding keyword: {e}")
            raise DatabaseError(f"Error adding keyword: {e}")


# Function to delete a keyword
def delete_keyword(keyword: str) -> str:
    keyword = keyword.strip().lower()
    with db.get_connection() as conn:
        cursor = conn.cursor()
        try:
            cursor.execute('SELECT id FROM Keywords WHERE keyword = ?', (keyword,))
            keyword_id = cursor.fetchone()
            if keyword_id:
                cursor.execute('DELETE FROM Keywords WHERE keyword = ?', (keyword,))
                cursor.execute('DELETE FROM keyword_fts WHERE rowid = ?', (keyword_id[0],))
                conn.commit()
                return f"Keyword '{keyword}' deleted successfully."
            else:
                return f"Keyword '{keyword}' not found."
        except sqlite3.Error as e:
            raise DatabaseError(f"Error deleting keyword: {e}")



# Function to add media with keywords
def add_media_with_keywords(url, title, media_type, content, keywords, prompt, summary, transcription_model, author,

                            ingestion_date):
    logging.debug(f"Entering add_media_with_keywords: URL={url}, Title={title}")
    # Set default values for missing fields
    if url is None:
        url = 'localhost'
    elif url is not None:
        url = url
    title = title or 'Untitled'
    media_type = media_type or 'Unknown'
    content = content or 'No content available'
    keywords = keywords or 'default'
    prompt = prompt or 'No prompt available'
    summary = summary or 'No summary available'
    transcription_model = transcription_model or 'Unknown'
    author = author or 'Unknown'
    ingestion_date = ingestion_date or datetime.now().strftime('%Y-%m-%d')

    if media_type not in ['article', 'audio', 'document', 'mediawiki_article', 'mediawiki_dump', 'obsidian_note', 'podcast', 'text', 'video', 'unknown']:
        raise InputError("Invalid media type. Allowed types: article, audio file, document, obsidian_note podcast, text, video, unknown.")

    if ingestion_date and not is_valid_date(ingestion_date):
        raise InputError("Invalid ingestion date format. Use YYYY-MM-DD.")

    # Handle keywords as either string or list
    if isinstance(keywords, str):
        keyword_list = [keyword.strip().lower() for keyword in keywords.split(',')]
    elif isinstance(keywords, list):
        keyword_list = [keyword.strip().lower() for keyword in keywords]
    else:
        keyword_list = ['default']

    logging.info(f"Adding/updating media: URL={url}, Title={title}, Type={media_type}")
    logging.debug(f"Content (first 500 chars): {content[:500]}...")
    logging.debug(f"Keywords: {keyword_list}")
    logging.info(f"Prompt: {prompt}")
    logging.info(f"Summary: {summary}")
    logging.info(f"Author: {author}")
    logging.info(f"Ingestion Date: {ingestion_date}")
    logging.info(f"Transcription Model: {transcription_model}")

    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            # Check if media already exists using both title and URL
            existing_media_id = check_media_exists(title, url)
            logging.debug(f"Existing media ID for {url}: {existing_media_id}")

            if existing_media_id:
                media_id = existing_media_id
                logging.debug(f"Updating existing media with ID: {media_id}")
                cursor.execute('''

                UPDATE Media 

                SET content = ?, transcription_model = ?, type = ?, author = ?, ingestion_date = ?

                WHERE id = ?

                ''', (content, transcription_model, media_type, author, ingestion_date, media_id))
            else:
                logging.debug("Inserting new media")
                cursor.execute('''

                INSERT INTO Media (url, title, type, content, author, ingestion_date, transcription_model)

                VALUES (?, ?, ?, ?, ?, ?, ?)

                ''', (url, title, media_type, content, author, ingestion_date, transcription_model))
                media_id = cursor.lastrowid
                logging.debug(f"New media inserted with ID: {media_id}")

            cursor.execute('''

            INSERT INTO MediaModifications (media_id, prompt, summary, modification_date)

            VALUES (?, ?, ?, ?)

            ''', (media_id, prompt, summary, ingestion_date))

            # Batch insert keywords
            keyword_params = [(keyword.strip().lower(),) for keyword in keyword_list]
            cursor.executemany('INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)', keyword_params)

            # Get keyword IDs
            placeholder = ','.join(['?'] * len(keyword_list))
            cursor.execute(f'SELECT id, keyword FROM Keywords WHERE keyword IN ({placeholder})', keyword_list)
            keyword_ids = cursor.fetchall()

            # Batch insert media-keyword associations
            media_keyword_params = [(media_id, keyword_id) for keyword_id, _ in keyword_ids]
            cursor.executemany('INSERT OR IGNORE INTO MediaKeywords (media_id, keyword_id) VALUES (?, ?)', media_keyword_params)

            # Update full-text search index
            cursor.execute('INSERT OR REPLACE INTO media_fts (rowid, title, content) VALUES (?, ?, ?)',
                           (media_id, title, content))

            # Add media version
            add_media_version(conn, media_id, prompt, summary)

            conn.commit()
            logging.info(f"Media '{title}' successfully added/updated with ID: {media_id}")

        return media_id, f"Media '{title}' added/updated successfully with keywords: {', '.join(keyword_list)}"

    except sqlite3.Error as e:
        logging.error(f"SQL Error in add_media_with_keywords: {e}")
        raise DatabaseError(f"Error adding media with keywords: {e}")
    except Exception as e:
        logging.error(f"Unexpected Error in add_media_with_keywords: {e}")
        raise DatabaseError(f"Unexpected error: {e}")


def ingest_article_to_db(url, title, author, content, keywords, summary, ingestion_date, custom_prompt):
    try:
        # Check if content is not empty or whitespace
        if not content.strip():
            raise ValueError("Content is empty.")

        keyword_list = keywords.split(',') if keywords else ["default"]
        keyword_str = ', '.join(keyword_list)

        # Set default values for missing fields
        url = url or 'Unknown'
        title = title or 'Unknown'
        author = author or 'Unknown'
        keywords = keywords or 'default'
        summary = summary or 'No summary available'
        ingestion_date = ingestion_date or datetime.now().strftime('%Y-%m-%d')

        # Log the values of all fields before calling add_media_with_keywords
        logging.debug(f"URL: {url}")
        logging.debug(f"Title: {title}")
        logging.debug(f"Author: {author}")
        logging.debug(f"Content: {content[:50]}... (length: {len(content)})")  # Log first 50 characters of content
        logging.debug(f"Keywords: {keywords}")
        logging.debug(f"Summary: {summary}")
        logging.debug(f"Ingestion Date: {ingestion_date}")
        logging.debug(f"Custom Prompt: {custom_prompt}")

        # Check if any required field is empty and log the specific missing field
        if not url:
            logging.error("URL is missing.")
            raise ValueError("URL is missing.")
        if not title:
            logging.error("Title is missing.")
            raise ValueError("Title is missing.")
        if not content:
            logging.error("Content is missing.")
            raise ValueError("Content is missing.")
        if not keywords:
            logging.error("Keywords are missing.")
            raise ValueError("Keywords are missing.")
        if not summary:
            logging.error("Summary is missing.")
            raise ValueError("Summary is missing.")
        if not ingestion_date:
            logging.error("Ingestion date is missing.")
            raise ValueError("Ingestion date is missing.")
        if not custom_prompt:
            logging.error("Custom prompt is missing.")
            raise ValueError("Custom prompt is missing.")

        # Add media with keywords to the database
        result = add_media_with_keywords(
            url=url,
            title=title,
            media_type='article',
            content=content,
            keywords=keyword_str or "article_default",
            prompt=custom_prompt or None,
            summary=summary or "No summary generated",
            transcription_model=None,  # or some default value if applicable
            author=author or 'Unknown',
            ingestion_date=ingestion_date
        )
        return result
    except Exception as e:
        logging.error(f"Failed to ingest article to the database: {e}")
        return str(e)


def fetch_all_keywords() -> List[str]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT keyword FROM Keywords')
            keywords = [row[0] for row in cursor.fetchall()]
            return keywords
    except sqlite3.Error as e:
        raise DatabaseError(f"Error fetching keywords: {e}")

def keywords_browser_interface():
    keywords = fetch_all_keywords()
    return gr.Markdown("\n".join(f"- {keyword}" for keyword in keywords))

def display_keywords():
    try:
        keywords = fetch_all_keywords()
        return "\n".join(keywords) if keywords else "No keywords found."
    except DatabaseError as e:
        return str(e)


def export_keywords_to_csv():
    try:
        keywords = fetch_all_keywords()
        if not keywords:
            return None, "No keywords found in the database."

        filename = "keywords.csv"
        with open(filename, 'w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(["Keyword"])
            for keyword in keywords:
                writer.writerow([keyword])

        return filename, f"Keywords exported to {filename}"
    except Exception as e:
        logger.error(f"Error exporting keywords to CSV: {e}")
        return None, f"Error exporting keywords: {e}"

def fetch_keywords_for_media(media_id):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

                SELECT k.keyword

                FROM Keywords k

                JOIN MediaKeywords mk ON k.id = mk.keyword_id

                WHERE mk.media_id = ?

            ''', (media_id,))
            keywords = [row[0] for row in cursor.fetchall()]
        return keywords
    except sqlite3.Error as e:
        logging.error(f"Error fetching keywords: {e}")
        return []

def update_keywords_for_media(media_id, keyword_list):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            # Remove old keywords
            cursor.execute('DELETE FROM MediaKeywords WHERE media_id = ?', (media_id,))

            # Add new keywords
            for keyword in keyword_list:
                cursor.execute('INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)', (keyword,))
                cursor.execute('SELECT id FROM Keywords WHERE keyword = ?', (keyword,))
                keyword_id = cursor.fetchone()[0]
                cursor.execute('INSERT INTO MediaKeywords (media_id, keyword_id) VALUES (?, ?)', (media_id, keyword_id))

            conn.commit()
        return "Keywords updated successfully."
    except sqlite3.Error as e:
        logging.error(f"Error updating keywords: {e}")
        return "Error updating keywords."

#
# End of Keyword-related functions
#######################################################################################################################


#######################################################################################################################
#
# Media-related Functions



# Function to fetch items based on search query and type
def browse_items(search_query, search_type):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            if search_type == 'Title':
                cursor.execute("SELECT id, title, url FROM Media WHERE title LIKE ?", (f'%{search_query}%',))
            elif search_type == 'URL':
                cursor.execute("SELECT id, title, url FROM Media WHERE url LIKE ?", (f'%{search_query}%',))
            elif search_type == 'Keyword':
                return fetch_items_by_keyword(search_query)
            elif search_type == 'Content':
                cursor.execute("SELECT id, title, url FROM Media WHERE content LIKE ?", (f'%{search_query}%',))
            else:
                raise ValueError(f"Invalid search type: {search_type}")

            results = cursor.fetchall()
            return results
    except sqlite3.Error as e:
        logger.error(f"Error fetching items by {search_type}: {e}")
        raise DatabaseError(f"Error fetching items by {search_type}: {e}")


# Function to fetch item details
def fetch_item_details(media_id: int):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""

                SELECT prompt, summary 

                FROM MediaModifications 

                WHERE media_id = ? 

                ORDER BY modification_date DESC 

                LIMIT 1

            """, (media_id,))
            prompt_summary_result = cursor.fetchone()
            cursor.execute("SELECT content FROM Media WHERE id = ?", (media_id,))
            content_result = cursor.fetchone()

            prompt = prompt_summary_result[0] if prompt_summary_result else ""
            summary = prompt_summary_result[1] if prompt_summary_result else ""
            content = content_result[0] if content_result else ""

            return content, prompt, summary
    except sqlite3.Error as e:
        logging.error(f"Error fetching item details: {e}")
        # Return empty strings if there's an error
        return "", "", ""

#
#  End of Media-related Functions
#######################################################################################################################


#######################################################################################################################
#
# Media-related Functions



# Function to add a version of a prompt and summary
def add_media_version(conn, media_id: int, prompt: str, summary: str) -> None:
    try:
        cursor = conn.cursor()

        # Get the current version number
        cursor.execute('SELECT MAX(version) FROM MediaVersion WHERE media_id = ?', (media_id,))
        current_version = cursor.fetchone()[0] or 0

        # Insert the new version
        cursor.execute('''

        INSERT INTO MediaVersion (media_id, version, prompt, summary, created_at)

        VALUES (?, ?, ?, ?, ?)

        ''', (media_id, current_version + 1, prompt, summary, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
    except DatabaseError as e:
        logging.error(f"Error adding media version: {e}")
        raise


# Function to search the database with advanced options, including keyword search and full-text search
def sqlite_search_db(search_query: str, search_fields: List[str], keywords: str, page: int = 1, results_per_page: int = 10):
    if page < 1:
        raise ValueError("Page number must be 1 or greater.")

    # Prepare keywords by splitting and trimming
    keywords = [keyword.strip().lower() for keyword in keywords.split(',') if keyword.strip()]

    with db.get_connection() as conn:
        cursor = conn.cursor()
        offset = (page - 1) * results_per_page

        # Prepare the search conditions for general fields
        search_conditions = []
        params = []

        for field in search_fields:
            if search_query:  # Ensure there's a search query before adding this condition
                search_conditions.append(f"Media.{field} LIKE ?")
                params.append(f'%{search_query}%')

        # Prepare the conditions for keywords filtering
        keyword_conditions = []
        for keyword in keywords:
            keyword_conditions.append(
                f"EXISTS (SELECT 1 FROM MediaKeywords mk JOIN Keywords k ON mk.keyword_id = k.id WHERE mk.media_id = Media.id AND k.keyword LIKE ?)")
            params.append(f'%{keyword}%')

        # Combine all conditions
        where_clause = " AND ".join(
            search_conditions + keyword_conditions) if search_conditions or keyword_conditions else "1=1"

        # Complete the query
        query = f'''

        SELECT DISTINCT Media.id, Media.url, Media.title, Media.type, Media.content, Media.author, Media.ingestion_date, 

               MediaModifications.prompt, MediaModifications.summary

        FROM Media

        LEFT JOIN MediaModifications ON Media.id = MediaModifications.media_id

        WHERE {where_clause}

        ORDER BY Media.ingestion_date DESC

        LIMIT ? OFFSET ?

        '''
        params.extend([results_per_page, offset])

        cursor.execute(query, params)
        results = cursor.fetchall()

        return results


# Gradio function to handle user input and display results with pagination, with better feedback
def search_and_display(search_query, search_fields, keywords, page):
    results = sqlite_search_db(search_query, search_fields, keywords, page)

    if isinstance(results, pd.DataFrame):
        # Convert DataFrame to a list of tuples or lists
        processed_results = results.values.tolist()  # This converts DataFrame rows to lists
    elif isinstance(results, list):
        # Ensure that each element in the list is itself a list or tuple (not a dictionary)
        processed_results = [list(item.values()) if isinstance(item, dict) else item for item in results]
    else:
        raise TypeError("Unsupported data type for results")

    return processed_results


def display_details(index, results):
    if index is None or results is None:
        return "Please select a result to view details."

    try:
        # Ensure the index is an integer and access the row properly
        index = int(index)
        if isinstance(results, pd.DataFrame):
            if index >= len(results):
                return "Index out of range. Please select a valid index."
            selected_row = results.iloc[index]
        else:
            # If results is not a DataFrame, but a list (assuming list of dicts)
            selected_row = results[index]
    except ValueError:
        return "Index must be an integer."
    except IndexError:
        return "Index out of range. Please select a valid index."

    # Build HTML output safely
    details_html = f"""

    <h3>{selected_row.get('Title', 'No Title')}</h3>

    <p><strong>URL:</strong> {selected_row.get('URL', 'No URL')}</p>

    <p><strong>Type:</strong> {selected_row.get('Type', 'No Type')}</p>

    <p><strong>Author:</strong> {selected_row.get('Author', 'No Author')}</p>

    <p><strong>Ingestion Date:</strong> {selected_row.get('Ingestion Date', 'No Date')}</p>

    <p><strong>Prompt:</strong> {selected_row.get('Prompt', 'No Prompt')}</p>

    <p><strong>Summary:</strong> {selected_row.get('Summary', 'No Summary')}</p>

    <p><strong>Content:</strong> {selected_row.get('Content', 'No Content')}</p>

    """
    return details_html


def get_details(index, dataframe):
    if index is None or dataframe is None or index >= len(dataframe):
        return "Please select a result to view details."
    row = dataframe.iloc[index]
    details = f"""

    <h3>{row['Title']}</h3>

    <p><strong>URL:</strong> {row['URL']}</p>

    <p><strong>Type:</strong> {row['Type']}</p>

    <p><strong>Author:</strong> {row['Author']}</p>

    <p><strong>Ingestion Date:</strong> {row['Ingestion Date']}</p>

    <p><strong>Prompt:</strong> {row['Prompt']}</p>

    <p><strong>Summary:</strong> {row['Summary']}</p>

    <p><strong>Content:</strong></p>

    <pre>{row['Content']}</pre>

    """
    return details


def format_results(results):
    if not results:
        return pd.DataFrame(columns=['URL', 'Title', 'Type', 'Content', 'Author', 'Ingestion Date', 'Prompt', 'Summary'])

    df = pd.DataFrame(results, columns=['URL', 'Title', 'Type', 'Content', 'Author', 'Ingestion Date', 'Prompt', 'Summary'])
    logging.debug(f"Formatted DataFrame: {df}")

    return df


# Function to export search results to CSV or markdown with pagination
def export_to_file(search_query: str, search_fields: List[str], keyword: str, page: int = 1, results_per_file: int = 1000, export_format: str = 'csv'):
    try:
        results = sqlite_search_db(search_query, search_fields, keyword, page, results_per_file)
        if not results:
            return "No results found to export."

        # Create an 'exports' directory if it doesn't exist
        if not os.path.exists('exports'):
            os.makedirs('exports')

        if export_format == 'csv':
            filename = f'exports/search_results_page_{page}.csv'
            with open(filename, 'w', newline='', encoding='utf-8') as file:
                writer = csv.writer(file)
                writer.writerow(['URL', 'Title', 'Type', 'Content', 'Author', 'Ingestion Date', 'Prompt', 'Summary'])
                for row in results:
                    writer.writerow(row)
        elif export_format == 'markdown':
            filename = f'exports/search_results_page_{page}.md'
            with open(filename, 'w', encoding='utf-8') as file:
                for item in results:
                    markdown_content = convert_to_markdown({
                        'title': item[1],
                        'url': item[0],
                        'type': item[2],
                        'content': item[3],
                        'author': item[4],
                        'ingestion_date': item[5],
                        'summary': item[7],
                        'keywords': item[8].split(',') if item[8] else []
                    })
                    file.write(markdown_content)
                    file.write("\n---\n\n")  # Separator between items
        else:
            return f"Unsupported export format: {export_format}"

        return f"Results exported to {filename}"
    except (DatabaseError, InputError) as e:
        return str(e)


# Helper function to validate date format
def is_valid_date(date_string: str) -> bool:
    try:
        datetime.strptime(date_string, '%Y-%m-%d')
        return True
    except ValueError:
        return False

def add_media_to_database(url, info_dict, segments, summary, keywords, custom_prompt_input, whisper_model, media_type='video'):
    db = Database()
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            # Extract content from segments
            if isinstance(segments, list):
                content = ' '.join([segment.get('Text', '') for segment in segments if 'Text' in segment])
            elif isinstance(segments, dict):
                content = segments.get('text', '') or segments.get('content', '')
            else:
                content = str(segments)

            # Process keywords
            if isinstance(keywords, str):
                keyword_list = [keyword.strip().lower() for keyword in keywords.split(',')]
            elif isinstance(keywords, (list, tuple)):
                keyword_list = [keyword.strip().lower() for keyword in keywords]
            else:
                keyword_list = ['default']

            # Check if media already exists
            cursor.execute('SELECT id FROM Media WHERE url = ?', (url,))
            existing_media = cursor.fetchone()

            if existing_media:
                media_id = existing_media[0]
                cursor.execute('''

                UPDATE Media 

                SET content = ?, transcription_model = ?, title = ?, type = ?, author = ?, ingestion_date = ?, chunking_status = ?

                WHERE id = ?

                ''', (content, whisper_model, info_dict.get('title', 'Untitled'), media_type,
                      info_dict.get('uploader', 'Unknown'), datetime.now().strftime('%Y-%m-%d'), 'pending', media_id))
            else:
                cursor.execute('''

                INSERT INTO Media (url, title, type, content, author, ingestion_date, transcription_model, chunking_status)

                VALUES (?, ?, ?, ?, ?, ?, ?, ?)

                ''', (url, info_dict.get('title', 'Untitled'), media_type, content,
                      info_dict.get('uploader', 'Unknown'), datetime.now().strftime('%Y-%m-%d'), whisper_model, 'pending'))
                media_id = cursor.lastrowid

            # Add modification
            cursor.execute('''

            INSERT INTO MediaModifications (media_id, prompt, summary, modification_date)

            VALUES (?, ?, ?, ?)

            ''', (media_id, custom_prompt_input, summary, datetime.now().strftime('%Y-%m-%d')))

            # Process keywords
            for keyword in keyword_list:
                cursor.execute('INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)', (keyword,))
                cursor.execute('SELECT id FROM Keywords WHERE keyword = ?', (keyword,))
                keyword_id = cursor.fetchone()[0]
                cursor.execute('INSERT OR IGNORE INTO MediaKeywords (media_id, keyword_id) VALUES (?, ?)',
                               (media_id, keyword_id))

            # Update full-text search index
            cursor.execute('INSERT OR REPLACE INTO media_fts (rowid, title, content) VALUES (?, ?, ?)',
                           (media_id, info_dict.get('title', 'Untitled'), content))

            # Add media version
            cursor.execute('SELECT MAX(version) FROM MediaVersion WHERE media_id = ?', (media_id,))
            current_version = cursor.fetchone()[0] or 0
            cursor.execute('''

            INSERT INTO MediaVersion (media_id, version, prompt, summary, created_at)

            VALUES (?, ?, ?, ?, ?)

            ''', (media_id, current_version + 1, custom_prompt_input, summary, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))

            conn.commit()

        # Schedule chunking
        schedule_chunking(media_id, content, info_dict.get('title', 'Untitled'))

        return f"Media '{info_dict.get('title', 'Untitled')}' added/updated successfully with keywords: {', '.join(keyword_list)}. Chunking scheduled."

    except DatabaseError as e:
        logging.error(f"Database error: {e}")
        raise
    except Exception as e:
        logging.error(f"Unexpected error: {e}")
        raise DatabaseError(f"Unexpected error: {e}")


# FIXME: This function is not complete and needs to be implemented
def schedule_chunking(media_id: int, content: str, media_name: str):
    try:
        chunks = chunk_text(content, chunk_options['method'], chunk_options['max_size'], chunk_options['overlap'])
        db = Database()
        with db.get_connection() as conn:
            cursor = conn.cursor()
            for i, chunk in enumerate(chunks):
                cursor.execute('''

                INSERT INTO MediaChunks (media_id, chunk_text, start_index, end_index, chunk_id)

                VALUES (?, ?, ?, ?, ?)

                ''', (media_id, chunk, i * chunk_options['max_size'],
                      min((i + 1) * chunk_options['max_size'], len(content)),
                      f"{media_id}_chunk_{i}"))
            conn.commit()

        # Update chunking status
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("UPDATE Media SET chunking_status = 'completed' WHERE id = ?", (media_id,))
            conn.commit()

    except Exception as e:
        logging.error(f"Error scheduling chunking for media_id {media_id}: {str(e)}")
        # You might want to update the chunking_status to 'failed' here

#
# End of ....
#######################################################################################################################


#######################################################################################################################
#
# Functions to manage prompts DB

def create_prompts_db():
    with sqlite3.connect(get_database_path('prompts.db')) as conn:
        cursor = conn.cursor()
        cursor.executescript('''

            CREATE TABLE IF NOT EXISTS Prompts (

                id INTEGER PRIMARY KEY AUTOINCREMENT,

                name TEXT NOT NULL UNIQUE,

                details TEXT,

                system TEXT,

                user TEXT

            );

            CREATE TABLE IF NOT EXISTS Keywords (

                id INTEGER PRIMARY KEY AUTOINCREMENT,

                keyword TEXT NOT NULL UNIQUE COLLATE NOCASE

            );

            CREATE TABLE IF NOT EXISTS PromptKeywords (

                prompt_id INTEGER,

                keyword_id INTEGER,

                FOREIGN KEY (prompt_id) REFERENCES Prompts (id),

                FOREIGN KEY (keyword_id) REFERENCES Keywords (id),

                PRIMARY KEY (prompt_id, keyword_id)

            );

            CREATE INDEX IF NOT EXISTS idx_keywords_keyword ON Keywords(keyword);

            CREATE INDEX IF NOT EXISTS idx_promptkeywords_prompt_id ON PromptKeywords(prompt_id);

            CREATE INDEX IF NOT EXISTS idx_promptkeywords_keyword_id ON PromptKeywords(keyword_id);

        ''')


def normalize_keyword(keyword):
    return re.sub(r'\s+', ' ', keyword.strip().lower())


def add_prompt(name, details, system, user=None, keywords=None):
    if not name or not system:
        return "Name and system prompt are required."

    try:
        with sqlite3.connect(get_database_path('prompts.db')) as conn:
            cursor = conn.cursor()
            cursor.execute('''

                INSERT INTO Prompts (name, details, system, user)

                VALUES (?, ?, ?, ?)

            ''', (name, details, system, user))
            prompt_id = cursor.lastrowid

            if keywords:
                normalized_keywords = [normalize_keyword(k) for k in keywords if k.strip()]
                for keyword in set(normalized_keywords):  # Use set to remove duplicates
                    cursor.execute('''

                        INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)

                    ''', (keyword,))
                    cursor.execute('SELECT id FROM Keywords WHERE keyword = ?', (keyword,))
                    keyword_id = cursor.fetchone()[0]
                    cursor.execute('''

                        INSERT OR IGNORE INTO PromptKeywords (prompt_id, keyword_id) VALUES (?, ?)

                    ''', (prompt_id, keyword_id))
        return "Prompt added successfully."
    except sqlite3.IntegrityError:
        return "Prompt with this name already exists."
    except sqlite3.Error as e:
        return f"Database error: {e}"


def fetch_prompt_details(name):
    with sqlite3.connect(get_database_path('prompts.db')) as conn:
        cursor = conn.cursor()
        cursor.execute('''

            SELECT p.name, p.details, p.system, p.user, GROUP_CONCAT(k.keyword, ', ') as keywords

            FROM Prompts p

            LEFT JOIN PromptKeywords pk ON p.id = pk.prompt_id

            LEFT JOIN Keywords k ON pk.keyword_id = k.id

            WHERE p.name = ?

            GROUP BY p.id

        ''', (name,))
        return cursor.fetchone()


def list_prompts(page=1, per_page=10):
    offset = (page - 1) * per_page
    with sqlite3.connect(get_database_path('prompts.db')) as conn:
        cursor = conn.cursor()
        cursor.execute('SELECT name FROM Prompts LIMIT ? OFFSET ?', (per_page, offset))
        prompts = [row[0] for row in cursor.fetchall()]

        # Get total count of prompts
        cursor.execute('SELECT COUNT(*) FROM Prompts')
        total_count = cursor.fetchone()[0]

    total_pages = (total_count + per_page - 1) // per_page
    return prompts, total_pages, page

# This will not scale. For a large number of prompts, use a more efficient method.
# FIXME - see above statement.
def load_preset_prompts():
    try:
        with sqlite3.connect(get_database_path('prompts.db')) as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT name FROM Prompts ORDER BY name ASC')
            prompts = [row[0] for row in cursor.fetchall()]
        return prompts
    except sqlite3.Error as e:
        print(f"Database error: {e}")
        return []


def insert_prompt_to_db(title, description, system_prompt, user_prompt, keywords=None):
    return add_prompt(title, description, system_prompt, user_prompt, keywords)


def get_prompt_db_connection():
    prompt_db_path = get_database_path('prompts.db')
    return sqlite3.connect(prompt_db_path)


def search_prompts(query):
    try:
        with get_prompt_db_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""

                SELECT p.name, p.details, p.system, p.user, GROUP_CONCAT(k.keyword, ', ') as keywords

                FROM Prompts p

                LEFT JOIN PromptKeywords pk ON p.id = pk.prompt_id

                LEFT JOIN Keywords k ON pk.keyword_id = k.id

                WHERE p.name LIKE ? OR p.details LIKE ? OR p.system LIKE ? OR p.user LIKE ? OR k.keyword LIKE ?

                GROUP BY p.id

                ORDER BY p.name

            """, (f'%{query}%', f'%{query}%', f'%{query}%', f'%{query}%', f'%{query}%'))
            return cursor.fetchall()
    except sqlite3.Error as e:
        logging.error(f"Error searching prompts: {e}")
        return []


def search_prompts_by_keyword(keyword, page=1, per_page=10):
    normalized_keyword = normalize_keyword(keyword)
    offset = (page - 1) * per_page
    with sqlite3.connect(get_database_path('prompts.db')) as conn:
        cursor = conn.cursor()
        cursor.execute('''

            SELECT DISTINCT p.name

            FROM Prompts p

            JOIN PromptKeywords pk ON p.id = pk.prompt_id

            JOIN Keywords k ON pk.keyword_id = k.id

            WHERE k.keyword LIKE ?

            LIMIT ? OFFSET ?

        ''', ('%' + normalized_keyword + '%', per_page, offset))
        prompts = [row[0] for row in cursor.fetchall()]

        # Get total count of matching prompts
        cursor.execute('''

            SELECT COUNT(DISTINCT p.id)

            FROM Prompts p

            JOIN PromptKeywords pk ON p.id = pk.prompt_id

            JOIN Keywords k ON pk.keyword_id = k.id

            WHERE k.keyword LIKE ?

        ''', ('%' + normalized_keyword + '%',))
        total_count = cursor.fetchone()[0]

    total_pages = (total_count + per_page - 1) // per_page
    return prompts, total_pages, page


def update_prompt_keywords(prompt_name, new_keywords):
    try:
        with sqlite3.connect(get_database_path('prompts.db')) as conn:
            cursor = conn.cursor()

            cursor.execute('SELECT id FROM Prompts WHERE name = ?', (prompt_name,))
            prompt_id = cursor.fetchone()
            if not prompt_id:
                return "Prompt not found."
            prompt_id = prompt_id[0]

            cursor.execute('DELETE FROM PromptKeywords WHERE prompt_id = ?', (prompt_id,))

            normalized_keywords = [normalize_keyword(k) for k in new_keywords if k.strip()]
            for keyword in set(normalized_keywords):  # Use set to remove duplicates
                cursor.execute('INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)', (keyword,))
                cursor.execute('SELECT id FROM Keywords WHERE keyword = ?', (keyword,))
                keyword_id = cursor.fetchone()[0]
                cursor.execute('INSERT INTO PromptKeywords (prompt_id, keyword_id) VALUES (?, ?)',
                               (prompt_id, keyword_id))

            # Remove unused keywords
            cursor.execute('''

                DELETE FROM Keywords

                WHERE id NOT IN (SELECT DISTINCT keyword_id FROM PromptKeywords)

            ''')
        return "Keywords updated successfully."
    except sqlite3.Error as e:
        return f"Database error: {e}"


def add_or_update_prompt(title, description, system_prompt, user_prompt, keywords=None):
    if not title:
        return "Error: Title is required."

    existing_prompt = fetch_prompt_details(title)
    if existing_prompt:
        # Update existing prompt
        result = update_prompt_in_db(title, description, system_prompt, user_prompt)
        if "successfully" in result:
            # Update keywords if the prompt update was successful
            keyword_result = update_prompt_keywords(title, keywords or [])
            result += f" {keyword_result}"
    else:
        # Insert new prompt
        result = insert_prompt_to_db(title, description, system_prompt, user_prompt, keywords)

    return result


def load_prompt_details(selected_prompt):
    if selected_prompt:
        details = fetch_prompt_details(selected_prompt)
        if details:
            return details[0], details[1], details[2], details[3], details[4]  # Include keywords
    return "", "", "", "", ""


def update_prompt_in_db(title, description, system_prompt, user_prompt):
    try:
        with sqlite3.connect(get_database_path('prompts.db')) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "UPDATE Prompts SET details = ?, system = ?, user = ? WHERE name = ?",
                (description, system_prompt, user_prompt, title)
            )
            if cursor.rowcount == 0:
                return "No prompt found with the given title."
        return "Prompt updated successfully!"
    except sqlite3.Error as e:
        return f"Error updating prompt: {e}"


create_prompts_db()

def delete_prompt(prompt_id):
    try:
        with sqlite3.connect(get_database_path('prompts.db')) as conn:
            cursor = conn.cursor()

            # Delete associated keywords
            cursor.execute("DELETE FROM PromptKeywords WHERE prompt_id = ?", (prompt_id,))

            # Delete the prompt
            cursor.execute("DELETE FROM Prompts WHERE id = ?", (prompt_id,))

            if cursor.rowcount == 0:
                return f"No prompt found with ID {prompt_id}"
            else:
                conn.commit()
                return f"Prompt with ID {prompt_id} has been successfully deleted"
    except sqlite3.Error as e:
        return f"An error occurred: {e}"

#
#
#######################################################################################################################


#######################################################################################################################
#
# Function to fetch/update media content

def update_media_content(selected_item, item_mapping, content_input, prompt_input, summary_input):
    try:
        if selected_item and item_mapping and selected_item in item_mapping:
            media_id = item_mapping[selected_item]

            with db.get_connection() as conn:
                cursor = conn.cursor()

                # Update the main content in the Media table
                cursor.execute("UPDATE Media SET content = ? WHERE id = ?", (content_input, media_id))

                # Check if a row already exists in MediaModifications for this media_id
                cursor.execute("SELECT COUNT(*) FROM MediaModifications WHERE media_id = ?", (media_id,))
                exists = cursor.fetchone()[0] > 0

                if exists:
                    # Update existing row
                    cursor.execute("""

                        UPDATE MediaModifications

                        SET prompt = ?, summary = ?, modification_date = CURRENT_TIMESTAMP

                        WHERE media_id = ?

                    """, (prompt_input, summary_input, media_id))
                else:
                    # Insert new row
                    cursor.execute("""

                        INSERT INTO MediaModifications (media_id, prompt, summary, modification_date)

                        VALUES (?, ?, ?, CURRENT_TIMESTAMP)

                    """, (media_id, prompt_input, summary_input))

                # Create new document version
                new_version = create_document_version(media_id, content_input)

                conn.commit()

            return f"Content updated successfully for media ID: {media_id}. New version: {new_version}"
        else:
            return "No item selected or invalid selection"
    except Exception as e:
        logging.error(f"Error updating media content: {e}")
        return f"Error updating content: {str(e)}"


def search_media_database(query: str) -> List[Tuple[int, str, str]]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT id, title, url FROM Media WHERE title LIKE ?", (f'%{query}%',))
            results = cursor.fetchall()
        return results
    except sqlite3.Error as e:
        raise Exception(f"Error searching media database: {e}")

def load_media_content(media_id: int) -> dict:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT content, prompt, summary FROM Media WHERE id = ?", (media_id,))
            result = cursor.fetchone()
            if result:
                return {
                    "content": result[0],
                    "prompt": result[1],
                    "summary": result[2]
                }
            return {"content": "", "prompt": "", "summary": ""}
    except sqlite3.Error as e:
        raise Exception(f"Error loading media content: {e}")


def fetch_items_by_title_or_url(search_query: str, search_type: str):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            if search_type == 'Title':
                cursor.execute("SELECT id, title, url FROM Media WHERE title LIKE ?", (f'%{search_query}%',))
            elif search_type == 'URL':
                cursor.execute("SELECT id, title, url FROM Media WHERE url LIKE ?", (f'%{search_query}%',))
            results = cursor.fetchall()
            return results
    except sqlite3.Error as e:
        raise DatabaseError(f"Error fetching items by {search_type}: {e}")


def fetch_items_by_keyword(search_query: str):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""

                SELECT m.id, m.title, m.url

                FROM Media m

                JOIN MediaKeywords mk ON m.id = mk.media_id

                JOIN Keywords k ON mk.keyword_id = k.id

                WHERE k.keyword LIKE ?

            """, (f'%{search_query}%',))
            results = cursor.fetchall()
            return results
    except sqlite3.Error as e:
        raise DatabaseError(f"Error fetching items by keyword: {e}")


def fetch_items_by_content(search_query: str):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT id, title, url FROM Media WHERE content LIKE ?", (f'%{search_query}%',))
            results = cursor.fetchall()
            return results
    except sqlite3.Error as e:
        raise DatabaseError(f"Error fetching items by content: {e}")


def fetch_item_details_single(media_id: int):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""

                SELECT prompt, summary 

                FROM MediaModifications 

                WHERE media_id = ? 

                ORDER BY modification_date DESC 

                LIMIT 1

            """, (media_id,))
            prompt_summary_result = cursor.fetchone()
            cursor.execute("SELECT content FROM Media WHERE id = ?", (media_id,))
            content_result = cursor.fetchone()

            prompt = prompt_summary_result[0] if prompt_summary_result else ""
            summary = prompt_summary_result[1] if prompt_summary_result else ""
            content = content_result[0] if content_result else ""

            return prompt, summary, content
    except sqlite3.Error as e:
        raise Exception(f"Error fetching item details: {e}")



def convert_to_markdown(item):
    markdown = f"# {item['title']}\n\n"
    markdown += f"**URL:** {item['url']}\n\n"
    markdown += f"**Author:** {item['author']}\n\n"
    markdown += f"**Ingestion Date:** {item['ingestion_date']}\n\n"
    markdown += f"**Type:** {item['type']}\n\n"
    markdown += f"**Keywords:** {', '.join(item['keywords'])}\n\n"
    markdown += "## Summary\n\n"
    markdown += f"{item['summary']}\n\n"
    markdown += "## Content\n\n"
    markdown += f"{item['content']}\n\n"
    return markdown

# Gradio function to handle user input and display results with pagination for displaying entries in the DB
def fetch_paginated_data(page: int, results_per_page: int) -> Tuple[List[Tuple], int]:
    try:
        offset = (page - 1) * results_per_page
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT COUNT(*) FROM Media")
            total_entries = cursor.fetchone()[0]

            cursor.execute("SELECT id, title, url FROM Media LIMIT ? OFFSET ?", (results_per_page, offset))
            results = cursor.fetchall()

        return results, total_entries
    except sqlite3.Error as e:
        raise Exception(f"Error fetching paginated data: {e}")

def format_results_as_html(results: List[Tuple]) -> str:
    html = "<table class='table table-striped'>"
    html += "<tr><th>ID</th><th>Title</th><th>URL</th></tr>"
    for row in results:
        html += f"<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td></tr>"
    html += "</table>"
    return html

def view_database(page: int, results_per_page: int) -> Tuple[str, str, int]:
    results, total_entries = fetch_paginated_data(page, results_per_page)
    formatted_results = format_results_as_html(results)
    # Calculate total pages
    total_pages = (total_entries + results_per_page - 1) // results_per_page
    return formatted_results, f"Page {page} of {total_pages}", total_pages


def search_and_display_items(query, search_type, page, entries_per_page,char_count):
    offset = (page - 1) * entries_per_page
    try:
        with sqlite3.connect('./Databases/media_summary.db') as conn:
            cursor = conn.cursor()

            # Adjust the SQL query based on the search type
            if search_type == "Title":
                where_clause = "WHERE m.title LIKE ?"
            elif search_type == "URL":
                where_clause = "WHERE m.url LIKE ?"
            elif search_type == "Keyword":
                where_clause = "WHERE k.keyword LIKE ?"
            elif search_type == "Content":
                where_clause = "WHERE m.content LIKE ?"
            else:
                raise ValueError("Invalid search type")

            cursor.execute(f'''

                SELECT m.id, m.title, m.url, m.content, mm.summary, GROUP_CONCAT(k.keyword, ', ') as keywords

                FROM Media m

                LEFT JOIN MediaModifications mm ON m.id = mm.media_id

                LEFT JOIN MediaKeywords mk ON m.id = mk.media_id

                LEFT JOIN Keywords k ON mk.keyword_id = k.id

                {where_clause}

                GROUP BY m.id

                ORDER BY m.ingestion_date DESC

                LIMIT ? OFFSET ?

            ''', (f'%{query}%', entries_per_page, offset))
            items = cursor.fetchall()

            cursor.execute(f'''

                SELECT COUNT(DISTINCT m.id)

                FROM Media m

                LEFT JOIN MediaKeywords mk ON m.id = mk.media_id

                LEFT JOIN Keywords k ON mk.keyword_id = k.id

                {where_clause}

            ''', (f'%{query}%',))
            total_items = cursor.fetchone()[0]

        results = ""
        for item in items:
            title = html.escape(item[1]).replace('\n', '<br>')
            url = html.escape(item[2]).replace('\n', '<br>')
            # First X amount of characters of the content
            content = html.escape(item[3] or '')[:char_count] + '...'
            summary = html.escape(item[4] or '').replace('\n', '<br>')
            keywords = html.escape(item[5] or '').replace('\n', '<br>')

            results += f"""

            <div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 20px;">

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">

                    <div><strong>Title:</strong> {title}</div>

                    <div><strong>URL:</strong> {url}</div>

                </div>

                <div style="margin-top: 10px;">

                    <strong>Content (first {char_count} characters):</strong>

                    <pre style="white-space: pre-wrap; word-wrap: break-word;">{content}</pre>

                </div>

                <div style="margin-top: 10px;">

                    <strong>Summary:</strong>

                    <pre style="white-space: pre-wrap; word-wrap: break-word;">{summary}</pre>

                </div>

                <div style="margin-top: 10px;">

                    <strong>Keywords:</strong> {keywords}

                </div>

            </div>

            """

        total_pages = (total_items + entries_per_page - 1) // entries_per_page
        pagination = f"Page {page} of {total_pages} (Total items: {total_items})"

        return results, pagination, total_pages
    except sqlite3.Error as e:
        return f"<p>Error searching items: {e}</p>", "Error", 0


#
# End of Functions to manage prompts DB / Fetch and update media content
#######################################################################################################################


#######################################################################################################################
#
# Obsidian-related Functions

def import_obsidian_note_to_db(note_data):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            cursor.execute("SELECT id FROM Media WHERE title = ? AND type = 'obsidian_note'", (note_data['title'],))
            existing_note = cursor.fetchone()

            # Generate a relative path or meaningful identifier instead of using the temporary file path
            relative_path = os.path.relpath(note_data['file_path'], start=os.path.dirname(note_data['file_path']))

            if existing_note:
                media_id = existing_note[0]
                cursor.execute("""

                    UPDATE Media

                    SET content = ?, author = ?, ingestion_date = CURRENT_TIMESTAMP, url = ?

                    WHERE id = ?

                """, (note_data['content'], note_data['frontmatter'].get('author', 'Unknown'), relative_path, media_id))

                cursor.execute("DELETE FROM MediaKeywords WHERE media_id = ?", (media_id,))
            else:
                cursor.execute("""

                    INSERT INTO Media (title, content, type, author, ingestion_date, url)

                    VALUES (?, ?, 'obsidian_note', ?, CURRENT_TIMESTAMP, ?)

                """, (note_data['title'], note_data['content'], note_data['frontmatter'].get('author', 'Unknown'),
                      relative_path))

                media_id = cursor.lastrowid

            for tag in note_data['tags']:
                cursor.execute("INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)", (tag,))
                cursor.execute("SELECT id FROM Keywords WHERE keyword = ?", (tag,))
                keyword_id = cursor.fetchone()[0]
                cursor.execute("INSERT OR IGNORE INTO MediaKeywords (media_id, keyword_id) VALUES (?, ?)",
                               (media_id, keyword_id))

            frontmatter_str = yaml.dump(note_data['frontmatter'])
            cursor.execute("""

                INSERT INTO MediaModifications (media_id, prompt, summary, modification_date)

                VALUES (?, 'Obsidian Frontmatter', ?, CURRENT_TIMESTAMP)

            """, (media_id, frontmatter_str))

            # Update full-text search index
            cursor.execute('INSERT OR REPLACE INTO media_fts (rowid, title, content) VALUES (?, ?, ?)',
                           (media_id, note_data['title'], note_data['content']))

        action = "Updated" if existing_note else "Imported"
        logger.info(f"{action} Obsidian note: {note_data['title']}")
        return True, None
    except sqlite3.Error as e:
        error_msg = f"Database error {'updating' if existing_note else 'importing'} note {note_data['title']}: {str(e)}"
        logger.error(error_msg)
        return False, error_msg
    except Exception as e:
        error_msg = f"Unexpected error {'updating' if existing_note else 'importing'} note {note_data['title']}: {str(e)}\n{traceback.format_exc()}"
        logger.error(error_msg)
        return False, error_msg


#
# End of Obsidian-related Functions
#######################################################################################################################


#######################################################################################################################
#
# Chat-related Functions



def create_chat_conversation(media_id, conversation_name):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

                INSERT INTO ChatConversations (media_id, conversation_name, created_at, updated_at)

                VALUES (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

            ''', (media_id, conversation_name))
            conn.commit()
            return cursor.lastrowid
    except sqlite3.Error as e:
        logging.error(f"Error creating chat conversation: {e}")
        raise DatabaseError(f"Error creating chat conversation: {e}")


def add_chat_message(conversation_id: int, sender: str, message: str) -> int:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

                INSERT INTO ChatMessages (conversation_id, sender, message)

                VALUES (?, ?, ?)

            ''', (conversation_id, sender, message))
            conn.commit()
            return cursor.lastrowid
    except sqlite3.Error as e:
        logging.error(f"Error adding chat message: {e}")
        raise DatabaseError(f"Error adding chat message: {e}")


def get_chat_messages(conversation_id: int) -> List[Dict[str, Any]]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

                SELECT id, sender, message, timestamp

                FROM ChatMessages

                WHERE conversation_id = ?

                ORDER BY timestamp ASC

            ''', (conversation_id,))
            messages = cursor.fetchall()
            return [
                {
                    'id': msg[0],
                    'sender': msg[1],
                    'message': msg[2],
                    'timestamp': msg[3]
                }
                for msg in messages
            ]
    except sqlite3.Error as e:
        logging.error(f"Error retrieving chat messages: {e}")
        raise DatabaseError(f"Error retrieving chat messages: {e}")


def search_chat_conversations(search_query: str) -> List[Dict[str, Any]]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

                SELECT cc.id, cc.media_id, cc.conversation_name, cc.created_at, m.title as media_title

                FROM ChatConversations cc

                LEFT JOIN Media m ON cc.media_id = m.id

                WHERE cc.conversation_name LIKE ? OR m.title LIKE ?

                ORDER BY cc.updated_at DESC

            ''', (f'%{search_query}%', f'%{search_query}%'))
            conversations = cursor.fetchall()
            return [
                {
                    'id': conv[0],
                    'media_id': conv[1],
                    'conversation_name': conv[2],
                    'created_at': conv[3],
                    'media_title': conv[4] or "Unknown Media"
                }
                for conv in conversations
            ]
    except sqlite3.Error as e:
        logging.error(f"Error searching chat conversations: {e}")
        return []


def update_chat_message(message_id: int, new_message: str) -> None:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

                UPDATE ChatMessages

                SET message = ?, timestamp = CURRENT_TIMESTAMP

                WHERE id = ?

            ''', (new_message, message_id))
            conn.commit()
    except sqlite3.Error as e:
        logging.error(f"Error updating chat message: {e}")
        raise DatabaseError(f"Error updating chat message: {e}")


def delete_chat_message(message_id: int) -> None:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('DELETE FROM ChatMessages WHERE id = ?', (message_id,))
            conn.commit()
    except sqlite3.Error as e:
        logging.error(f"Error deleting chat message: {e}")
        raise DatabaseError(f"Error deleting chat message: {e}")


def save_chat_history_to_database(chatbot, conversation_id, media_id, media_name, conversation_name):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            # If conversation_id is None, create a new conversation
            if conversation_id is None:
                cursor.execute('''

                    INSERT INTO ChatConversations (media_id, media_name, conversation_name, created_at, updated_at)

                    VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

                ''', (media_id, media_name, conversation_name))
                conversation_id = cursor.lastrowid
            else:
                # If conversation exists, update the media_name
                cursor.execute('''

                    UPDATE ChatConversations

                    SET media_name = ?, updated_at = CURRENT_TIMESTAMP

                    WHERE id = ?

                ''', (media_name, conversation_id))

            # Save each message in the chatbot history
            for i, (user_msg, ai_msg) in enumerate(chatbot):
                cursor.execute('''

                    INSERT INTO ChatMessages (conversation_id, sender, message, timestamp)

                    VALUES (?, ?, ?, CURRENT_TIMESTAMP)

                ''', (conversation_id, 'user', user_msg))

                cursor.execute('''

                    INSERT INTO ChatMessages (conversation_id, sender, message, timestamp)

                    VALUES (?, ?, ?, CURRENT_TIMESTAMP)

                ''', (conversation_id, 'ai', ai_msg))

            # Update the conversation's updated_at timestamp
            cursor.execute('''

                UPDATE ChatConversations

                SET updated_at = CURRENT_TIMESTAMP

                WHERE id = ?

            ''', (conversation_id,))

            conn.commit()

        return conversation_id
    except Exception as e:
        logging.error(f"Error saving chat history to database: {str(e)}")
        raise


def get_conversation_name(conversation_id):
    if conversation_id is None:
        return None

    try:
        with sqlite3.connect('media_summary.db') as conn:  # Replace with your actual database name
            cursor = conn.cursor()

            query = """

            SELECT conversation_name, media_name

            FROM ChatConversations

            WHERE id = ?

            """

            cursor.execute(query, (conversation_id,))
            result = cursor.fetchone()

            if result:
                conversation_name, media_name = result
                if conversation_name:
                    return conversation_name
                elif media_name:
                    return f"{media_name}-chat"

            return None  # Return None if no result found
    except sqlite3.Error as e:
        logging.error(f"Database error in get_conversation_name: {e}")
        return None
    except Exception as e:
        logging.error(f"Unexpected error in get_conversation_name: {e}")
        return None

#
# End of Chat-related Functions
#######################################################################################################################


#######################################################################################################################
#
# Functions to Compare Transcripts

# Fetch Transcripts
def get_transcripts(media_id):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, whisper_model, transcription, created_at

            FROM Transcripts

            WHERE media_id = ?

            ORDER BY created_at DESC

            ''', (media_id,))
            return cursor.fetchall()
    except Exception as e:
        logging.error(f"Error in get_transcripts: {str(e)}")
        return []


#
# End of Functions to Compare Transcripts
#######################################################################################################################


#######################################################################################################################
#
# Functions to handle deletion of media items


def mark_as_trash(media_id: int) -> None:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("""

            UPDATE Media 

            SET is_trash = 1, trash_date = ?

            WHERE id = ?

        """, (datetime.now(), media_id))
        conn.commit()


def restore_from_trash(media_id: int) -> None:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("""

            UPDATE Media 

            SET is_trash = 0, trash_date = NULL

            WHERE id = ?

        """, (media_id,))
        conn.commit()


def get_trashed_items() -> List[Dict]:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("""

            SELECT id, title, trash_date 

            FROM Media 

            WHERE is_trash = 1

            ORDER BY trash_date DESC

        """)
        return [{'id': row[0], 'title': row[1], 'trash_date': row[2]} for row in cursor.fetchall()]


def permanently_delete_item(media_id: int) -> None:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("DELETE FROM Media WHERE id = ?", (media_id,))
        cursor.execute("DELETE FROM MediaKeywords WHERE media_id = ?", (media_id,))
        cursor.execute("DELETE FROM MediaVersion WHERE media_id = ?", (media_id,))
        cursor.execute("DELETE FROM MediaModifications WHERE media_id = ?", (media_id,))
        cursor.execute("DELETE FROM media_fts WHERE rowid = ?", (media_id,))
        conn.commit()


def empty_trash(days_threshold: int) -> Tuple[int, int]:
    threshold_date = datetime.now() - timedelta(days=days_threshold)
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("""

            SELECT id FROM Media 

            WHERE is_trash = 1 AND trash_date <= ?

        """, (threshold_date,))
        old_items = cursor.fetchall()

        for item in old_items:
            permanently_delete_item(item[0])

        cursor.execute("""

            SELECT COUNT(*) FROM Media 

            WHERE is_trash = 1 AND trash_date > ?

        """, (threshold_date,))
        remaining_items = cursor.fetchone()[0]

    return len(old_items), remaining_items


def user_delete_item(media_id: int, force: bool = False) -> str:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT is_trash, trash_date FROM Media WHERE id = ?", (media_id,))
        result = cursor.fetchone()

        if not result:
            return "Item not found."

        is_trash, trash_date = result

        if not is_trash:
            mark_as_trash(media_id)
            return "Item moved to trash."

        if force or (trash_date and (datetime.now() - trash_date).days >= 30):
            permanently_delete_item(media_id)
            return "Item permanently deleted."
        else:
            return "Item is already in trash. Use force=True to delete permanently before 30 days."


def get_chunk_text(media_id: int, chunk_index: int) -> str:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT content FROM MediaChunks WHERE media_id = ? AND chunk_index = ?",
                       (media_id, chunk_index))
        result = cursor.fetchone()
    return result[0] if result else None

def get_full_document(media_id: int) -> str:
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT content FROM Media WHERE id = ?", (media_id,))
        result = cursor.fetchone()
    return result[0] if result else None

def get_all_content_from_database() -> List[Dict[str, Any]]:
    """

    Retrieve all media content from the database that requires embedding.



    Returns:

        List[Dict[str, Any]]: A list of dictionaries, each containing the media ID, content, title, and other relevant fields.

    """
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""

                SELECT id, content, title, author, type

                FROM Media

                WHERE is_trash = 0  -- Exclude items marked as trash

            """)
            media_items = cursor.fetchall()

            all_content = [
                {
                    'id': item[0],
                    'content': item[1],
                    'title': item[2],
                    'author': item[3],
                    'type': item[4]
                }
                for item in media_items
            ]

        return all_content

    except sqlite3.Error as e:
        logger.error(f"Error retrieving all content from database: {e}")
        raise DatabaseError(f"Error retrieving all content from database: {e}")


def get_media_content(media_id: int) -> str:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT content FROM Media WHERE id = ?", (media_id,))
            result = cursor.fetchone()
            if result is None:
                raise ValueError(f"No media found with id {media_id}")
            return result[0]
    except sqlite3.Error as e:
        logging.error(f"Database error in get_media_content: {e}")
        raise DatabaseError(f"Failed to retrieve media content: {e}")
    except Exception as e:
        logging.error(f"Unexpected error in get_media_content: {e}")
        raise

def get_media_title(media_id: int) -> str:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT title FROM Media WHERE id = ?", (media_id,))
            result = cursor.fetchone()
            return result[0] if result else f"Unknown Source (ID: {media_id})"
    except sqlite3.Error as e:
        logging.error(f"Database error in get_media_title: {e}")
        return f"Unknown Source (ID: {media_id})"

def get_media_transcripts(media_id):
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, whisper_model, transcription, created_at

            FROM Transcripts

            WHERE media_id = ?

            ORDER BY created_at DESC

            ''', (media_id,))
            results = cursor.fetchall()
            return [
                {
                    'id': row[0],
                    'whisper_model': row[1],
                    'content': row[2],
                    'created_at': row[3]
                }
                for row in results
            ]
    except Exception as e:
        logging.error(f"Error in get_media_transcripts: {str(e)}")
        return []

def get_specific_transcript(transcript_id: int) -> Dict:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, whisper_model, transcription, created_at

            FROM Transcripts

            WHERE id = ?

            ''', (transcript_id,))
            result = cursor.fetchone()
            if result:
                return {
                    'id': result[0],
                    'whisper_model': result[1],
                    'content': result[2],
                    'created_at': result[3]
                }
            return {'error': f"No transcript found with ID {transcript_id}"}
    except Exception as e:
        logging.error(f"Error in get_specific_transcript: {str(e)}")
        return {'error': f"Error retrieving transcript: {str(e)}"}

def get_media_summaries(media_id: int) -> List[Dict]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, summary, modification_date

            FROM MediaModifications

            WHERE media_id = ? AND summary IS NOT NULL

            ORDER BY modification_date DESC

            ''', (media_id,))
            results = cursor.fetchall()
            return [
                {
                    'id': row[0],
                    'content': row[1],
                    'created_at': row[2]
                }
                for row in results
            ]
    except Exception as e:
        logging.error(f"Error in get_media_summaries: {str(e)}")

def get_specific_summary(summary_id: int) -> Dict:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, summary, modification_date

            FROM MediaModifications

            WHERE id = ?

            ''', (summary_id,))
            result = cursor.fetchone()
            if result:
                return {
                    'id': result[0],
                    'content': result[1],
                    'created_at': result[2]
                }
            return {'error': f"No summary found with ID {summary_id}"}
    except Exception as e:
        logging.error(f"Error in get_specific_summary: {str(e)}")
        return {'error': f"Error retrieving summary: {str(e)}"}

def get_media_prompts(media_id: int) -> List[Dict]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, prompt, modification_date

            FROM MediaModifications

            WHERE media_id = ? AND prompt IS NOT NULL

            ORDER BY modification_date DESC

            ''', (media_id,))
            results = cursor.fetchall()
            return [
                {
                    'id': row[0],
                    'content': row[1],
                    'created_at': row[2]
                }
                for row in results
            ]
    except Exception as e:
        logging.error(f"Error in get_media_prompts: {str(e)}")
        return []

def get_specific_prompt(prompt_id: int) -> Dict:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''

            SELECT id, prompt, modification_date

            FROM MediaModifications

            WHERE id = ?

            ''', (prompt_id,))
            result = cursor.fetchone()
            if result:
                return {
                    'id': result[0],
                    'content': result[1],
                    'created_at': result[2]
                }
            return {'error': f"No prompt found with ID {prompt_id}"}
    except Exception as e:
        logging.error(f"Error in get_specific_prompt: {str(e)}")
        return {'error': f"Error retrieving prompt: {str(e)}"}


def delete_specific_transcript(transcript_id: int) -> str:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('DELETE FROM Transcripts WHERE id = ?', (transcript_id,))
            conn.commit()
            if cursor.rowcount > 0:
                return f"Transcript with ID {transcript_id} has been deleted successfully."
            else:
                return f"No transcript found with ID {transcript_id}."
    except Exception as e:
        logging.error(f"Error in delete_specific_transcript: {str(e)}")
        return f"Error deleting transcript: {str(e)}"

def delete_specific_summary(summary_id: int) -> str:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('UPDATE MediaModifications SET summary = NULL WHERE id = ?', (summary_id,))
            conn.commit()
            if cursor.rowcount > 0:
                return f"Summary with ID {summary_id} has been deleted successfully."
            else:
                return f"No summary found with ID {summary_id}."
    except Exception as e:
        logging.error(f"Error in delete_specific_summary: {str(e)}")
        return f"Error deleting summary: {str(e)}"

def delete_specific_prompt(prompt_id: int) -> str:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('UPDATE MediaModifications SET prompt = NULL WHERE id = ?', (prompt_id,))
            conn.commit()
            if cursor.rowcount > 0:
                return f"Prompt with ID {prompt_id} has been deleted successfully."
            else:
                return f"No prompt found with ID {prompt_id}."
    except Exception as e:
        logging.error(f"Error in delete_specific_prompt: {str(e)}")
        return f"Error deleting prompt: {str(e)}"


def get_paginated_files(page: int = 1, results_per_page: int = 50) -> Tuple[List[Tuple[int, str]], int, int]:
    try:
        offset = (page - 1) * results_per_page
        with db.get_connection() as conn:
            cursor = conn.cursor()

            # Get total count of media items
            cursor.execute("SELECT COUNT(*) FROM Media")
            total_entries = cursor.fetchone()[0]

            # Fetch paginated results
            cursor.execute("""

                SELECT id, title 

                FROM Media 

                ORDER BY title

                LIMIT ? OFFSET ?

            """, (results_per_page, offset))
            results = cursor.fetchall()

        # Calculate total pages
        total_pages = (total_entries + results_per_page - 1) // results_per_page

        return results, total_pages, page
    except sqlite3.Error as e:
        logging.error(f"Error fetching paginated files: {e}")
        raise DatabaseError(f"Error fetching paginated files: {e}")


#
# End of Functions to handle deletion of media items
#######################################################################################################################


#######################################################################################################################
#
# Functions to manage document versions

def create_document_version(media_id: int, content: str) -> int:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            # Get the latest version number
            cursor.execute('''

                SELECT MAX(version_number) 

                FROM DocumentVersions 

                WHERE media_id = ?

            ''', (media_id,))

            latest_version = cursor.fetchone()[0] or 0
            new_version = latest_version + 1

            # Insert new version
            cursor.execute('''

                INSERT INTO DocumentVersions (media_id, version_number, content)

                VALUES (?, ?, ?)

            ''', (media_id, new_version, content))

            conn.commit()
            return new_version
    except sqlite3.Error as e:
        logging.error(f"Error creating document version: {e}")
        raise DatabaseError(f"Error creating document version: {e}")


def get_document_version(media_id: int, version_number: int = None) -> Dict[str, Any]:
    try:
        with db.get_connection() as conn:
            cursor = conn.cursor()

            if version_number is None:
                # Get the latest version
                cursor.execute('''

                    SELECT id, version_number, content, created_at

                    FROM DocumentVersions

                    WHERE media_id = ?

                    ORDER BY version_number DESC

                    LIMIT 1

                ''', (media_id,))
            else:
                cursor.execute('''

                    SELECT id, version_number, content, created_at

                    FROM DocumentVersions

                    WHERE media_id = ? AND version_number = ?

                ''', (media_id, version_number))

            result = cursor.fetchone()

            if result:
                return {
                    'id': result[0],
                    'version_number': result[1],
                    'content': result[2],
                    'created_at': result[3]
                }
            else:
                return {'error': f"No document version found for media_id {media_id}" + (f" and version_number {version_number}" if version_number is not None else "")}
    except sqlite3.Error as e:
        error_message = f"Error retrieving document version: {e}"
        logging.error(error_message)
        return {'error': error_message}

#
# End of Functions to manage document versions
#######################################################################################################################


#######################################################################################################################
#
# Functions to manage media chunks

def process_chunks(database, chunks: List[Dict], media_id: int, batch_size: int = 100):
    """

    Process chunks in batches and insert them into the database.



    :param database: Database instance to use for inserting chunks

    :param chunks: List of chunk dictionaries

    :param media_id: ID of the media these chunks belong to

    :param batch_size: Number of chunks to process in each batch

    """
    total_chunks = len(chunks)
    processed_chunks = 0

    for i in range(0, total_chunks, batch_size):
        batch = chunks[i:i + batch_size]
        chunk_data = [
            (media_id, chunk['text'], chunk['start_index'], chunk['end_index'])
            for chunk in batch
        ]

        try:
            database.execute_many(
                "INSERT INTO MediaChunks (media_id, chunk_text, start_index, end_index) VALUES (?, ?, ?, ?)",
                chunk_data
            )
            processed_chunks += len(batch)
            logging.info(f"Processed {processed_chunks}/{total_chunks} chunks for media_id {media_id}")
        except Exception as e:
            logging.error(f"Error inserting chunk batch for media_id {media_id}: {e}")
            # Optionally, you could raise an exception here to stop processing
            # raise

    logging.info(f"Finished processing all {total_chunks} chunks for media_id {media_id}")


# Usage example:
# chunks = [{'text': 'chunk1', 'start_index': 0, 'end_index': 10}, ...]
# process_chunks(db, chunks, media_id=1, batch_size=100)

def batch_insert_chunks(conn, chunks, media_id):
    cursor = conn.cursor()
    chunk_data = [(
        media_id,
        chunk['text'],
        chunk['metadata']['start_index'],
        chunk['metadata']['end_index'],
        f"{media_id}_chunk_{i}"
    ) for i, chunk in enumerate(chunks, 1)]

    cursor.executemany('''

    INSERT INTO MediaChunks (media_id, chunk_text, start_index, end_index, chunk_id)

    VALUES (?, ?, ?, ?, ?)

    ''', chunk_data)


chunk_queue = queue.Queue()

def chunk_processor():
    while True:
        chunk_batch = chunk_queue.get()
        if chunk_batch is None:
            break
        try:
            with db.get_connection() as conn:
                conn.execute("BEGIN TRANSACTION")
                try:
                    batch_insert_chunks(conn, chunk_batch['chunks'], chunk_batch['media_id'])
                    conn.commit()
                except Exception as e:
                    conn.rollback()
                    logging.error(f"Error in batch insert: {str(e)}")
        except Exception as e:
            logging.error(f"Error processing chunk batch: {str(e)}")
        finally:
            chunk_queue.task_done()

# Start the chunk processor thread
#chunk_processor_thread = threading.Thread(target=chunk_processor)
#chunk_processor_thread.start()

# Make sure to properly shut down the chunk processor when your application exits
# def shutdown_chunk_processor():
#     chunk_queue.put(None)
#     chunk_processor_thread.join()

#FIXME - add into main db creation code
def update_media_chunks_table():
    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute('''

        CREATE TABLE IF NOT EXISTS MediaChunks_new (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            media_id INTEGER,

            chunk_text TEXT,

            start_index INTEGER,

            end_index INTEGER,

            chunk_id TEXT,

            FOREIGN KEY (media_id) REFERENCES Media(id)

        )

        ''')
        cursor.execute('''

        INSERT INTO MediaChunks_new (media_id, chunk_text, start_index, end_index)

        SELECT media_id, chunk_text, start_index, end_index FROM MediaChunks

        ''')
        cursor.execute('DROP TABLE MediaChunks')
        cursor.execute('ALTER TABLE MediaChunks_new RENAME TO MediaChunks')

    logger.info("Updated MediaChunks table schema")

update_media_chunks_table()
# Above function is a dirty hack that should be merged into the initial DB creation statement. This is a placeholder
# FIXME


# This is backwards compatibility for older setups.
# Function to add a missing column to the Media table
def add_missing_column_if_not_exists(db, table_name, column_name, column_definition):
    try:
        # Check if the column already exists in the table
        cursor = db.cursor()
        cursor.execute(f"PRAGMA table_info({table_name})")
        columns = [column[1] for column in cursor.fetchall()]

        # If the column is not found, add it
        if column_name not in columns:
            logging.info(f"Adding missing column '{column_name}' to table '{table_name}'")
            cursor.execute(f"ALTER TABLE {table_name} ADD COLUMN {column_definition}")
            db.commit()
            logging.info(f"Column '{column_name}' added successfully.")
        else:
            logging.info(f"Column '{column_name}' already exists in table '{table_name}'")

    except sqlite3.Error as e:
        logging.error(f"Error checking or adding column '{column_name}' in table '{table_name}': {e}")
        raise

# Example usage of the function
def update_media_table(db):
    # Add chunking_status column if it doesn't exist
    add_missing_column_if_not_exists(db, 'Media', 'chunking_status', "TEXT DEFAULT 'pending'")

#
# End of Functions to manage media chunks
#######################################################################################################################