File size: 67,628 Bytes
11d9dfb
 
 
 
 
 
 
 
 
c0310a8
046f392
9fb62ac
11d9dfb
 
046f392
11d9dfb
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
11d9dfb
 
 
 
 
c0310a8
 
5e2e4e3
c0310a8
5e2e4e3
11d9dfb
 
 
 
 
5e2e4e3
11d9dfb
5e2e4e3
11d9dfb
5e2e4e3
11d9dfb
 
 
5e2e4e3
11d9dfb
5e2e4e3
 
9fb62ac
11d9dfb
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
5e2e4e3
 
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fb62ac
 
11d9dfb
 
 
 
 
9fb62ac
11d9dfb
 
 
9fb62ac
 
11d9dfb
 
9fb62ac
11d9dfb
 
9fb62ac
 
 
 
11d9dfb
 
 
 
 
 
 
 
046f392
11d9dfb
 
 
046f392
11d9dfb
046f392
 
9fb62ac
 
 
 
046f392
 
 
 
9fb62ac
 
 
 
 
 
 
046f392
 
 
 
9fb62ac
11d9dfb
046f392
 
 
 
11d9dfb
046f392
 
9fb62ac
 
 
 
 
 
 
 
 
 
 
 
 
 
046f392
 
9fb62ac
046f392
 
 
9fb62ac
046f392
 
 
9fb62ac
046f392
11d9dfb
 
9fb62ac
11d9dfb
 
 
 
9fb62ac
 
 
 
 
 
 
 
11d9dfb
 
5e2e4e3
11d9dfb
 
 
 
 
5e2e4e3
11d9dfb
 
 
 
 
 
 
 
 
 
5e2e4e3
11d9dfb
 
 
 
 
 
 
 
bdb85c2
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
bdb85c2
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
11d9dfb
 
 
 
 
 
5e2e4e3
 
 
 
11d9dfb
 
 
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50c07a8
11d9dfb
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
50c07a8
11d9dfb
50c07a8
11d9dfb
 
50c07a8
11d9dfb
 
 
 
 
 
 
 
5e2e4e3
0651996
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0651996
11d9dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
5e2e4e3
0651996
 
5e2e4e3
11d9dfb
5e2e4e3
 
 
 
11d9dfb
 
 
5e2e4e3
 
 
11d9dfb
 
 
 
 
 
 
 
 
5e2e4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d9dfb
 
 
 
 
 
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
"""
Main Gradio interface for the Professional RAG Assistant.
"""

import gradio as gr
import asyncio
import threading
import time
import json
import sys
import signal
import logging
from typing import Any, Dict, List, Optional, Tuple, Union
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError


def ensure_dict_safe(value: Any) -> Dict[str, Any]:
    """Ensure a value is a safe dictionary."""
    if isinstance(value, dict):
        return value
    elif value is None or value == "" or value == []:
        return {}
    elif isinstance(value, str):
        # Handle HTML-formatted JSON strings from our HTML components
        if value.startswith('<pre>') and value.endswith('</pre>'):
            try:
                json_str = value[5:-6]  # Remove <pre> and </pre> tags
                return json.loads(json_str)
            except:
                return {}
        elif value.startswith('{') and value.endswith('}'):
            try:
                return json.loads(value)
            except:
                return {}
        else:
            return {"value": value}
    elif isinstance(value, (list, tuple)):
        return {"items": list(value)}
    elif isinstance(value, (int, float, bool)):
        return {"value": value}
    else:
        return {"data": str(value)}


def dict_to_html_json(value: Any) -> str:
    """Convert a value to HTML-formatted JSON for display."""
    try:
        safe_dict = ensure_dict_safe(value)
        return f"<pre>{json.dumps(safe_dict, indent=2)}</pre>"
    except Exception:
        return "<pre>{}</pre>"

from .themes import get_theme, get_custom_css
from .components import (
    create_header, create_file_upload_section, create_search_interface,
    create_results_display, create_document_management, create_system_status,
    create_analytics_dashboard, format_document_list, format_search_results,
    create_analytics_charts, format_system_overview, create_error_display,
    create_success_display, create_loading_display
)
from .conversation_components import (
    create_chat_interface, create_chat_history_display, create_chat_input, create_conversation_controls,
    create_conversation_state, create_conversation_info_panel, create_typing_indicator,
    create_conversation_analytics, update_conversation_analytics, update_chat_history,
    format_conversation_response, extract_conversation_stats, get_conversation_css,
    get_conversation_javascript, create_chat_message
)
from .utils import (
    save_uploaded_files, validate_file_types, cleanup_temp_files,
    generate_session_id, format_file_size, parse_search_filters
)

sys.path.append(str(Path(__file__).parent.parent))

from src.rag_system import RAGSystem, EnhancedRAGSystem
from src.error_handler import RAGError
from src.logging_utils import setup_logging, get_safe_logger, sanitize_log_message


class RAGInterface:
    """Main interface class for the RAG system."""
    
    def __init__(self, config_path: str = None, use_enhanced_rag: bool = True):
        """Initialize the RAG interface."""
        self.rag_system: Optional[Union[RAGSystem, EnhancedRAGSystem]] = None
        self.config_path = config_path or "config.yaml"
        self.use_enhanced_rag = use_enhanced_rag
        self.active_sessions: Dict[str, Dict[str, Any]] = {}
        self._initialization_lock = threading.Lock()
        self._initialized = False
        self._conversation_enabled = False
        
        # Setup logging with Unicode safety
        self.logger = get_safe_logger(__name__)
        
        # Initialize RAG system
        self._initialize_rag_system()
        
    def _initialize_rag_system(self) -> None:
        """Initialize the RAG system."""
        try:
            with self._initialization_lock:
                if not self._initialized:
                    if self.use_enhanced_rag:
                        print("Initializing Enhanced RAG system with conversation capabilities...")
                        try:
                            self.rag_system = EnhancedRAGSystem(config_path=self.config_path)
                            self._conversation_enabled = hasattr(self.rag_system, 'process_conversation')
                            print(f"Enhanced RAG system initialized. Conversation enabled: {self._conversation_enabled}")
                        except Exception as e:
                            print(f"Failed to initialize Enhanced RAG system: {e}")
                            print("Falling back to standard RAG system...")
                            self.rag_system = RAGSystem(config_path=self.config_path)
                            self._conversation_enabled = False
                    else:
                        print("Initializing standard RAG system...")
                        self.rag_system = RAGSystem(config_path=self.config_path)
                        self._conversation_enabled = False
                    
                    # Warm up the system
                    warmup_result = self.rag_system.warmup()
                    if warmup_result.get("success"):
                        system_type = "Enhanced RAG" if self._conversation_enabled else "Standard RAG"
                        print(f"{system_type} system initialized and warmed up successfully")
                        self._initialized = True
                    else:
                        print(f"RAG system warmup failed: {warmup_result.get('error', {}).get('message')}")
                        
        except Exception as e:
            print(f"Failed to initialize RAG system: {e}")
            self.rag_system = None
    
    def get_system_status(self) -> str:
        """Get current system status HTML."""
        if not self.rag_system or not self._initialized:
            return create_error_display("System not initialized. Please check configuration and restart.")
        
        try:
            stats_response = self.rag_system.get_system_stats()
            if not stats_response.get("success"):
                return create_error_display(f"Failed to get system status: {stats_response.get('error', {}).get('message')}")
            
            stats = stats_response["data"]
            status_info = stats.get("status", {})
            
            if status_info.get("ready"):
                status_message = f"System ready - {status_info.get('documents_indexed', 0)} documents indexed"
                return create_success_display(status_message)
            else:
                return create_error_display("System not ready")
                
        except Exception as e:
            return create_error_display(f"Error getting system status: {str(e)}")
    
    def process_documents(
        self, 
        files: List[gr.File], 
        session_id: str,
        progress=gr.Progress()
    ) -> Tuple[str, str, bool, str]:
        """Process uploaded documents."""
        if not files:
            return (
                create_error_display("No files uploaded"),
                create_error_display("Please select files to upload"),
                False,  # upload button disabled
                "No documents uploaded yet."
            )
        
        if not self.rag_system or not self._initialized:
            return (
                create_error_display("System not initialized"),
                create_error_display("Please restart the application"),
                False,
                "No documents uploaded yet."
            )
        
        try:
            self.logger.info(f"Starting document upload process - {len(files)} files received")
            
            # Validate file types
            allowed_extensions = [".pdf", ".docx", ".txt"]
            valid_files, validation_errors = validate_file_types(files, allowed_extensions)
            
            if validation_errors:
                self.logger.warning(f"File validation errors: {validation_errors}")
                error_html = create_error_display("\\n".join(validation_errors))
                return error_html, error_html, len(valid_files) > 0, self.get_document_list()
            
            self.logger.info(f"File validation passed - {len(valid_files)} valid files")
            
            # Save uploaded files
            progress(0.1, desc="Saving uploaded files...")
            self.logger.info("Saving uploaded files to temporary directory...")
            saved_files = save_uploaded_files(valid_files)
            
            for file_path, original_name in saved_files:
                file_size = Path(file_path).stat().st_size / (1024 * 1024)  # Size in MB
                self.logger.info(f"Saved file: {original_name} ({file_size:.2f} MB) -> {file_path}")
            
            if not saved_files:
                return (
                    create_error_display("No valid files to process"),
                    create_error_display("Please check your files and try again"),
                    False,
                    self.get_document_list()
                )
            
            # Process each file with timeout
            processed_count = 0
            total_files = len(saved_files)
            results = []
            timeout_seconds = 600  # 10 minutes
            
            def process_single_file(file_path, original_name, session_id):
                """Process a single file - to be run with timeout."""
                self.logger.info(f"Processing file: {original_name}")
                start_time = time.time()
                
                result = self.rag_system.add_document(
                    file_path=file_path,
                    filename=original_name,
                    user_session=session_id
                )
                
                processing_time = time.time() - start_time
                self.logger.info(f"File processing completed: {original_name} (took {processing_time:.2f}s)")
                
                return result
            
            self.logger.info(f"Starting processing of {total_files} files with {timeout_seconds//60}-minute timeout per file")
            
            with ThreadPoolExecutor(max_workers=1) as executor:
                for i, (file_path, original_name) in enumerate(saved_files):
                    progress((i + 1) / total_files * 0.8 + 0.1, desc=f"Processing {original_name}...")
                    self.logger.info(f"Processing file {i+1}/{total_files}: {original_name}")
                    
                    try:
                        # Submit the task with timeout
                        future = executor.submit(process_single_file, file_path, original_name, session_id)
                        result = future.result(timeout=timeout_seconds)
                        
                        if result.get("success"):
                            processed_count += 1
                            chunks_created = result['data']['chunks_created']
                            
                            # Log detailed success info
                            self.logger.info(f"SUCCESS: {original_name} - {chunks_created} chunks created")
                            
                            # Log sample chunk info if available
                            if 'sample_chunks' in result['data']:
                                sample_chunks = result['data']['sample_chunks']
                                self.logger.info(f"Sample chunks from {original_name}:")
                                for idx, chunk in enumerate(sample_chunks[:3]):  # Show first 3 chunks
                                    chunk_preview = chunk['content'][:100] + "..." if len(chunk['content']) > 100 else chunk['content']
                                    self.logger.info(f"  Chunk {idx}: {chunk_preview}")
                            
                            results.append(f"βœ… {original_name}: {chunks_created} chunks created")
                        else:
                            error_msg = result.get("error", {}).get("message", "Unknown error")
                            self.logger.error(f"FAILED: {original_name} - {error_msg}")
                            results.append(f"❌ {original_name}: {error_msg}")
                            
                    except FutureTimeoutError:
                        self.logger.error(f"TIMEOUT: {original_name} exceeded {timeout_seconds//60} minute limit")
                        results.append(f"⏰ {original_name}: Processing timed out after {timeout_seconds//60} minutes")
                        future.cancel()  # Cancel the task if possible
                    except Exception as e:
                        self.logger.error(f"EXCEPTION: {original_name} - {str(e)}")
                        results.append(f"❌ {original_name}: {str(e)}")
            
            progress(1.0, desc="Cleaning up...")
            self.logger.info("Cleaning up temporary files...")
            
            # Clean up temporary files
            cleanup_temp_files([fp for fp, _ in saved_files])
            
            # Log final summary
            total_processing_time = time.time() - time.time()  # This will be updated properly
            self.logger.info(f"Document upload process completed:")
            self.logger.info(f"  - Total files: {total_files}")
            self.logger.info(f"  - Successfully processed: {processed_count}")
            self.logger.info(f"  - Failed: {total_files - processed_count}")
            self.logger.info(f"  - Success rate: {(processed_count/total_files*100):.1f}%")
            
            # Create result message
            if processed_count == total_files:
                self.logger.info(f"[SUCCESS] ALL DOCUMENTS PROCESSED SUCCESSFULLY ({processed_count}/{total_files})")
                status_html = create_success_display(
                    f"Successfully processed {processed_count} documents:\\n" + "\\n".join(results)
                )
                upload_status = create_success_display(f"All {processed_count} documents processed successfully!")
            elif processed_count > 0:
                self.logger.warning(f"[PARTIAL] PARTIAL SUCCESS ({processed_count}/{total_files} documents processed)")
                status_html = f"""
                <div style='background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: 1rem; margin: 1rem 0;'>
                    <div style='font-weight: 600; color: #92400e; margin-bottom: 0.5rem;'>
                        ⚠️ Partially successful ({processed_count}/{total_files} files processed)
                    </div>
                    <div style='color: #78350f; font-size: 0.9rem;'>{"<br>".join(results)}</div>
                </div>
                """
                upload_status = status_html
            else:
                self.logger.error(f"[ERROR] NO DOCUMENTS PROCESSED SUCCESSFULLY (0/{total_files})")
                status_html = create_error_display(
                    f"Failed to process any documents:\\n" + "\\n".join(results)
                )
                upload_status = create_error_display("Document processing failed")
            
            return (
                status_html,
                upload_status,
                gr.update(interactive=True),  # Enable search button
                self.get_document_list()
            )
            
        except Exception as e:
            # Clean up on error
            try:
                if 'saved_files' in locals():
                    cleanup_temp_files([fp for fp, _ in saved_files])
            except:
                pass
            
            error_message = f"Document processing failed: {str(e)}"
            error_html = create_error_display(error_message)
            return error_html, error_html, gr.update(interactive=False), self.get_document_list()
    
    def perform_search(
        self,
        query: str,
        search_mode: str,
        num_results: int,
        enable_reranking: bool,
        metadata_filters: str,
        session_id: str
    ) -> Tuple[str, str, str]:
        """Perform search and return results."""
        if not self.rag_system or not self._initialized:
            error_html = create_error_display("System not initialized")
            return error_html, "{}", ""
        
        if not query or not query.strip():
            error_html = create_error_display("Please enter a search query")
            return error_html, "{}", ""
        
        try:
            # Parse metadata filters
            filters = parse_search_filters(metadata_filters) if metadata_filters else None
            
            # Perform search
            result = self.rag_system.search(
                query=query.strip(),
                k=num_results,
                search_mode=search_mode,
                enable_reranking=enable_reranking,
                metadata_filter=filters,
                user_session=session_id
            )
            
            if not result.get("success"):
                error_msg = result.get("error", {}).get("message", "Search failed")
                error_html = create_error_display(error_msg)
                return error_html, "{}", ""
            
            # Format results
            search_data = result["data"]
            results = search_data.get("results", [])
            search_time = search_data.get("search_time", 0)
            
            # Create HTML display
            results_html, stats_html = format_search_results(results, search_time, query)
            
            # Create JSON data for detailed view
            json_data = {
                "query": query,
                "search_mode": search_mode,
                "results_count": len(results),
                "search_time": search_time,
                "results": results[:5],  # Limit JSON display
                "query_suggestions": search_data.get("query_suggestions", [])
            }
            
            return results_html, json.dumps(json_data, indent=2), stats_html
            
        except Exception as e:
            error_html = create_error_display(f"Search failed: {str(e)}")
            return error_html, "{}", ""
    
    def get_document_list(self) -> str:
        """Get formatted document list."""
        if not self.rag_system or not self._initialized:
            return "<div style='text-align: center; color: #6b7280; padding: 1rem;'>System not initialized</div>"
        
        try:
            result = self.rag_system.get_document_list()
            if result.get("success"):
                documents = result["data"]["documents"]
                return format_document_list(documents)
            else:
                return create_error_display("Failed to load document list")
        except Exception as e:
            return create_error_display(f"Error loading documents: {str(e)}")
    
    def clear_documents(self) -> Tuple[str, str]:
        """Clear all documents."""
        if not self.rag_system or not self._initialized:
            error_html = create_error_display("System not initialized")
            return error_html, error_html
        
        try:
            result = self.rag_system.clear_all_documents()
            if result.get("success"):
                success_msg = f"Cleared {result['data']['documents_removed']} documents"
                success_html = create_success_display(success_msg)
                return success_html, self.get_document_list()
            else:
                error_msg = result.get("error", {}).get("message", "Failed to clear documents")
                error_html = create_error_display(error_msg)
                return error_html, self.get_document_list()
        except Exception as e:
            error_html = create_error_display(f"Error clearing documents: {str(e)}")
            return error_html, self.get_document_list()
    
    def process_conversation(
        self,
        user_message: str,
        chat_history: str,
        session_state: Any = None,
        conversation_context: Any = None,
        mode: str = "hybrid",
        show_sources: bool = True,
        show_suggestions: bool = True,
        progress=gr.Progress()
    ) -> Tuple[str, str, str, str]:
        """
        Process a conversation message.

        Args:
            user_message: User's input message
            chat_history: Current chat history HTML
            session_state: Current session state (can be dict or None)
            conversation_context: Current conversation context (can be dict or None)
            mode: Response mode (conversation, rag, hybrid)
            show_sources: Whether to show sources
            show_suggestions: Whether to show suggestions
            progress: Gradio progress indicator

        Returns:
            Tuple of (updated_chat_history, updated_session_state_html, updated_context_html, empty_input)
        """
        # Handle session_state and conversation_context properly - ensure they're always dicts
        session_state = ensure_dict_safe(session_state)
        conversation_context = ensure_dict_safe(conversation_context)

            
        if not self.rag_system or not self._initialized:
            error_message = "System not initialized. Please check configuration and restart."
            error_html = create_chat_message(content=error_message, role="system")
            updated_history = update_chat_history(chat_history, error_message, "system")
            return updated_history, "", session_state, conversation_context
        
        if not user_message or not user_message.strip():
            return chat_history, "", session_state, conversation_context
        
        try:
            # Show typing indicator
            progress(0.1, desc="Processing your message...")
            
            # Add user message to chat history
            user_message = user_message.strip()
            updated_history = update_chat_history(chat_history, user_message, "user")
            
            # Update session state
            if not session_state.get("session_id"):
                session_state["session_id"] = generate_session_id()
                session_state["started_at"] = time.time()
                session_state["message_count"] = 0
                session_state["user_id"] = f"user_{int(time.time())}"
            
            session_state["message_count"] += 1
            
            progress(0.3, desc="Generating response...")
            
            # Process with enhanced RAG system if available
            conversation_processed = False
            
            if self._conversation_enabled and hasattr(self.rag_system, 'process_conversation'):
                try:
                    # Use enhanced conversation processing
                    result = self.rag_system.process_conversation(
                        user_input=user_message,
                        session_id=session_state["session_id"],
                        user_id=session_state.get("user_id")
                    )
                    
                    progress(0.8, desc="Formatting response...")
                    
                    if result.get("success"):
                        response_data = result["data"]
                        assistant_response = response_data.get("response", "I couldn't generate a response.")
                        confidence = response_data.get("confidence", 0)
                        sources = response_data.get("sources", []) if show_sources else []
                        suggestions = response_data.get("suggestions", []) if show_suggestions else []
                        
                        # Update conversation context
                        processing_info = response_data.get("processing_info", {})
                        conversation_context["last_intent"] = processing_info.get("intent", "unknown")
                        conversation_context["last_route"] = processing_info.get("route", "unknown")
                        conversation_context["last_confidence"] = confidence
                        
                        # Add assistant message to chat history
                        updated_history = update_chat_history(
                            updated_history, 
                            assistant_response, 
                            "assistant",
                            sources=sources,
                            confidence=confidence,
                            suggestions=suggestions
                        )
                        conversation_processed = True
                    else:
                        error_msg = result.get("error", {}).get("message", "Conversation processing failed")
                        self.logger.warning(f"Conversation processing failed: {error_msg}")
                        # Don't show error to user, fall back to simple response instead
                        
                except Exception as e:
                    self.logger.error(f"Exception in conversation processing: {e}")
                    # Don't show error to user, fall back to simple response instead
            
            # Fallback: Simple greeting response for basic interactions
            if not conversation_processed:
                # Check if it's a simple greeting
                greeting_words = ["hi", "hello", "hey", "greetings", "good morning", "good afternoon", "good evening"]
                if any(word in user_message.lower() for word in greeting_words):
                    # Simple greeting response
                    assistant_response = "Hello! I'm your RAG assistant. I can help you search through your documents and answer questions. How can I assist you today?"
                    updated_history = update_chat_history(
                        updated_history,
                        assistant_response,
                        "assistant",
                        suggestions=["What documents do you have?", "How can I search for information?", "What can you help me with?"] if show_suggestions else None
                    )
                    conversation_processed = True
                
            # If still not processed, provide conversational response
            if not conversation_processed:
                # Try to search for relevant information first
                search_result = self.rag_system.search(
                    query=user_message,
                    k=3,
                    search_mode=mode if mode in ["vector", "bm25", "hybrid"] else "hybrid"
                )

                progress(0.8, desc="Generating response...")

                if search_result.get("success"):
                    search_data = search_result["data"]
                    results = search_data.get("results", [])

                    if results:
                        # Generate a conversational response based on the search results
                        best_result = results[0]
                        content_snippet = best_result.get("content", "")[:300]
                        source_name = best_result.get("metadata", {}).get("source", "your documents")

                        response_content = f"Based on {source_name}, I can help with that. {content_snippet}..."

                        if len(results) > 1:
                            response_content += f"\n\nI found {len(results)} related pieces of information that might be helpful."

                        sources = [
                            {
                                "title": result.get("metadata", {}).get("source", "Unknown Source"),
                                "content": result.get("content", "")[:200] + "...",
                                "score": result.get("scores", {}).get("final_score", 0)
                            }
                            for result in results[:2]
                        ] if show_sources else []

                        suggestions = [
                            "Can you tell me more about this?",
                            "What else should I know?",
                            "Are there any related topics?"
                        ] if show_suggestions else []

                        updated_history = update_chat_history(
                            updated_history,
                            response_content,
                            "assistant",
                            sources=sources,
                            suggestions=suggestions
                        )
                    else:
                        # No documents found - provide helpful conversational response
                        response_content = f"I understand you're asking about '{user_message}'. "

                        if hasattr(self.rag_system, 'get_document_list'):
                            doc_result = self.rag_system.get_document_list()
                            if doc_result.get("success") and doc_result["data"]["documents"]:
                                response_content += "I couldn't find specific information about this in your uploaded documents. You might want to try rephrasing your question or asking about topics that are covered in your documents."
                                suggestions = [
                                    "What documents do I have?",
                                    "What topics are covered in my documents?",
                                    "Can you help me search differently?"
                                ] if show_suggestions else []
                            else:
                                response_content += "It looks like you haven't uploaded any documents yet. Upload some documents first, and then I can help answer questions about them!"
                                suggestions = [
                                    "How do I upload documents?",
                                    "What file types do you support?",
                                    "What can you help me with?"
                                ] if show_suggestions else []
                        else:
                            response_content += "I'd be happy to help, but I need more context. Could you provide more details or try rephrasing your question?"
                            suggestions = [
                                "Can you be more specific?",
                                "What exactly are you looking for?",
                                "How can I help you better?"
                            ] if show_suggestions else []

                        updated_history = update_chat_history(
                            updated_history,
                            response_content,
                            "assistant",
                            suggestions=suggestions
                        )
                else:
                    # Search failed - provide conversational fallback
                    response_content = f"I'm having trouble processing your question about '{user_message}' right now. Could you try rephrasing it or asking something else?"
                    suggestions = [
                        "What can you help me with?",
                        "How does this system work?",
                        "Can I try a different question?"
                    ] if show_suggestions else []

                    updated_history = update_chat_history(
                        updated_history,
                        response_content,
                        "assistant",
                        suggestions=suggestions
                    )
            
            progress(1.0, desc="Complete!")
            
            # Ensure HTML-safe return values for display
            return updated_history, dict_to_html_json(session_state), dict_to_html_json(conversation_context), ""

        except Exception as e:
            error_msg = f"Error processing conversation: {str(e)}"
            updated_history = update_chat_history(chat_history, error_msg, "system")

            # Ensure HTML-safe return values in error case
            return updated_history, dict_to_html_json(session_state), dict_to_html_json(conversation_context), ""
    
    def clear_conversation(
        self,
        session_state: Any = None
    ) -> Tuple[str, Dict[str, Any], Dict[str, Any]]:
        """
        Clear the conversation and reset state.
        
        Args:
            session_state: Current session state (can be dict or None)
            
        Returns:
            Tuple of (new_chat_history, reset_session_state, reset_context)
        """
        # Handle session_state properly
        session_state = ensure_dict_safe(session_state)
            
        try:
            # Clear conversation session in enhanced RAG system if available
            if (self._conversation_enabled and 
                hasattr(self.rag_system, 'clear_conversation_session') and 
                session_state.get("session_id")):
                
                self.rag_system.clear_conversation_session(session_state["session_id"])
            
            # Reset states
            new_session_state = {
                "session_id": None,
                "user_id": None,
                "started_at": None,
                "message_count": 0
            }
            
            new_context = {
                "mentioned_entities": [],
                "active_topics": [],
                "last_query_type": None,
                "document_context": {}
            }
            
            # Create fresh chat history - get the HTML content directly
            initial_html = """
    <div class="chat-container" id="chat-container">
        <div class="chat-welcome">
            <div class="welcome-icon">πŸ’¬</div>
            <h3>Welcome to the RAG Assistant!</h3>
            <p>Ask questions about your documents or start a conversation. I can help you find information, explain concepts, and provide detailed answers based on your uploaded documents.</p>
            <div class="quick-actions">
                <button class="quick-action-button" onclick="sendSuggestion('What documents do I have uploaded?')">πŸ“ View my documents</button>
                <button class="quick-action-button" onclick="sendSuggestion('Summarize the main topics in my documents')">πŸ“ Summarize topics</button>
                <button class="quick-action-button" onclick="sendSuggestion('Help me understand a concept')">πŸ” Explain a concept</button>
            </div>
        </div>
    </div>
    """
            new_chat_history = initial_html

            return new_chat_history, dict_to_html_json(new_session_state), dict_to_html_json(new_context)

        except Exception as e:
            print(f"Error clearing conversation: {e}")
            # Still return reset values even if clearing failed
            initial_html = """
    <div class="chat-container" id="chat-container">
        <div class="chat-welcome">
            <div class="welcome-icon">πŸ’¬</div>
            <h3>Welcome to the RAG Assistant!</h3>
            <p>Ask questions about your documents or start a conversation. I can help you find information, explain concepts, and provide detailed answers based on your uploaded documents.</p>
            <div class="quick-actions">
                <button class="quick-action-button" onclick="sendSuggestion('What documents do I have uploaded?')">πŸ“ View my documents</button>
                <button class="quick-action-button" onclick="sendSuggestion('Summarize the main topics in my documents')">πŸ“ Summarize topics</button>
                <button class="quick-action-button" onclick="sendSuggestion('Help me understand a concept')">πŸ” Explain a concept</button>
            </div>
        </div>
    </div>
    """
            new_chat_history = initial_html
            new_session_state = {"session_id": None, "user_id": None, "started_at": None, "message_count": 0}
            new_context = {"mentioned_entities": [], "active_topics": [], "last_query_type": None, "document_context": {}}
            
            return new_chat_history, dict_to_html_json(new_session_state), dict_to_html_json(new_context)
    
    def get_analytics_data(self) -> Tuple[str, gr.Plot, gr.Plot, List[List[str]]]:
        """Get analytics dashboard data."""
        if not self.rag_system or not self._initialized:
            return (
                create_error_display("System not initialized"),
                gr.Plot(),
                gr.Plot(),
                []
            )
        
        try:
            result = self.rag_system.get_analytics_dashboard()
            if not result.get("success"):
                error_html = create_error_display("Failed to load analytics data")
                return error_html, gr.Plot(), gr.Plot(), []
            
            analytics_data = result["data"]
            
            # Format system overview
            overview_html = format_system_overview(analytics_data)
            
            # Create charts
            query_chart, modes_chart = create_analytics_charts(analytics_data)
            
            # Create activity table data
            activity_data = []
            system_data = analytics_data.get("system", {})
            
            activity_data.append([
                "System Started",
                "System Initialization",
                f"Uptime: {system_data.get('uptime_hours', 0):.1f} hours",
                "βœ… Active"
            ])
            
            if system_data.get("total_queries", 0) > 0:
                activity_data.append([
                    "Recent",
                    "Search Queries",
                    f"{system_data.get('total_queries')} total queries",
                    "πŸ“Š Active"
                ])
            
            # Add conversation metrics if enhanced system is enabled
            if self._conversation_enabled and hasattr(self.rag_system, 'conversation_manager'):
                try:
                    conversation_stats = self.rag_system.conversation_manager.get_session_statistics()
                    if conversation_stats.get("active_sessions", 0) > 0:
                        activity_data.append([
                            "Now",
                            "Active Conversations",
                            f"{conversation_stats.get('active_sessions', 0)} sessions",
                            "πŸ’¬ Active"
                        ])
                    
                    total_conversations = conversation_stats.get("total_conversations", 0)
                    if total_conversations > 0:
                        activity_data.append([
                            "Recent",
                            "Conversation Sessions",
                            f"{total_conversations} total conversations",
                            "πŸ’¬ Complete"
                        ])
                        
                    total_messages = conversation_stats.get("total_messages", 0)
                    if total_messages > 0:
                        activity_data.append([
                            "Recent",
                            "Chat Messages",
                            f"{total_messages} messages exchanged",
                            "πŸ“ Active"
                        ])
                except Exception as e:
                    self.logger.warning(f"Could not get conversation statistics: {e}")
            
            if system_data.get("total_documents_processed", 0) > 0:
                activity_data.append([
                    "Recent",
                    "Document Processing",
                    f"{system_data.get('total_documents_processed')} documents processed",
                    "πŸ“„ Complete"
                ])
            
            return overview_html, query_chart, modes_chart, activity_data
            
        except Exception as e:
            error_html = create_error_display(f"Error loading analytics: {str(e)}")
            return error_html, gr.Plot(), gr.Plot(), []
    
    def create_interface(self) -> gr.Blocks:
        """Create the main Gradio interface."""
        theme = get_theme()
        css = get_custom_css()
        
        # Add conversation CSS if conversation is enabled
        if self._conversation_enabled:
            css += "\n" + get_conversation_css()
        
        with gr.Blocks(
            theme=theme,
            css=css,
            title="Professional RAG Assistant",
            analytics_enabled=False
        ) as interface:
            
            # Add JavaScript for conversation if enabled
            if self._conversation_enabled:
                gr.HTML(get_conversation_javascript())
            # Session state
            session_id_state = gr.State(value=generate_session_id())
            
            # Header
            create_header()
            
            # System status
            system_status = create_system_status()
            
            # Main tabs
            with gr.Tabs() as main_tabs:
                # Chat Tab
                with gr.Tab("πŸ’¬ Chat", id="chat"):
                    gr.Markdown("""
                    ## πŸ€– **Intelligent Document Chat**

                    **Talk to your documents naturally!** This AI-powered chat interface understands your questions and provides intelligent responses based on your uploaded documents.

                    ✨ **Key Features:**
                    - πŸ’¬ **Natural Conversation**: Ask questions in plain English
                    - 🎯 **Smart Responses**: Choose conversation, RAG, or hybrid modes
                    - πŸ“š **Source Citations**: See exactly where information comes from
                    - πŸ’‘ **Follow-up Suggestions**: Get AI-generated next questions

                    πŸš€ **Get Started:** Upload documents first, then return here to start chatting!
                    """)
                    
                    # Chat interface components
                    chat_components = create_chat_interface()
                    chat_history_display, chat_input, send_button, clear_chat_button, session_state_display = chat_components[:5]
                    conversation_context_display, mode_selector, show_sources_checkbox, show_suggestions_checkbox = chat_components[5:]
                    
                    with gr.Row():
                        with gr.Column(scale=3):
                            chat_history_display
                            
                            with gr.Row():
                                chat_input
                                send_button
                            
                            with gr.Row():
                                clear_chat_button
                                mode_selector
                        
                        with gr.Column(scale=1):
                            with gr.Accordion("Chat Options", open=True):
                                show_sources_checkbox
                                show_suggestions_checkbox

                    # Hidden debug components - placed outside visible UI but still accessible for event handling
                    with gr.Row(visible=False):
                        session_state_display
                        conversation_context_display
                
                # Document Upload Tab
                with gr.Tab("πŸ“ Document Upload", id="upload"):
                    gr.Markdown("""
                    ## πŸ“ **Document Upload & Processing**

                    **Build your intelligent knowledge base!** Upload your documents and let our AI process them for instant search and conversation capabilities.

                    πŸ“„ **Supported Formats:**
                    - πŸ“Š **PDF files** - Research papers, reports, manuals (up to 50MB each)
                    - πŸ“ **DOCX files** - Word documents, proposals, notes
                    - πŸ“ƒ **TXT files** - Plain text, transcripts, code files

                    ⚑ **Smart Processing:**
                    - 🧠 **Intelligent chunking** with context preservation
                    - πŸ“Š **Metadata extraction** for better organization
                    - 🎯 **Vector embeddings** for semantic search
                    - ⏱️ **Real-time progress** tracking

                    πŸ’‘ **Pro Tip:** Upload related documents together for better cross-document insights!
                    """)
                    
                    file_upload, upload_status, upload_button = create_file_upload_section()
                    
                    with gr.Accordion("Upload Settings", open=False):
                        gr.Markdown("""
                        **Supported formats:** PDF, DOCX, TXT  
                        **Maximum file size:** 50MB per file  
                        **Processing:** Documents are split into chunks and indexed for search
                        """)
                
                # Search Tab
                with gr.Tab("πŸ” Search", id="search"):
                    gr.Markdown("""
                    ## πŸ” **Advanced Document Search**

                    **Find exactly what you need!** Our hybrid AI search combines vector similarity and keyword matching for superior results.

                    🎯 **Search Capabilities:**
                    - 🧠 **Semantic Search** - Understands meaning, not just keywords
                    - πŸ“ **Keyword Search** - Traditional exact text matching
                    - πŸ”€ **Hybrid Mode** - Best of both worlds (recommended)
                    - πŸ“Š **Smart Re-ranking** - Improves relevance with cross-encoders

                    βš™οΈ **Advanced Features:**
                    - πŸŽ›οΈ **Configurable parameters** - Adjust search weights and result count
                    - 🏷️ **Metadata filtering** - Filter by document properties
                    - πŸ“ˆ **Relevance scoring** - See confidence levels for each result
                    - πŸ“‹ **JSON export** - Raw data for technical analysis

                    πŸ’‘ **Perfect for:** Research, fact-finding, and detailed document analysis
                    """)
                    
                    with gr.Row():
                        with gr.Column(scale=4):
                            search_components = create_search_interface()
                            search_query, search_controls, search_button = search_components[:3]
                            search_mode, num_results, enable_reranking = search_components[3:]
                        
                        with gr.Column(scale=1):
                            with gr.Accordion("Advanced Options", open=False):
                                metadata_filters = gr.Textbox(
                                    label="Metadata Filters",
                                    placeholder='{"source": "document.pdf"}',
                                    lines=3,
                                    info="JSON or key:value,key2:value2 format"
                                )
                    
                    # Results display
                    results_html, results_json, search_stats = create_results_display()
                    
                    with gr.Accordion("Detailed Results (JSON)", open=False):
                        results_json
                
                # Document Management Tab
                with gr.Tab("πŸ“š Documents", id="documents"):
                    gr.Markdown("""
                    ## πŸ“š **Document Library Manager**

                    **Organize your knowledge base!** View, manage, and monitor all your uploaded documents in one central location.

                    πŸ“Š **Document Overview:**
                    - πŸ“„ **File Details** - Name, size, format, and upload date
                    - 🧩 **Processing Stats** - Number of chunks and processing status
                    - πŸ” **Search Performance** - Track which documents are most useful
                    - πŸ“ˆ **Usage Analytics** - See query patterns and access frequency

                    πŸ› οΈ **Management Tools:**
                    - πŸ—‘οΈ **Individual Removal** - Delete specific documents
                    - 🧹 **Bulk Clear** - Remove all documents at once
                    - πŸ”„ **Refresh Status** - Update document list and statistics
                    - πŸ“‹ **Export List** - Get document inventory

                    πŸ’‘ **Best Practice:** Regularly review and organize your document library for optimal performance
                    """)
                    
                    document_list, refresh_docs_btn, clear_docs_btn = create_document_management()
                
                # Analytics Tab
                with gr.Tab("πŸ“Š Analytics", id="analytics"):
                    gr.Markdown("""
                    ## πŸ“Š **System Analytics & Insights**

                    **Monitor your RAG system performance!** Track usage patterns, system health, and optimization opportunities.

                    πŸ“ˆ **Performance Metrics:**
                    - ⚑ **Response Times** - Average query processing speed
                    - πŸ” **Search Accuracy** - Relevance scores and success rates
                    - πŸ’¬ **Chat Analytics** - Conversation patterns and engagement
                    - πŸ“Š **System Health** - Memory usage and processing efficiency

                    🎯 **Usage Insights:**
                    - πŸ”₯ **Popular Queries** - Most frequently asked questions
                    - πŸ“„ **Document Utilization** - Which documents are accessed most
                    - 🎭 **Mode Preferences** - Conversation vs RAG vs Hybrid usage
                    - ⏰ **Activity Patterns** - Peak usage times and trends

                    πŸ› οΈ **Optimization Tools:**
                    - πŸ“‹ **Performance Reports** - Detailed analytics export
                    - πŸ”„ **Real-time Monitoring** - Live system status updates
                    - πŸ’‘ **Recommendations** - AI-suggested improvements
                    - πŸ“ˆ **Trend Analysis** - Historical performance tracking

                    πŸ’‘ **Use this data to:** Optimize document libraries, improve search strategies, and enhance user experience
                    """)
                    
                    analytics_components = create_analytics_dashboard()
                    system_overview, query_chart, search_modes_chart, activity_table = analytics_components
                    
                    with gr.Row():
                        with gr.Column():
                            query_chart
                        with gr.Column():
                            search_modes_chart
                    
                    with gr.Accordion("Recent Activity", open=False):
                        activity_table
                    
                    refresh_analytics_btn = gr.Button("Refresh Analytics", variant="secondary")
            
            # Event handlers
            
            # File upload events
            file_upload.change(
                fn=lambda files: (
                    create_success_display(f"βœ… {len(files)} file(s) selected! Click the green 'πŸš€ Process Documents' button below to continue.") if files and len(files) > 0 else "<div style='text-align: center; color: #6b7280; padding: 1rem;'>πŸ“ No files selected</div>",
                    gr.update(interactive=files is not None and len(files) > 0)
                ),
                inputs=[file_upload],
                outputs=[upload_status, upload_button],
                show_progress=False
            )
            
            upload_button.click(
                fn=self.process_documents,
                inputs=[file_upload, session_id_state],
                outputs=[upload_status, system_status, search_button, document_list],
                show_progress=True
            )
            
            # Search events
            search_query.change(
                fn=lambda query: gr.update(interactive=len(query.strip()) > 0 if query else False),
                inputs=[search_query],
                outputs=[search_button],
                show_progress=False
            )
            
            search_button.click(
                fn=lambda: create_loading_display("Searching..."),
                inputs=[],
                outputs=[results_html],
                show_progress=False
            ).then(
                fn=self.perform_search,
                inputs=[
                    search_query, search_mode, num_results,
                    enable_reranking, metadata_filters, session_id_state
                ],
                outputs=[results_html, results_json, search_stats],
                show_progress=True
            )
            
            # Document management events
            refresh_docs_btn.click(
                fn=self.get_document_list,
                inputs=[],
                outputs=[document_list],
                show_progress=False
            )
            
            clear_docs_btn.click(
                fn=self.clear_documents,
                inputs=[],
                outputs=[system_status, document_list],
                show_progress=True
            )
            
            # Analytics events
            refresh_analytics_btn.click(
                fn=self.get_analytics_data,
                inputs=[],
                outputs=[system_overview, query_chart, search_modes_chart, activity_table],
                show_progress=True
            )
            
            # Chat events - full RAG with duplicate prevention
            def handle_chat_submit(message, history, mode, show_sources, show_suggestions):
                # Prevent empty messages
                if not message or not message.strip():
                    return history, dict_to_html_json({}), dict_to_html_json({}), ""

                user_message = message.strip()

                # Initialize session state
                session_state = {
                    "session_id": f"session_{int(time.time())}",
                    "message_count": 1
                }
                conversation_context = {}

                # Generate intelligent response
                try:
                    # Check for greetings first
                    greeting_words = ["hi", "hello", "hey", "greetings", "good morning", "good afternoon", "good evening"]
                    if any(word in user_message.lower() for word in greeting_words):
                        response = "Hello! I'm your RAG assistant. I can help you search through your documents and answer questions. How can I assist you today?"
                        suggestions = ["What documents do you have?", "How can I search for information?", "What can you help me with?"] if show_suggestions else []
                        sources = []

                    # Try to search for relevant information
                    elif self.rag_system and self._initialized:
                        search_result = self.rag_system.search(
                            query=user_message,
                            k=3,
                            search_mode=mode if mode in ["vector", "bm25", "hybrid"] else "hybrid"
                        )

                        if search_result.get("success"):
                            results = search_result["data"].get("results", [])

                            if results:
                                # Generate conversational response from search results
                                best_result = results[0]
                                content_snippet = best_result.get("content", "")[:300]
                                source_name = best_result.get("metadata", {}).get("source", "your documents")

                                response = f"Based on {source_name}, I can help with that. {content_snippet}..."
                                if len(results) > 1:
                                    response += f"\n\nI found {len(results)} related pieces of information that might be helpful."

                                sources = [
                                    {
                                        "title": result.get("metadata", {}).get("source", "Unknown Source"),
                                        "content": result.get("content", "")[:200] + "...",
                                        "score": result.get("scores", {}).get("final_score", 0)
                                    }
                                    for result in results[:2]
                                ] if show_sources else []

                                suggestions = [
                                    "Can you tell me more about this?",
                                    "What else should I know?",
                                    "Are there any related topics?"
                                ] if show_suggestions else []
                            else:
                                # No search results found
                                doc_result = self.rag_system.get_document_list()
                                if doc_result.get("success") and doc_result["data"]["documents"]:
                                    response = f"I understand you're asking about '{user_message}'. I couldn't find specific information about this in your uploaded documents. You might want to try rephrasing your question or asking about topics that are covered in your documents."
                                    suggestions = [
                                        "What documents do I have?",
                                        "What topics are covered in my documents?",
                                        "Can you help me search differently?"
                                    ] if show_suggestions else []
                                else:
                                    response = f"I understand you're asking about '{user_message}'. It looks like you haven't uploaded any documents yet. Upload some documents first, and then I can help answer questions about them!"
                                    suggestions = [
                                        "How do I upload documents?",
                                        "What file types do you support?",
                                        "What can you help me with?"
                                    ] if show_suggestions else []
                                sources = []
                        else:
                            response = f"I'm having trouble processing your question about '{user_message}' right now. Could you try rephrasing it or asking something else?"
                            suggestions = [
                                "What can you help me with?",
                                "How does this system work?",
                                "Can I try a different question?"
                            ] if show_suggestions else []
                            sources = []
                    else:
                        response = "The system is not ready yet. Please check the configuration and try again."
                        suggestions = []
                        sources = []

                except Exception as e:
                    response = f"I encountered an error processing your message. Please try again."
                    suggestions = ["Can you try rephrasing?", "What else can I help with?"] if show_suggestions else []
                    sources = []

                # Build complete chat history from scratch to prevent duplicates
                new_history = f"""
                <div class="chat-container" id="chat-container">
                    <div class="message user-message">
                        <div class="message-content">{user_message}</div>
                    </div>
                    <div class="message assistant-message">
                        <div class="message-content">{response}</div>"""

                # Add sources if available
                if sources:
                    new_history += """
                        <div class="message-sources">
                            <h4>πŸ“š Sources:</h4>
                            <div class="sources-list">"""
                    for source in sources:
                        new_history += f"""
                                <div class="source-item">
                                    <div class="source-header">
                                        <span class="source-title">{source['title']}</span>
                                        <span class="source-score">{source['score']:.1%}</span>
                                    </div>
                                    <div class="source-preview">{source['content']}</div>
                                </div>"""
                    new_history += """
                            </div>
                        </div>"""

                # Add suggestions if available
                if suggestions:
                    new_history += """
                        <div class="message-suggestions">
                            <h4>πŸ’‘ Suggestions:</h4>
                            <div class="suggestions-list">"""
                    for suggestion in suggestions:
                        new_history += f"""
                                <button class="suggestion-button" onclick="sendSuggestion('{suggestion}')">{suggestion}</button>"""
                    new_history += """
                            </div>
                        </div>"""

                new_history += """
                    </div>
                </div>
                """

                return new_history, dict_to_html_json(session_state), dict_to_html_json(conversation_context), ""
                
            chat_input.submit(
                fn=handle_chat_submit,
                inputs=[
                    chat_input, chat_history_display, mode_selector,
                    show_sources_checkbox, show_suggestions_checkbox
                ],
                outputs=[
                    chat_history_display, session_state_display,
                    conversation_context_display, chat_input
                ],
                show_progress=True
            )
            
            send_button.click(
                fn=handle_chat_submit,
                inputs=[
                    chat_input, chat_history_display, mode_selector,
                    show_sources_checkbox, show_suggestions_checkbox
                ],
                outputs=[
                    chat_history_display, session_state_display,
                    conversation_context_display, chat_input
                ],
                show_progress=True
            )
            
            def handle_clear_chat():
                # Return fresh chat history
                initial_html = """
    <div class="chat-container" id="chat-container">
        <div class="chat-welcome">
            <div class="welcome-icon">πŸ€–</div>
            <h3>Welcome to Your Intelligent Document Assistant!</h3>
            <p>🎯 <strong>What I can do for you:</strong></p>
            <ul style="text-align: left; max-width: 600px; margin: 0 auto 1.5rem;">
                <li>πŸ’¬ <strong>Chat naturally</strong> about your documents - ask questions in plain English</li>
                <li>πŸ” <strong>Find specific information</strong> instantly from your uploaded files</li>
                <li>πŸ“Š <strong>Summarize content</strong> and explain complex concepts</li>
                <li>🎨 <strong>Choose response modes</strong> - conversational, technical, or hybrid</li>
            </ul>
            <p style="color: #6b7280; font-size: 0.9rem; margin-bottom: 1.5rem;">
                πŸ’‘ <em>New here? Start by uploading documents in the "πŸ“ Document Upload" tab, then come back to chat!</em>
            </p>
            <div class="quick-actions">
                <h4 style="margin: 0 0 1rem; color: #374151;">πŸš€ Try these to get started:</h4>
                <button class="quick-action-button" onclick="sendSuggestion('Hello! What can you help me with?')">πŸ‘‹ Say hello</button>
                <button class="quick-action-button" onclick="sendSuggestion('What documents do I have uploaded?')">πŸ“ Check my documents</button>
                <button class="quick-action-button" onclick="sendSuggestion('Summarize the main topics in my documents')">πŸ“ Summarize content</button>
                <button class="quick-action-button" onclick="sendSuggestion('How does this system work?')">❓ Learn how it works</button>
            </div>
        </div>
    </div>
    """
                return initial_html, dict_to_html_json({}), dict_to_html_json({})
                
            clear_chat_button.click(
                fn=handle_clear_chat,
                inputs=[],
                outputs=[chat_history_display, session_state_display, conversation_context_display],
                show_progress=False
            )
            
            # Enable chat input when message is typed
            chat_input.change(
                fn=lambda message: gr.update(interactive=len(message.strip()) > 0 if message else False),
                inputs=[chat_input],
                outputs=[send_button],
                show_progress=False
            )
            
            # Initialize interface
            interface.load(
                fn=lambda: (
                    self.get_system_status(),
                    "<div style='text-align: center; color: #6b7280; padding: 1rem;'>πŸ“ No files selected</div>",  # Initial upload status
                    gr.update(interactive=False),  # Upload button disabled initially
                    gr.update(interactive=False),  # Search button disabled initially
                    gr.update(interactive=False),  # Send button disabled initially
                    self.get_document_list(),
                    *self.get_analytics_data(),
                    "",  # Initial chat history
                    dict_to_html_json({}),  # Initial session state
                    dict_to_html_json({})   # Initial conversation context
                ),
                inputs=[],
                outputs=[
                    system_status, upload_status, upload_button, search_button, send_button, document_list,
                    system_overview, query_chart, search_modes_chart, activity_table,
                    chat_history_display, session_state_display, conversation_context_display
                ],
                show_progress=False
            )
        
        return interface


def create_interface(config_path: str = None) -> gr.Blocks:
    """Create and return the RAG interface."""
    try:
        # Setup logging configuration first
        import yaml
        config_file = config_path or "config.yaml"
        try:
            with open(config_file, 'r') as f:
                config = yaml.safe_load(f)
            setup_logging(config)
        except Exception as e:
            print(f"Warning: Could not setup logging from config: {e}")
        
        # Create interface
        rag_interface = RAGInterface(config_path)
        return rag_interface.create_interface()
    except Exception as e:
        print(f"Error creating interface: {e}")
        raise


if __name__ == "__main__":
    # For testing
    interface = create_interface()
    interface.launch(debug=True)