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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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
# DEPENDENCIES
import os
import gc
import io
import csv
import json
import time
import signal
import atexit
import shutil
import asyncio
import logging
import uvicorn
import tempfile
import traceback
import threading
from typing import Set
from typing import Any
from typing import List
from typing import Dict
from pathlib import Path
from typing import Tuple
from fastapi import File
from fastapi import Form
from signal import SIGINT
from signal import SIGTERM
from pydantic import Field
from fastapi import FastAPI
from typing import Optional
from datetime import datetime
from datetime import timedelta
from fastapi import UploadFile
from pydantic import BaseModel
from fastapi import HTTPException
from config.models import PromptType
from config.models import ChatRequest
from config.models import LLMProvider
from utils.helpers import IDGenerator
from config.models import QueryRequest 
from config.settings import get_settings
from config.models import RAGASStatistics
from config.models import RAGASExportData
from config.models import DocumentMetadata
from fastapi.responses import HTMLResponse
from fastapi.responses import FileResponse
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from utils.file_handler import FileHandler
from utils.validators import FileValidator
from fastapi.staticfiles import StaticFiles
from utils.error_handler import RAGException
from utils.error_handler import FileException
from config.models import RAGASEvaluationResult
from config.logging_config import setup_logging
from generation.llm_client import get_llm_client
from embeddings.bge_embedder import get_embedder
from concurrent.futures import ThreadPoolExecutor
from ingestion.router import get_ingestion_router
from utils.validators import validate_upload_file
from fastapi.middleware.cors import CORSMiddleware
from vector_store.index_builder import get_index_builder
from document_parser.parser_factory import ParserFactory
from evaluation.ragas_evaluator import get_ragas_evaluator
from vector_store.metadata_store import get_metadata_store
from embeddings.embedding_cache import get_embedding_cache
from ingestion.progress_tracker import get_progress_tracker
from retrieval.hybrid_retriever import get_hybrid_retriever
from chunking.adaptive_selector import get_adaptive_selector
from retrieval.context_assembler import get_context_assembler
from document_parser.parser_factory import get_parser_factory
from chunking.adaptive_selector import AdaptiveChunkingSelector 
from generation.response_generator import get_response_generator
from config.models import ProcessingStatus as ProcessingStatusEnum


# Setup logging and settings
settings = get_settings()
logger   = setup_logging(log_level      = settings.LOG_LEVEL,
                         log_dir        = settings.LOG_DIR,
                         enable_console = True,
                         enable_file    = True,
                        )


# Global Cleanup Variables 
_cleanup_registry : Set[str] = set()
_cleanup_lock                = threading.RLock()
_is_cleaning                 = False
_cleanup_executor            = ThreadPoolExecutor(max_workers        = 2, 
                                                  thread_name_prefix = "cleanup_",
                                                 )


# Analytics Cache Structure
class AnalyticsCache:
    """
    Cache for analytics data to avoid recalculating on every request
    """
    def __init__(self, ttl_seconds: int = 30):
        self.data            = None
        self.last_calculated = None
        self.ttl_seconds     = ttl_seconds
        self.is_calculating  = False
    

    def is_valid(self) -> bool:
        """
        Check if cache is still valid
        """
        if self.data is None or self.last_calculated is None:
            return False
        
        elapsed = (datetime.now() - self.last_calculated).total_seconds()
        
        return (elapsed < self.ttl_seconds)
    

    def update(self, data: Dict):
        """
        Update cache with new data
        """
        self.data            = data
        self.last_calculated = datetime.now()
    
    
    def get(self) -> Optional[Dict]:
        """
        Get cached data if valid
        """
        return self.data if self.is_valid() else None


class CleanupManager:
    """
    Centralized cleanup manager with multiple redundancy layers
    """
    @staticmethod
    def register_resource(resource_id: str, cleanup_func, *args, **kwargs):
        """
        Register a resource for cleanup
        """
        with _cleanup_lock:
            _cleanup_registry.add(resource_id)
        
        # Register with atexit for process termination
        atexit.register(cleanup_func, *args, **kwargs)
        
        return resource_id
    

    @staticmethod
    def unregister_resource(resource_id: str):
        """
        Unregister a resource (if already cleaned up elsewhere)
        """
        with _cleanup_lock:
            if resource_id in _cleanup_registry:
                _cleanup_registry.remove(resource_id)
    

    @staticmethod
    async def full_cleanup(state: Optional['AppState'] = None) -> bool:
        """
        Perform full system cleanup with redundancy
        """
        global _is_cleaning
        
        with _cleanup_lock:
            if _is_cleaning:
                logger.warning("Cleanup already in progress")
                return False
            
            _is_cleaning = True
        
        try:
            logger.info("Starting comprehensive system cleanup...")
            
            # Layer 1: Memory cleanup
            success1 = await CleanupManager._cleanup_memory(state)
            
            # Layer 2: Disk cleanup (async to not block)
            success2 = await CleanupManager._cleanup_disk_async()
            
            # Layer 3: Component cleanup
            success3 = await CleanupManager._cleanup_components(state)
            
            # Layer 4: External resources
            success4 = CleanupManager._cleanup_external_resources()
            
            # Clear registry
            with _cleanup_lock:
                _cleanup_registry.clear()
            
            overall_success = all([success1, success2, success3, success4])
            
            if overall_success:
                logger.info("Comprehensive cleanup completed successfully")
            
            else:
                logger.warning("Cleanup completed with some failures")
            
            return overall_success
            
        except Exception as e:
            logger.error(f"Cleanup failed catastrophically: {e}", exc_info=True)
            return False
        
        finally:
            with _cleanup_lock:
                _is_cleaning = False
    
    @staticmethod
    async def _cleanup_memory(state: Optional['AppState']) -> bool:
        """
        Memory cleanup
        """
        try:
            if not state:
                logger.warning("No AppState provided for memory cleanup")
                return True
            
            # Session cleanup
            session_count = len(state.active_sessions)
            state.active_sessions.clear()
            state.config_overrides.clear()
            logger.info(f"Cleared {session_count} sessions from memory")
            
            # Document data cleanup
            doc_count   = len(state.processed_documents)
            chunk_count = sum(len(chunks) for chunks in state.document_chunks.values())

            state.processed_documents.clear()
            state.document_chunks.clear()
            state.uploaded_files.clear()
            logger.info(f"Cleared {doc_count} documents ({chunk_count} chunks) from memory")
            
            # Performance data cleanup
            state.query_timings.clear()
            state.chunking_statistics.clear()
            
            # State reset
            state.is_ready          = False
            state.processing_status = "idle"
            
            # Cache cleanup
            if hasattr(state, 'analytics_cache'):
                state.analytics_cache.data = None
            
            # Force garbage collection
            collected = gc.collect()
            logger.debug(f"🧹 Garbage collection freed {collected} objects")
            
            return True
            
        except Exception as e:
            logger.error(f"Memory cleanup failed: {e}")
            return False
    
    @staticmethod
    async def _cleanup_disk_async() -> bool:
        """
        Asynchronous disk cleanup
        """
        try:
            # Run in thread pool to avoid blocking
            loop    = asyncio.get_event_loop()
            success = await loop.run_in_executor(_cleanup_executor, CleanupManager._cleanup_disk_sync)

            return success

        except Exception as e:
            logger.error(f"Async disk cleanup failed: {e}")
            return False
    

    @staticmethod
    def _cleanup_disk_sync() -> bool:
        """
        Synchronous disk cleanup
        """
        try:
            logger.info("Starting disk cleanup...")
            
            # Track what we clean
            cleaned_paths = list()
            
            # Vector store directory
            if settings.VECTOR_STORE_DIR.exists():
                vector_files = list(settings.VECTOR_STORE_DIR.glob("*"))
                for file in vector_files:
                    try:
                        if file.is_file():
                            file.unlink()
                            cleaned_paths.append(str(file))
                        
                        elif file.is_dir():
                            shutil.rmtree(file)
                            cleaned_paths.append(str(file))
                    
                    except Exception as e:
                        logger.warning(f"Failed to delete {file}: {e}")
                
                logger.info(f"Cleaned {len(cleaned_paths)} vector store files")
            
            # Upload directory (preserve directory structure)
            if settings.UPLOAD_DIR.exists():
                upload_files = list(settings.UPLOAD_DIR.glob("*"))
                for file in upload_files:
                    try:
                        if file.is_file():
                            file.unlink()
                            cleaned_paths.append(str(file))
                        
                        elif file.is_dir():
                            shutil.rmtree(file)
                            cleaned_paths.append(str(file))
                    
                    except Exception as e:
                        logger.warning(f"Failed to delete {file}: {e}")
                
                # Recreate empty directory
                settings.UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
                logger.info(f"Cleaned {len(upload_files)} uploaded files")
            
            # Metadata database
            metadata_path = Path(settings.METADATA_DB_PATH)
            if metadata_path.exists():
                try:
                    metadata_path.unlink(missing_ok=True)
                    cleaned_paths.append(str(metadata_path))
                    logger.info("Cleaned metadata database")
                
                except Exception as e:
                    logger.warning(f"Failed to delete metadata DB: {e}")
            
            # Backup directory
            if settings.BACKUP_DIR.exists():
                backup_files = list(settings.BACKUP_DIR.glob("*"))
                for file in backup_files:
                    try:
                        if file.is_file():
                            file.unlink()
                        
                        elif file.is_dir():
                            shutil.rmtree(file)
                    
                    except:
                        pass  # Silently fail for backups
                logger.info(f"Cleaned {len(backup_files)} backup files")
            
            # Temp files cleanup
            CleanupManager._cleanup_temp_files()
            
            logger.info(f"Disk cleanup completed: {len(cleaned_paths)} items cleaned")
            
            return True
            
        except Exception as e:
            logger.error(f"Disk cleanup failed: {e}")
            return False
    

    @staticmethod
    def _cleanup_temp_files():
        """
        Clean up temporary files
        """
        temp_dir = tempfile.gettempdir()
        
        # Clean our specific temp files (if any)
        for pattern in ["rag_*", "faiss_*", "embedding_*"]:
            for file in Path(temp_dir).glob(pattern):
                try:
                    file.unlink(missing_ok=True)
                except:
                    pass
    

    @staticmethod
    async def _cleanup_components(state: Optional['AppState']) -> bool:
        """
        Component-specific cleanup
        """
        try:
            if not state:
                return True
            
            components_cleaned = 0
            
            # Vector store components
            if state.index_builder:
                try:
                    state.index_builder.clear_indexes()
                    components_cleaned += 1
                
                except Exception as e:
                    logger.warning(f"Index builder cleanup failed: {e}")
            
            if state.metadata_store and hasattr(state.metadata_store, 'clear_all'):
                try:
                    state.metadata_store.clear_all()
                    components_cleaned += 1
                
                except Exception as e:
                    logger.warning(f"Metadata store cleanup failed: {e}")
            
            # RAGAS evaluator
            if state.ragas_evaluator and hasattr(state.ragas_evaluator, 'clear_history'):
                try:
                    state.ragas_evaluator.clear_history()
                    components_cleaned += 1
                
                except Exception as e:
                    logger.warning(f"RAGAS evaluator cleanup failed: {e}")
            
            logger.info(f"Cleaned {components_cleaned} components")
            return True
            
        except Exception as e:
            logger.error(f"Component cleanup failed: {e}")
            return False
    

    @staticmethod
    def _cleanup_external_resources() -> bool:
        """
        External resource cleanup
        """
        try:
            # Close database connections
            CleanupManager._close_db_connections()
            
            # Clean up thread pool
            _cleanup_executor.shutdown(wait = False)
            
            logger.info("External resources cleaned")
            return True
            
        except Exception as e:
            logger.error(f"External resource cleanup failed: {e}")
            return False
    

    @staticmethod
    def _close_db_connections():
        """
        Close any open database connections
        """
        try:
            # SQLite handles this automatically in most cases
            pass
        except:
            pass

    
    @staticmethod
    def handle_signal(signum, frame):
        """
        Signal handler for graceful shutdown
        """
        global _is_cleaning
        
        # If already cleaning up, don't raise KeyboardInterrupt
        with _cleanup_lock:
            if _is_cleaning:
                logger.info(f"Signal {signum} received during cleanup - ignoring")
                return
            
        if (signum == SIGINT):
            logger.info("Ctrl+C received - shutdown initiated")
            raise KeyboardInterrupt
        
        elif (signum == SIGTERM):
            logger.info("SIGTERM received - shutdown initiated")
            # Just log, not scheduling anything
        
        else:
            logger.info(f"Signal {signum} received")


# Global state manager
class AppState:
    """
    Manages application state and components
    """
    def __init__(self):
        self.is_ready            = False
        self.processing_status   = "idle"
        self.uploaded_files      = list()
        self.active_sessions     = dict()
        self.processed_documents = dict()
        self.document_chunks     = dict()
        
        # Performance tracking
        self.query_timings       = list()  
        self.chunking_statistics = dict()
        
        # Core components
        self.file_handler        = None
        self.parser_factory      = None
        self.chunking_selector   = None
        
        # Embeddings components
        self.embedder            = None
        self.embedding_cache     = None
        
        # Ingestion components
        self.ingestion_router    = None
        self.progress_tracker    = None
        
        # Vector store components
        self.index_builder       = None
        self.metadata_store      = None
        
        # Retrieval components
        self.hybrid_retriever    = None
        self.context_assembler   = None
        
        # Generation components
        self.response_generator  = None
        self.llm_client          = None
        
        # RAGAS component
        self.ragas_evaluator     = None

        # Processing tracking
        self.current_processing  = None
        self.processing_progress = {"status"       : "idle",
                                    "current_step" : "Waiting",
                                    "progress"     : 0,
                                    "processed"    : 0,
                                    "total"        : 0,
                                    "details"      : {},
                                   }

        # Session-based configuration overrides
        self.config_overrides    = dict()
        
        # Analytics cache
        self.analytics_cache     = AnalyticsCache(ttl_seconds = 30)
        
        # System start time
        self.start_time          = datetime.now()

        # Add cleanup tracking 
        self._cleanup_registered = False
        self._cleanup_resources  = list()
        
        # Register with cleanup manager
        self._register_for_cleanup()


    def _register_for_cleanup(self):
        """
        Register this AppState instance for cleanup
        """
        if not self._cleanup_registered:
            resource_id              = f"appstate_{id(self)}"

            CleanupManager.register_resource(resource_id, self._emergency_cleanup)
            self._cleanup_resources.append(resource_id)
            
            self._cleanup_registered = True
    

    def _emergency_cleanup(self):
        """
        Emergency cleanup if regular cleanup fails
        """
        try:
            logger.warning("Performing emergency cleanup...")
            
            # Brutal but effective memory clearing
            for attr in ['active_sessions', 'processed_documents', 'document_chunks', 'uploaded_files', 'query_timings', 'chunking_statistics']:
                if hasattr(self, attr):
                    getattr(self, attr).clear()
            
            # Nullify heavy objects
            self.index_builder  = None
            self.metadata_store = None
            self.embedder       = None
            
            logger.warning("Emergency cleanup completed")
        
        except:
            # Last resort - don't crash during emergency cleanup
            pass  
    

    async def graceful_shutdown(self):
        """
        Graceful shutdown procedure
        """
        logger.info("Starting graceful shutdown...")
        
        # Notify clients (if any WebSocket connections)
        await self._notify_clients()
        
        # Perform cleanup
        await CleanupManager.full_cleanup(self)
        
        # Unregister from cleanup manager
        for resource_id in self._cleanup_resources:
            CleanupManager.unregister_resource(resource_id)
        
        logger.info("Graceful shutdown completed")
    

    async def _notify_clients(self):
        """
        Notify connected clients of shutdown
        """
        # Placeholder for WebSocket notifications
        pass
    

    def add_query_timing(self, duration_ms: float):
        """
        Record query timing for analytics
        """
        self.query_timings.append((datetime.now(), duration_ms))
        # Keep only last 1000 timings to prevent memory issues
        if (len(self.query_timings) > 1000):
            self.query_timings = self.query_timings[-1000:]
    

    def get_performance_metrics(self) -> Dict:
        """
        Calculate performance metrics from recorded timings
        """
        if not self.query_timings:
            return {"avg_response_time" : 0,
                    "min_response_time" : 0,
                    "max_response_time" : 0,
                    "total_queries"     : 0,
                    "queries_last_hour" : 0,
                   }
        

        # Get recent timings (last hour)
        one_hour_ago   = datetime.now() - timedelta(hours = 1)
        recent_timings = [t for t, _ in self.query_timings if (t > one_hour_ago)]
        
        # Calculate statistics
        durations      = [duration for _, duration in self.query_timings]
        
        return {"avg_response_time" : int(sum(durations) / len(durations)),
                "min_response_time" : int(min(durations)) if durations else 0,
                "max_response_time" : int(max(durations)) if durations else 0,
                "total_queries"     : len(self.query_timings),
                "queries_last_hour" : len(recent_timings),
                "p95_response_time" : int(sorted(durations)[int(len(durations) * 0.95)]) if (len(durations) > 10) else 0,
               }

    
    def get_chunking_statistics(self) -> Dict:
        """
        Get statistics about chunking strategies used
        """
        if not self.chunking_statistics:
            return {"primary_strategy" : "adaptive",
                    "total_chunks"     : 0,
                    "avg_chunk_size"   : 0,
                    "strategies_used"  : {},
                   }
        
        total_chunks = sum(self.chunking_statistics.values())
        strategies   = {k: v for k, v in self.chunking_statistics.items() if (v > 0)}
        
        return {"primary_strategy" : max(strategies.items(), key=lambda x: x[1])[0] if strategies else "adaptive",
                "total_chunks"     : total_chunks,
                "strategies_used"  : strategies,
               }

    
    def get_system_health(self) -> Dict:
        """
        Get comprehensive system health status
        """
        llm_healthy        = self.llm_client.check_health() if self.llm_client else False
        vector_store_ready = self.is_ready
        
        # Check embedding model
        embedding_ready    = self.embedder is not None
        
        # Check retrieval components
        retrieval_ready    = (self.hybrid_retriever is not None and self.context_assembler is not None)
        
        # Determine overall status
        if all([llm_healthy, vector_store_ready, embedding_ready, retrieval_ready]):
            overall_status = "healthy"
        
        elif vector_store_ready and embedding_ready and retrieval_ready:
            # LLM issues but RAG works
            overall_status = "degraded"  
        
        else:
            overall_status = "unhealthy"
        
        return {"overall"      : overall_status,
                "llm"          : llm_healthy,
                "vector_store" : vector_store_ready,
                "embeddings"   : embedding_ready,
                "retrieval"    : retrieval_ready,
                "generation"   : self.response_generator is not None,
               }

    
    def get_system_information(self) -> Dict:
        """
        Get current system information
        """
        # Get chunking strategy
        chunking_strategy = "adaptive"
        
        if self.chunking_selector:
            try:
                # Try to get strategy from selector
                if (hasattr(self.chunking_selector, 'get_current_strategy')):
                    chunking_strategy = self.chunking_selector.get_current_strategy()
                
                elif (hasattr(self.chunking_selector, 'prefer_llamaindex')):
                    chunking_strategy = "llama_index" if self.chunking_selector.prefer_llamaindex else "adaptive"
            
            except:
                pass
        
        # Get vector store status
        vector_store_status = "Not Ready"

        if self.is_ready:
            try:
                index_stats  = self.index_builder.get_index_stats() if self.index_builder else {}
                total_chunks = index_stats.get('total_chunks_indexed', 0)
                
                if (total_chunks > 0):
                    vector_store_status = f"Ready ({total_chunks} chunks)"
                
                else:
                    vector_store_status = "Empty"
            
            except:
                vector_store_status = "Ready"
        
        # Get model info
        current_model   = settings.OPENAI_MODEL
        embedding_model = settings.EMBEDDING_MODEL
        
        # Uptime
        uptime_seconds  = (datetime.now() - self.start_time).total_seconds()
        
        return {"vector_store_status"   : vector_store_status,
                "current_model"         : current_model,
                "embedding_model"       : embedding_model,
                "chunking_strategy"     : chunking_strategy,
                "system_uptime_seconds" : int(uptime_seconds),
                "last_updated"          : datetime.now().isoformat(),
               }
    

    def calculate_quality_metrics(self) -> Dict:
        """
        Calculate quality metrics for the system
        """
        total_queries = 0
        total_sources = 0
        source_counts = list()
        
        # Analyze session data
        for session_id, messages in self.active_sessions.items():
            total_queries += len(messages)
            
            for msg in messages:
                sources        = len(msg.get('sources', []))
                total_sources += sources

                source_counts.append(sources)
        
        # Calculate averages
        avg_sources_per_query = total_sources / total_queries if total_queries > 0 else 0
        
        # Calculate metrics based on heuristics
        # These are simplified - for production, use RAGAS or similar framework
        
        if (total_queries == 0):
            return {"answer_relevancy"  : 0.0,
                    "faithfulness"      : 0.0,
                    "context_precision" : 0.0,
                    "context_recall"    : None,
                    "overall_score"     : 0.0,
                    "confidence"        : "low",
                    "metrics_available" : False
                   }
        
        # Heuristic calculations
        answer_relevancy  = min(0.9, 0.7 + (avg_sources_per_query * 0.1))
        faithfulness      = min(0.95, 0.8 + (avg_sources_per_query * 0.05))
        context_precision = min(0.85, 0.6 + (avg_sources_per_query * 0.1))
        
        # Overall score weighted average
        overall_score     = (answer_relevancy * 0.4 + faithfulness * 0.3 + context_precision * 0.3)
        
        confidence        = "high" if total_queries > 10 else ("medium" if (total_queries > 3) else "low")
        
        return {"answer_relevancy"      : round(answer_relevancy, 3),
                "faithfulness"          : round(faithfulness, 3),
                "context_precision"     : round(context_precision, 3),
                "context_recall"        : None,  # Requires ground truth
                "overall_score"         : round(overall_score, 3),
                "avg_sources_per_query" : round(avg_sources_per_query, 2),
                "queries_with_sources"  : sum(1 for count in source_counts if count > 0),
                "confidence"            : confidence,
                "metrics_available"     : True,
                "evaluation_note"       : "Metrics are heuristic estimates. For accurate evaluation, use RAGAS framework.",
               }

    
    def calculate_comprehensive_analytics(self) -> Dict:
        """
        Calculate comprehensive analytics data
        """
        # Performance metrics
        performance     = self.get_performance_metrics()
        
        # System information
        system_info     = self.get_system_information()
        
        # Quality metrics
        quality_metrics = self.calculate_quality_metrics()
        
        # Health status
        health_status   = self.get_system_health()
        
        # Chunking statistics
        chunking_stats  = self.get_chunking_statistics()
        
        # Document statistics
        total_docs      = len(self.processed_documents)
        total_chunks    = sum(len(chunks) for chunks in self.document_chunks.values())
        
        # Session statistics
        total_sessions  = len(self.active_sessions)
        total_messages  = sum(len(msgs) for msgs in self.active_sessions.values())
        
        # File statistics
        uploaded_files  = len(self.uploaded_files)
        total_file_size = sum(f.get('size', 0) for f in self.uploaded_files)
        
        # Index statistics
        index_stats     = dict()

        if self.index_builder:
            try:
                index_stats = self.index_builder.get_index_stats()
            
            except:
                index_stats = {"error": "Could not retrieve index stats"}
        
        return {"performance_metrics" : performance,
                "quality_metrics"     : quality_metrics,
                "system_information"  : system_info,
                "health_status"       : health_status,
                "chunking_statistics" : chunking_stats,
                "document_statistics" : {"total_documents"         : total_docs,
                                         "total_chunks"            : total_chunks,
                                         "uploaded_files"          : uploaded_files,
                                         "total_file_size_bytes"   : total_file_size,
                                         "total_file_size_mb"      : round(total_file_size / (1024 * 1024), 2) if (total_file_size > 0) else 0,
                                         "avg_chunks_per_document" : round(total_chunks / total_docs, 2) if (total_docs > 0) else 0,
                                        },
                "session_statistics"  : {"total_sessions"           : total_sessions,
                                         "total_messages"           : total_messages,
                                         "avg_messages_per_session" : round(total_messages / total_sessions, 2) if (total_sessions > 0) else 0
                                        },
                "index_statistics"    : index_stats,
                "calculated_at"       : datetime.now().isoformat(),
                "cache_info"          : {"from_cache"      : False,
                                         "next_refresh_in" : self.analytics_cache.ttl_seconds,
                                        }
               }


def _setup_signal_handlers():
    """
    Setup signal handlers for graceful shutdown
    """
    try:
        signal.signal(signal.SIGINT, CleanupManager.handle_signal)
        signal.signal(signal.SIGTERM, CleanupManager.handle_signal)
        logger.debug("Signal handlers registered")
    
    except Exception as e:
        logger.warning(f"Failed to setup signal handlers: {e}")


def _atexit_cleanup():
    """
    Atexit handler as last resort
    """
    logger.info("Atexit cleanup triggered")
    
    # Check if it's already in a cleanup process
    with _cleanup_lock:
        if _is_cleaning:
            logger.info("Cleanup already in progress, skipping atexit cleanup")
            return

    try:
        # Check if app exists
        if (('app' in globals()) and (hasattr(app.state, 'app'))):
            # Run cleanup in background thread
            cleanup_thread = threading.Thread(target  = lambda: asyncio.run(CleanupManager.full_cleanup(app.state.app)),
                                              name    = "atexit_cleanup",
                                              daemon  = True,
                                             )
            cleanup_thread.start()
            cleanup_thread.join(timeout = 5.0)
    
    except Exception as e:
        logger.error(f"Atexit cleanup error: {e}")
        # Don't crash during atexit


async def _brute_force_cleanup_app_state(state: AppState):
    """
    Brute force AppState cleanup
    """
    try:
        # Clear all collections
        for attr_name in dir(state):
            if not attr_name.startswith('_'):
                attr = getattr(state, attr_name)
                
                if isinstance(attr, (list, dict, set)):
                    attr.clear()
        
        # Nullify heavy components
        for attr_name in ['index_builder', 'metadata_store', 'embedder', 'llm_client', 'ragas_evaluator']:
            if hasattr(state, attr_name):
                setattr(state, attr_name, None)
        
    except:
        pass


# Application lifespan manager
@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Manage application startup and shutdown with multiple cleanup guarantees
    """
    # Setup signal handlers FIRST
    _setup_signal_handlers()
    
    # Register atexit cleanup
    atexit.register(_atexit_cleanup)

    logger.info("Starting QuerySphere ...")
    
    try:
        # Initialize application state
        app.state.app = AppState()
        
        # Initialize core components
        await initialize_components(app.state.app)
        
        logger.info("Application startup complete. System ready.")
        
        # Yield control to FastAPI
        yield
    
    except Exception as e:
        logger.error(f"Application runtime error: {e}", exc_info = True)
        raise
    
    finally:
        # GUARANTEED cleanup (even on crash)
        logger.info("Beginning guaranteed cleanup sequence...")
        
        # Set the cleaning flag
        with _cleanup_lock:
            _is_cleaning = True
        
        try:
            # Simple cleanup
            if (hasattr(app.state, 'app')):
                # Just clear the state, don't run full cleanup again
                await _brute_force_cleanup_app_state(app.state.app)
                
                # Clean up disk resources
                await CleanupManager._cleanup_disk_async()
                
                # Shutdown the executor
                _cleanup_executor.shutdown(wait = True)
        
        except Exception as e:
            logger.error(f"Cleanup error in lifespan finally: {e}")
    


# Create FastAPI application
app = FastAPI(title       = "QuerySphere",
              description = "Enterprise RAG Platform with Multi-Source & Multi-Format Document Ingestion Support",
              version     = "1.0.0",
              lifespan    = lifespan,
             )


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


# ============================================================================
# INITIALIZATION FUNCTIONS
# ============================================================================
async def initialize_components(state: AppState):
    """
    Initialize all application components
    """
    try:
        logger.info("Initializing components...")
        
        # Create necessary directories
        create_directories()
        
        # Initialize utilities
        state.file_handler      = FileHandler()
        logger.info("FileHandler initialized")
        
        # Initialize document parsing
        state.parser_factory    = get_parser_factory()
        logger.info(f"ParserFactory initialized with support for: {', '.join(state.parser_factory.get_supported_extensions())}")
        
        # Initialize chunking
        state.chunking_selector = get_adaptive_selector()
        logger.info("AdaptiveChunkingSelector initialized")
        
        # Initialize embeddings
        state.embedder          = get_embedder()
        state.embedding_cache   = get_embedding_cache()
        logger.info(f"Embedder initialized: {state.embedder.get_model_info()}")
        
        # Initialize ingestion
        state.ingestion_router  = get_ingestion_router()
        state.progress_tracker  = get_progress_tracker()
        logger.info("Ingestion components initialized")
        
        # Initialize vector store
        state.index_builder     = get_index_builder()
        state.metadata_store    = get_metadata_store()
        logger.info("Vector store components initialized")
        
        # Check if indexes exist and load them
        if state.index_builder.is_index_built():
            logger.info("Existing indexes found - loading...")
            index_stats    = state.index_builder.get_index_stats()

            logger.info(f"Indexes loaded: {index_stats}")
            state.is_ready = True
        
        # Initialize retrieval
        state.hybrid_retriever  = get_hybrid_retriever()
        state.context_assembler = get_context_assembler()
        logger.info("Retrieval components initialized")
        
        # Initialize generation components
        state.response_generator = get_response_generator(provider   = LLMProvider.OPENAI,
                                                          model_name = settings.OPENAI_MODEL,
                                                         )

        state.llm_client         = get_llm_client(provider = LLMProvider.OPENAI)

        logger.info(f"Generation components initialized: model={settings.OPENAI_MODEL}")

        # Check LLM health
        if state.llm_client.check_health():
            logger.info("LLM provider health check: PASSED")
        
        else:
            logger.warning("LLM provider health check: FAILED - Ensure Ollama is running")
            logger.warning("- Run: ollama serve (in a separate terminal)")
            logger.warning("- Run: ollama pull mistral (if model not downloaded)")

        # Initialize RAGAS evaluator
        if settings.ENABLE_RAGAS:
            state.ragas_evaluator = get_ragas_evaluator(enable_ground_truth_metrics = settings.RAGAS_ENABLE_GROUND_TRUTH)

            logger.info("RAGAS evaluator initialized")

        else:
            logger.info("RAGAS evaluation disabled in settings")

        
        logger.info("All components initialized successfully")
        
    except Exception as e:
        logger.error(f"Component initialization failed: {e}", exc_info = True)
        raise


async def cleanup_components(state: AppState):
    """
    Cleanup components on shutdown
    """
    try:
        logger.info("Starting component cleanup...")
    
        # Use the cleanup manager
        await CleanupManager.full_cleanup(state)
        
        logger.info("Component cleanup complete")
        
    except Exception as e:
        logger.error(f"Component cleanup error: {e}", exc_info = True)
        
        # Last-ditch effort
        await _brute_force_cleanup_app_state(state)


def create_directories():
    """
    Create necessary directories
    """
    directories = [settings.UPLOAD_DIR,
                   settings.VECTOR_STORE_DIR,
                   settings.BACKUP_DIR,
                   Path(settings.METADATA_DB_PATH).parent,
                   settings.LOG_DIR,
                  ]
    
    for directory in directories:
        Path(directory).mkdir(parents = True, exist_ok = True)
    
    logger.info("Directories created/verified")


# ============================================================================
# API ENDPOINTS
# ============================================================================
@app.get("/", response_class = HTMLResponse)
async def serve_frontend():
    """
    Serve the main frontend HTML
    """
    frontend_path = Path("frontend/index.html")
    if frontend_path.exists():
        return FileResponse(frontend_path)
    
    raise HTTPException(status_code = 404, 
                        detail      = "Frontend not found",
                       )


@app.get("/api/health")
async def health_check():
    """
    Health check endpoint
    """
    state         = app.state.app
    
    health_status = state.get_system_health()
    
    return {"status"     : health_status["overall"],
            "timestamp"  : datetime.now().isoformat(),
            "version"    : "1.0.0",
            "components" : {"vector_store"     : health_status["vector_store"],
                            "llm"              : health_status["llm"],
                            "embeddings"       : health_status["embeddings"],
                            "retrieval"        : health_status["retrieval"],
                            "generation"       : health_status["generation"],
                            "hybrid_retriever" : health_status["retrieval"],
                           },
            "details"    : health_status
           }


@app.get("/api/system-info")
async def get_system_info():
    """
    Get system information and status
    """
    state       = app.state.app
    
    # Get system information
    system_info = state.get_system_information()
    
    # Get LLM provider info
    llm_info    = dict()

    if state.llm_client:
        llm_info = state.llm_client.get_provider_info()
    
    # Get current configuration
    current_config = {"inference_model"  : settings.OPENAI_MODEL,
                      "embedding_model"  : settings.EMBEDDING_MODEL,
                      "vector_weight"    : settings.VECTOR_WEIGHT,
                      "bm25_weight"      : settings.BM25_WEIGHT,
                      "temperature"      : settings.DEFAULT_TEMPERATURE,
                      "max_tokens"       : settings.MAX_TOKENS,
                      "chunk_size"       : settings.FIXED_CHUNK_SIZE,
                      "chunk_overlap"    : settings.FIXED_CHUNK_OVERLAP,
                      "top_k_retrieve"   : settings.TOP_K_RETRIEVE,
                      "enable_reranking" : settings.ENABLE_RERANKING,
                     }
                    
    return {"system_state"       : {"is_ready"          : state.is_ready,
                                    "processing_status" : state.processing_status,
                                    "total_documents"   : len(state.uploaded_files),
                                    "active_sessions"   : len(state.active_sessions),
                                   },
            "configuration"      : current_config,
            "llm_provider"       : llm_info,
            "system_information" : system_info,
            "timestamp"          : datetime.now().isoformat()
           }


@app.post("/api/upload")
async def upload_files(files: List[UploadFile] = File(...)):
    """
    Upload multiple files
    """
    state = app.state.app
    
    try:
        logger.info(f"Received {len(files)} files for upload")
        uploaded_info = list()
        
        for file in files:
            try:
                # Validate file type
                if not state.parser_factory.is_supported(Path(file.filename)):
                    logger.warning(f"Unsupported file type: {file.filename}")
                    continue
                
                # Save file to upload directory
                file_path     = settings.UPLOAD_DIR / FileHandler.generate_unique_filename(file.filename, settings.UPLOAD_DIR)
                
                # Write file content
                content       = await file.read()

                with open(file_path, 'wb') as f:
                    f.write(content)
                
                # Get file metadata
                file_metadata = FileHandler.get_file_metadata(file_path)
                
                file_info     = {"filename"      : file_path.name,
                                 "original_name" : file.filename,
                                 "size"          : file_metadata["size_bytes"],
                                 "upload_time"   : datetime.now().isoformat(),
                                 "file_path"     : str(file_path),
                                 "status"        : "uploaded",
                                }
                
                uploaded_info.append(file_info)
                state.uploaded_files.append(file_info)
                
                logger.info(f"Uploaded: {file.filename} -> {file_path.name}")
                
            except Exception as e:
                logger.error(f"Failed to upload {file.filename}: {e}")
                continue
        
        # Clear analytics cache since we have new data
        state.analytics_cache.data = None
        
        return {"success" : True,
                "message" : f"Successfully uploaded {len(uploaded_info)} files",
                "files"   : uploaded_info,
               }
        
    except Exception as e:
        logger.error(f"Upload error: {e}", exc_info = True)

        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.post("/api/start-processing")
async def start_processing():
    """
    Start processing uploaded documents
    """
    state = app.state.app
    
    if not state.uploaded_files:
        raise HTTPException(status_code = 400, 
                            detail      = "No files uploaded",
                           )

     
    if (state.processing_status == "processing"):
        raise HTTPException(status_code = 400, 
                            detail      = "Processing already in progress",
                           )
    
    try:
        state.processing_status   = "processing"
        state.processing_progress = {"status"       : "processing",
                                     "current_step" : "Starting document processing...",
                                     "progress"     : 0,
                                     "processed"    : 0,
                                     "total"        : len(state.uploaded_files),
                                     "details"      : {},
                                    }
        
        logger.info("Starting document processing pipeline...")
        
        all_chunks     = list()
        chunking_stats = dict()
        
        # Process each file
        for idx, file_info in enumerate(state.uploaded_files):
            try:
                file_path                                 = Path(file_info["file_path"])
                
                # Update progress - Parsing
                state.processing_progress["current_step"] = f"Parsing {file_info['original_name']}..."
                state.processing_progress["progress"]     = int((idx / len(state.uploaded_files)) * 20)
                
                # Parse document
                logger.info(f"Parsing document: {file_path}")
                text, metadata                            = state.parser_factory.parse(file_path,
                                                                                       extract_metadata = True,
                                                                                       clean_text       = True,
                                                                                      )
                
                if not text:
                    logger.warning(f"No text extracted from {file_path}")
                    continue
                
                logger.info(f"Extracted {len(text)} characters from {file_path}")
                
                # Update progress - Chunking
                state.processing_progress["current_step"] = f"Chunking {file_info['original_name']}..."
                state.processing_progress["progress"]     = int((idx / len(state.uploaded_files)) * 40) + 20
                
                # Chunk document
                logger.info(f"Chunking document: {metadata.document_id}")
                chunks                                    = state.chunking_selector.chunk_text(text     = text,
                                                                                               metadata = metadata,
                                                                                              )
                
                # Get strategy used from metadata or selector
                strategy_used = "adaptive"  # Default

                if (metadata and hasattr(metadata, 'chunking_strategy')):
                    strategy_used = metadata.chunking_strategy.value if metadata.chunking_strategy else "adaptive"
                
                elif (hasattr(state.chunking_selector, 'last_strategy_used')):
                    strategy_used = state.chunking_selector.last_strategy_used

                # Track chunking strategy usage
                if strategy_used not in chunking_stats:
                    chunking_stats[strategy_used] = 0

                chunking_stats[strategy_used] += len(chunks)
                
                logger.info(f"Created {len(chunks)} chunks for {metadata.document_id} using {strategy_used}")
                
                # Update progress - Embedding
                state.processing_progress["current_step"] = f"Generating embeddings for {file_info['original_name']}..."
                state.processing_progress["progress"]     = int((idx / len(state.uploaded_files)) * 60) + 40
                
                # Generate embeddings for chunks
                logger.info(f"Generating embeddings for {len(chunks)} chunks...")
                chunks_with_embeddings                    = state.embedder.embed_chunks(chunks     = chunks,
                                                                                        batch_size = settings.EMBEDDING_BATCH_SIZE,
                                                                                        normalize  = True,
                                                                                       )
                
                logger.info(f"Generated embeddings for {len(chunks_with_embeddings)} chunks")
                
                # Store chunks
                all_chunks.extend(chunks_with_embeddings)
                
                # Store processed document and chunks
                state.processed_documents[metadata.document_id] = {"metadata"          : metadata,
                                                                   "text"              : text,
                                                                   "file_info"         : file_info,
                                                                   "chunks_count"      : len(chunks_with_embeddings),
                                                                   "processed_time"    : datetime.now().isoformat(),
                                                                   "chunking_strategy" : strategy_used,
                                                                  }
                
                state.document_chunks[metadata.document_id]     = chunks_with_embeddings
                
                # Update progress
                state.processing_progress["processed"]          = idx + 1
                
            except Exception as e:
                logger.error(f"Failed to process {file_info['original_name']}: {e}", exc_info=True)
                continue
        
        # Update chunking statistics
        state.chunking_statistics = chunking_stats
        
        if not all_chunks:
            raise Exception("No chunks were successfully processed")
        
        # Update progress - Building indexes
        state.processing_progress["current_step"] = "Building vector and keyword indexes..."
        state.processing_progress["progress"]     = 80
        
        # Build indexes (FAISS + BM25 + Metadata)
        logger.info(f"Building indexes for {len(all_chunks)} chunks...")
        index_stats                               = state.index_builder.build_indexes(chunks  = all_chunks,
                                                                                      rebuild = True,
                                                                                     )
        
        logger.info(f"Indexes built: {index_stats}")
        
        # Update progress - Indexing for hybrid retrieval
        state.processing_progress["current_step"] = "Indexing for hybrid retrieval..."
        state.processing_progress["progress"]     = 95
        
        # Mark as ready
        state.processing_status                   = "ready"
        state.is_ready                            = True
        state.processing_progress["status"]       = "ready"
        state.processing_progress["current_step"] = "Processing complete"
        state.processing_progress["progress"]     = 100
        
        # Clear analytics cache
        state.analytics_cache.data                = None
        
        logger.info(f"Processing complete. Processed {len(state.processed_documents)} documents with {len(all_chunks)} total chunks.")
        
        return {"success"             : True,
                "message"             : "Processing completed successfully",
                "status"              : "ready",
                "documents_processed" : len(state.processed_documents),
                "total_chunks"        : len(all_chunks),
                "chunking_statistics" : chunking_stats,
                "index_stats"         : index_stats,
               }
        
    except Exception as e:
        state.processing_status             = "error"
        state.processing_progress["status"] = "error"

        logger.error(f"Processing error: {e}", exc_info = True)

        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/processing-status")
async def get_processing_status():
    """
    Get current processing status
    """
    state = app.state.app
    
    return {"status"              : state.processing_progress["status"],
            "progress"            : state.processing_progress["progress"],
            "current_step"        : state.processing_progress["current_step"],
            "processed_documents" : state.processing_progress["processed"],
            "total_documents"     : state.processing_progress["total"],
            "details"             : state.processing_progress["details"],
           }


@app.get("/api/ragas/history")
async def get_ragas_history():
    """
    Get RAGAS evaluation history for current session
    """
    state = app.state.app
    
    if not settings.ENABLE_RAGAS or not state.ragas_evaluator:

        raise HTTPException(status_code = 400,
                            detail      = "RAGAS evaluation is not enabled. Set ENABLE_RAGAS=True in settings.",
                           )
    
    try:
        history = state.ragas_evaluator.get_evaluation_history()
        stats   = state.ragas_evaluator.get_session_statistics()
        
        return {"success"     : True,
                "total_count" : len(history),
                "statistics"  : stats.model_dump(), 
                "history"     : history
               }
        
    except Exception as e:
        logger.error(f"RAGAS history retrieval error: {e}", exc_info = True)

        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.post("/api/ragas/clear")
async def clear_ragas_history():
    """
    Clear RAGAS evaluation history
    """
    state = app.state.app
    
    if not settings.ENABLE_RAGAS or not state.ragas_evaluator:

        raise HTTPException(status_code = 400,
                            detail      = "RAGAS evaluation is not enabled.",
                           )
    
    try:
        state.ragas_evaluator.clear_history()
        
        return {"success" : True,
                "message" : "RAGAS evaluation history cleared, new session started",
               }
        
    except Exception as e:
        logger.error(f"RAGAS history clear error: {e}", exc_info = True)

        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/ragas/statistics")
async def get_ragas_statistics():
    """
    Get aggregate RAGAS statistics for current session
    """
    state = app.state.app
    
    if not settings.ENABLE_RAGAS or not state.ragas_evaluator:

        raise HTTPException(status_code = 400,
                            detail      = "RAGAS evaluation is not enabled.",
                           )
    
    try:
        stats = state.ragas_evaluator.get_session_statistics()
        
        return {"success"    : True,
                "statistics" : stats.model_dump(),
               }
        
    except Exception as e:
        logger.error(f"RAGAS statistics error: {e}", exc_info = True)

        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/ragas/export")
async def export_ragas_data():
    """
    Export all RAGAS evaluation data
    """
    state = app.state.app
    
    if not settings.ENABLE_RAGAS or not state.ragas_evaluator:

        raise HTTPException(status_code = 400,
                            detail      = "RAGAS evaluation is not enabled.",
                           )
    
    try:
        export_data = state.ragas_evaluator.export_to_dict()
        
        return JSONResponse(content = json.loads(export_data.model_dump_json()))
        
    except Exception as e:
        logger.error(f"RAGAS export error: {e}", exc_info = True)

        raise HTTPException(status_code = 500,
                            detail      = str(e),
                           )


@app.get("/api/ragas/config")
async def get_ragas_config():
    """
    Get current RAGAS configuration
    """
    return {"enabled"              : settings.ENABLE_RAGAS,
            "ground_truth_enabled" : settings.RAGAS_ENABLE_GROUND_TRUTH,
            "base_metrics"         : settings.RAGAS_METRICS,
            "ground_truth_metrics" : settings.RAGAS_GROUND_TRUTH_METRICS,
            "evaluation_timeout"   : settings.RAGAS_EVALUATION_TIMEOUT,
            "batch_size"           : settings.RAGAS_BATCH_SIZE,
           }


@app.post("/api/chat")
async def chat(request: ChatRequest):
    """
    Handle chat queries with LLM-based intelligent routing (generic vs RAG)
    Supports both conversational queries and document-based queries
    """
    state      = app.state.app
    
    message    = request.message
    session_id = request.session_id
    
    # Check LLM health (required for both general and RAG queries)
    if not state.llm_client.check_health():
        raise HTTPException(status_code = 503,
                            detail      = "LLM service unavailable. Please ensure OpenAI API Key is availabale or Ollama is running.",
                           )
    
    try:
        logger.info(f"Chat query received: {message}")
        
        # Check if documents are available
        has_documents = state.is_ready and (len(state.processed_documents) > 0)
        
        logger.debug(f"System state - Documents available: {has_documents}, Processed docs: {len(state.processed_documents)}, System ready: {state.is_ready}")
        
        # Get conversation history for this session (for general queries)
        conversation_history = None
        
        if (session_id and (session_id in state.active_sessions)):
            # Convert to format expected by general_responder
            conversation_history = list()
            
            # Last 10 messages for context
            for msg in state.active_sessions[session_id][-10:]:
                conversation_history.append({"role"    : "user",
                                             "content" : msg.get("query", ""),
                                           })

                conversation_history.append({"role"    : "assistant",
                                             "content" : msg.get("response", ""),
                                           })
        
        # Create QueryRequest object
        query_request     = QueryRequest(query            = message,
                                         top_k            = settings.TOP_K_RETRIEVE,
                                         enable_reranking = settings.ENABLE_RERANKING,
                                         temperature      = settings.DEFAULT_TEMPERATURE,
                                         top_p            = settings.TOP_P,
                                         max_tokens       = settings.MAX_TOKENS,
                                         include_sources  = True,
                                         include_metrics  = False,
                                         stream           = False,
                                        )
        
        # Generate response using response generator (with LLM-based routing)
        start_time        = time.time()

        query_response    = await state.response_generator.generate_response(request              = query_request,
                                                                             conversation_history = conversation_history,
                                                                             has_documents        = has_documents,  # Pass document availability
                                                                            )
        
        # Convert to ms
        total_time        = (time.time() - start_time) * 1000
        
        # Record timing for analytics
        state.add_query_timing(total_time)

        # Determine query type using response metadata
        is_general_query  = False

        # Default to rag
        actual_query_type = "rag"  

        # Check if response has metadata
        if (hasattr(query_response, 'query_type')):
            actual_query_type = query_response.query_type
            is_general_query  = (actual_query_type == "general")

        elif (hasattr(query_response, 'is_general_query')):
            is_general_query  = query_response.is_general_query
            actual_query_type = "general" if is_general_query else "rag"

        else:
            # Method 2: Check sources (fallback)
            has_sources       = query_response.sources and len(query_response.sources) > 0
            is_general_query  = not has_sources
            actual_query_type = "general" if is_general_query else "rag"
        
        logger.debug(f"Query classification: actual_query_type={actual_query_type}, has_sources={query_response.sources and len(query_response.sources) > 0}")
    
        # Extract contexts for RAGAS evaluation (only if RAG was used)
        contexts          = list()

        if query_response.sources:
            contexts = [chunk.chunk.text for chunk in query_response.sources]
        
        # Run RAGAS evaluation (only if RAGAS enabled)
        ragas_result   = None

        if (settings.ENABLE_RAGAS and state.ragas_evaluator):
            try:
                logger.info("Running RAGAS evaluation...")
                
                ragas_result = state.ragas_evaluator.evaluate_single(query              = message,
                                                                     answer             = query_response.answer,
                                                                     contexts           = contexts,
                                                                     ground_truth       = None,
                                                                     retrieval_time_ms  = int(query_response.retrieval_time_ms),
                                                                     generation_time_ms = int(query_response.generation_time_ms),
                                                                     total_time_ms      = int(query_response.total_time_ms),
                                                                     chunks_retrieved   = len(query_response.sources),
                                                                     query_type         = actual_query_type,
                                                                    )
                
                logger.info(f"RAGAS evaluation complete: type={actual_query_type.upper()}, relevancy={ragas_result.answer_relevancy:.3f}, faithfulness={ragas_result.faithfulness:.3f}, overall={ragas_result.overall_score:.3f}")
            
            except Exception as e:
                logger.error(f"RAGAS evaluation failed: {e}", exc_info = True)
                # Continue without RAGAS metrics - don't fail the request
        
        # Format sources for response
        sources = list()

        for i, chunk_with_score in enumerate(query_response.sources[:5], 1):
            chunk  = chunk_with_score.chunk

            source = {"rank"             : i,
                      "score"            : chunk_with_score.score,
                      "document_id"      : chunk.document_id,
                      "chunk_id"         : chunk.chunk_id,
                      "text_preview"     : chunk.text[:500] + "..." if len(chunk.text) > 500 else chunk.text,
                      "page_number"      : chunk.page_number,
                      "section_title"    : chunk.section_title,
                      "retrieval_method" : chunk_with_score.retrieval_method,
                     }

            sources.append(source)
        
        # Generate session ID if not provided
        if not session_id:
            session_id = f"session_{datetime.now().timestamp()}"
        
        # Determine query type for response metadata
        is_general_query = (actual_query_type == "general")
        
        # Prepare response
        response         = {"session_id"       : session_id,
                            "response"         : query_response.answer,
                            "sources"          : sources,
                            "is_general_query" : is_general_query,
                            "metrics"          : {"retrieval_time"    : int(query_response.retrieval_time_ms),
                                                  "generation_time"   : int(query_response.generation_time_ms),
                                                  "total_time"        : int(query_response.total_time_ms),
                                                  "chunks_retrieved"  : len(query_response.sources),
                                                  "chunks_used"       : len(sources),
                                                  "tokens_used"       : query_response.tokens_used.get("total", 0) if query_response.tokens_used else 0,
                                                  "actual_total_time" : int(total_time),
                                                  "query_type"        : actual_query_type,
                                                  "llm_classified"    : True,  # Now using LLM for classification
                                                 },
                           }
        
        # Add RAGAS metrics if evaluation succeeded
        if ragas_result:
            response["ragas_metrics"] = {"answer_relevancy"   : round(ragas_result.answer_relevancy, 3),
                                         "faithfulness"       : round(ragas_result.faithfulness, 3),
                                         "context_precision"  : round(ragas_result.context_precision, 3) if ragas_result.context_precision else None,
                                         "context_relevancy"  : round(ragas_result.context_relevancy, 3),
                                         "overall_score"      : round(ragas_result.overall_score, 3),
                                         "context_recall"     : round(ragas_result.context_recall, 3) if ragas_result.context_recall else None,
                                         "answer_similarity"  : round(ragas_result.answer_similarity, 3) if ragas_result.answer_similarity else None,
                                         "answer_correctness" : round(ragas_result.answer_correctness, 3) if ragas_result.answer_correctness else None,
                                         "query_type"         : ragas_result.query_type, 
                                        }
        else:
            response["ragas_metrics"] = None
        
        # Store in session
        if session_id not in state.active_sessions:
            state.active_sessions[session_id] = list()
        
        state.active_sessions[session_id].append({"query"            : message,
                                                  "response"         : query_response.answer,
                                                  "sources"          : sources,
                                                  "timestamp"        : datetime.now().isoformat(),
                                                  "metrics"          : response["metrics"],
                                                  "ragas_metrics"    : response.get("ragas_metrics", {}),
                                                  "is_general_query" : is_general_query,
                                                })
        
        # Clear analytics cache when new data is available
        state.analytics_cache.data = None
        
        logger.info(f"Chat response generated successfully in {int(total_time)}ms | (type: {actual_query_type.upper()})")
        
        return response
        
    except Exception as e:
        logger.error(f"Chat error: {e}", exc_info = True)
        
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/configuration")
async def get_configuration():
    """
    Get current configuration
    """
    state        = app.state.app
    
    # Get system health
    health_status = state.get_system_health()
    
    return {"configuration" : {"inference_model"   : settings.OPENAI_MODEL,
                               "embedding_model"   : settings.EMBEDDING_MODEL,
                               "chunking_strategy" : "adaptive",
                               "chunk_size"        : settings.FIXED_CHUNK_SIZE,
                               "chunk_overlap"     : settings.FIXED_CHUNK_OVERLAP,
                               "retrieval_top_k"   : settings.TOP_K_RETRIEVE,
                               "vector_weight"     : settings.VECTOR_WEIGHT,
                               "bm25_weight"       : settings.BM25_WEIGHT,
                               "temperature"       : settings.DEFAULT_TEMPERATURE,
                               "max_tokens"        : settings.MAX_TOKENS,
                               "enable_reranking"  : settings.ENABLE_RERANKING,
                               "is_ready"          : state.is_ready,
                               "llm_healthy"       : health_status["llm"],
                              },
            "health"        : health_status,
           }


@app.post("/api/configuration")
async def update_configuration(temperature: float = Form(None), max_tokens: int = Form(None), retrieval_top_k: int = Form(None),
                               vector_weight: float = Form(None), bm25_weight: float = Form(None), enable_reranking: bool = Form(None),
                               session_id: str = Form(None)):
    """
    Update system configuration (runtime parameters only)
    """
    state = app.state.app
    
    try:
        updates = dict()
        
        # Runtime parameters (no rebuild required)
        if (temperature is not None):
            updates["temperature"] = temperature
        
        if (max_tokens and (max_tokens != settings.MAX_TOKENS)):
            updates["max_tokens"] = max_tokens
        
        if (retrieval_top_k and (retrieval_top_k != settings.TOP_K_RETRIEVE)):
            updates["retrieval_top_k"] = retrieval_top_k
        
        if ((vector_weight is not None) and (vector_weight != settings.VECTOR_WEIGHT)):
            updates["vector_weight"] = vector_weight
            
            # Update hybrid retriever weights
            if bm25_weight is not None:
                state.hybrid_retriever.update_weights(vector_weight, bm25_weight)
        
        if ((bm25_weight is not None) and (bm25_weight != settings.BM25_WEIGHT)):
            updates["bm25_weight"] = bm25_weight
        
        if (enable_reranking is not None):
            updates["enable_reranking"] = enable_reranking
        
        # Store session-based config overrides
        if session_id:
            if session_id not in state.config_overrides:
                state.config_overrides[session_id] = {}
            
            state.config_overrides[session_id].update(updates)
        
        logger.info(f"Configuration updated: {updates}")
        
        # Clear analytics cache since configuration changed
        state.analytics_cache.data = None
        
        return {"success" : True,
                "message" : "Configuration updated successfully",
                "updates" : updates,
               }
        
    except Exception as e:
        logger.error(f"Configuration update error: {e}", exc_info = True)
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/analytics")
async def get_analytics():
    """
    Get comprehensive system analytics and metrics with caching
    """
    state = app.state.app
    
    try:
        # Check cache first
        cached_data = state.analytics_cache.get()
        
        if cached_data:
            cached_data["cache_info"]["from_cache"] = True
            
            return cached_data
        
        # Calculate fresh analytics
        analytics_data = state.calculate_comprehensive_analytics()
        
        # Update cache
        state.analytics_cache.update(analytics_data)
        
        return analytics_data
        
    except Exception as e:
        logger.error(f"Analytics calculation error: {e}", exc_info = True)
        
        # Return basic analytics even if calculation fails
        return {"performance_metrics" : {"avg_response_time" : 0,
                                         "total_queries"     : 0,
                                         "queries_last_hour" : 0,
                                         "error"             : "Could not calculate performance metrics"
                                        },
                "quality_metrics"     : {"answer_relevancy"  : 0.0,
                                         "faithfulness"      : 0.0,
                                         "context_precision" : 0.0,
                                         "overall_score"     : 0.0,
                                         "confidence"        : "low",
                                         "metrics_available" : False,
                                         "error"             : "Could not calculate quality metrics"
                                        },
                "system_information"  : state.get_system_information() if hasattr(state, 'get_system_information') else {},
                "health_status"       : {"overall" : "unknown"},
                "document_statistics" : {"total_documents" : len(state.processed_documents),
                                         "total_chunks"    : sum(len(chunks) for chunks in state.document_chunks.values()),
                                         "uploaded_files"  : len(state.uploaded_files)
                                        },
                "session_statistics"  : {"total_sessions" : len(state.active_sessions),
                                         "total_messages" : sum(len(msgs) for msgs in state.active_sessions.values())
                                        },
                "calculated_at"       : datetime.now().isoformat(),
                "error"               : str(e)
               }


@app.get("/api/analytics/refresh")
async def refresh_analytics():
    """
    Force refresh analytics cache
    """
    state = app.state.app
    
    try:
        # Clear cache
        state.analytics_cache.data = None
        
        # Calculate fresh analytics
        analytics_data             = state.calculate_comprehensive_analytics()
        
        return {"success" : True,
                "message" : "Analytics cache refreshed successfully",
                "data"    : analytics_data,
               }
        
    except Exception as e:
        logger.error(f"Analytics refresh error: {e}", exc_info = True)
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/analytics/detailed")
async def get_detailed_analytics():
    """
    Get detailed analytics including query history and component performance
    """
    state = app.state.app
    
    try:
        # Get basic analytics
        analytics         = await get_analytics()
        
        # Add detailed session information
        detailed_sessions = list()

        for session_id, messages in state.active_sessions.items():
            session_info = {"session_id"            : session_id,
                            "message_count"         : len(messages),
                            "first_message"         : messages[0]["timestamp"] if messages else None,
                            "last_message"          : messages[-1]["timestamp"] if messages else None,
                            "total_response_time"   : sum(msg.get("metrics", {}).get("total_time", 0) for msg in messages),
                            "avg_sources_per_query" : sum(len(msg.get("sources", [])) for msg in messages) / len(messages) if messages else 0,
                           }

            detailed_sessions.append(session_info)
        
        # Add component performance if available
        component_performance = dict()

        if state.hybrid_retriever:
            try:
                retrieval_stats                    = state.hybrid_retriever.get_retrieval_stats()
                component_performance["retrieval"] = retrieval_stats

            except:
                component_performance["retrieval"] = {"error": "Could not retrieve stats"}
        
        if state.embedder:
            try:
                embedder_info                       = state.embedder.get_model_info()
                component_performance["embeddings"] = {"model"     : embedder_info.get("model_name", "unknown"),
                                                       "dimension" : embedder_info.get("embedding_dim", 0),
                                                       "device"    : embedder_info.get("device", "cpu"),
                                                      }
            except:
                component_performance["embeddings"] = {"error": "Could not retrieve stats"}
        
        analytics["detailed_sessions"]     = detailed_sessions
        analytics["component_performance"] = component_performance
        
        return analytics
        
    except Exception as e:
        logger.error(f"Detailed analytics error: {e}", exc_info = True)
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/export-chat/{session_id}")
async def export_chat(session_id: str, format: str = "json"):
    """
    Export chat history
    """
    state = app.state.app
    if session_id not in state.active_sessions:
        raise HTTPException(status_code = 404, 
                            detail      = "Session not found",
                           )

    try:
        chat_history = state.active_sessions[session_id]
        
        if (format == "json"):
            return JSONResponse(content = {"session_id"     : session_id,
                                           "export_time"    : datetime.now().isoformat(),
                                           "total_messages" : len(chat_history),
                                           "history"        : chat_history,
                                          }
                               )

        elif (format == "csv"):
            output = io.StringIO()
            
            if chat_history:
                fieldnames = ["timestamp", "query", "response", "sources_count", "response_time_ms"]
                writer     = csv.DictWriter(output, fieldnames = fieldnames)
                writer.writeheader()
                
                for entry in chat_history:
                    writer.writerow({"timestamp"        : entry.get("timestamp", ""),
                                     "query"            : entry.get("query", ""),
                                     "response"         : entry.get("response", ""),
                                     "sources_count"    : len(entry.get("sources", [])),
                                     "response_time_ms" : entry.get("metrics", {}).get("total_time", 0),
                                   })
            
            return JSONResponse(content = {"csv"        : output.getvalue(),
                                           "session_id" : session_id,
                                           "format"     : "csv",
                                          }
                               )

        else:
            raise HTTPException(status_code = 400, 
                                detail      = "Unsupported format. Use 'json' or 'csv'",
                               )
            
    except Exception as e:
        logger.error(f"Export error: {e}", exc_info = True)
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )
                           

@app.post("/api/cleanup/session/{session_id}")
async def cleanup_session(session_id: str):
    """
    Clean up specific session
    """
    state = app.state.app
    
    if session_id in state.active_sessions:
        del state.active_sessions[session_id]
        
        if session_id in state.config_overrides:
            del state.config_overrides[session_id]
        
        # Check if no sessions left
        if not state.active_sessions:
            logger.info("No active sessions, suggesting vector store cleanup")
            
            return {"success"    : True, 
                    "message"    : f"Session {session_id} cleaned up",
                    "suggestion" : "No active sessions remaining. Consider cleaning vector store.",
                   }
        
        return {"success" : True, 
                "message" : f"Session {session_id} cleaned up",
               }
    
    return {"success" : False, 
            "message" : "Session not found",
           }


@app.post("/api/cleanup/vector-store")
async def cleanup_vector_store():
    """
    Manual vector store cleanup
    """
    state = app.state.app
    
    try:
        # Use cleanup manager
        success = await CleanupManager.full_cleanup(state)
        
        if success:
            return {"success" : True, 
                    "message" : "Vector store and all data cleaned up",
                   }
        
        else:
            return {"success" : False, 
                    "message" : "Cleanup completed with errors",
                   }
            
    except Exception as e:
        logger.error(f"Manual cleanup error: {e}")
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.post("/api/cleanup/full")
async def full_cleanup_endpoint():
    """
    Full system cleanup endpoint
    """
    state = app.state.app
    
    try:
        # Also clean up frontend sessions
        state.active_sessions.clear()
        state.config_overrides.clear()
        
        # Full cleanup
        success = await CleanupManager.full_cleanup(state)
        
        return {"success" : success,
                "message" : "Full system cleanup completed",
                "details" : {"sessions_cleaned" : 0,  # Already cleared above
                             "memory_freed"     : "All application state",
                             "disk_space_freed" : "All vector store and uploaded files",
                            }
               }
        
    except Exception as e:
        logger.error(f"Full cleanup endpoint error: {e}")
        raise HTTPException(status_code = 500, 
                            detail      = str(e),
                           )


@app.get("/api/cleanup/status")
async def get_cleanup_status():
    """
    Get cleanup status and statistics
    """
    state = app.state.app
    
    return {"sessions_active"       : len(state.active_sessions),
            "documents_processed"   : len(state.processed_documents),
            "total_chunks"          : sum(len(chunks) for chunks in state.document_chunks.values()),
            "vector_store_ready"    : state.is_ready,
            "cleanup_registry_size" : len(_cleanup_registry),
            "suggested_action"      : "cleanup_vector_store" if state.is_ready else "upload_documents",
           }


# ============================================================================
# MAIN ENTRY POINT
# ============================================================================
if __name__ == "__main__":
    try:
        # Run the app
        uvicorn.run("app:app",
                    host                      = settings.HOST,
                    port                      = settings.PORT,
                    reload                    = settings.DEBUG,
                    log_level                 = "info",
                    timeout_graceful_shutdown = 10.0,
                    access_log                = False,
                   )
        
    except KeyboardInterrupt:
        logger.info("Keyboard interrupt received - normal shutdown")
    
    except Exception as e:
        logger.error(f"Application crashed: {e}", exc_info = True)
    
    finally:
        # Simple final cleanup
        logger.info("Application stopping, final cleanup...")
        try:
            # Shutdown executor if it exists
            if '_cleanup_executor' in globals():
                _cleanup_executor.shutdown(wait = True)

        except:
            pass
        
        logger.info("Application stopped")