File size: 62,706 Bytes
f0b765c
 
838cd23
 
f0b765c
 
838cd23
 
 
 
 
 
 
 
4b28fb0
 
 
838cd23
4b28fb0
 
2d4c5b0
f0b765c
 
2d4c5b0
838cd23
 
 
 
4b28fb0
 
 
 
 
 
 
838cd23
77068ee
 
 
7d886a8
 
 
 
 
 
c4b1964
 
69fcd44
7d886a8
 
69fcd44
7d886a8
 
69fcd44
 
 
 
 
 
 
 
7d886a8
69fcd44
7d886a8
 
 
 
 
 
e3a1eb8
7d886a8
04aa1ba
4b28fb0
 
 
7d886a8
 
 
c4b1964
4b28fb0
 
7d886a8
 
 
 
 
69fcd44
f5d3b25
 
 
 
 
 
 
 
 
 
 
2d4c5b0
 
 
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d4c5b0
4b28fb0
 
 
 
 
 
2d4c5b0
439ebb4
 
 
 
 
 
04aa1ba
 
439ebb4
 
04aa1ba
439ebb4
 
04aa1ba
 
 
 
 
 
 
 
 
 
 
69fcd44
 
 
 
 
 
 
7d886a8
e3dd1d2
 
69fcd44
e3dd1d2
dca2bc9
e3dd1d2
69fcd44
e3dd1d2
69fcd44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dd1d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69fcd44
 
 
e3dd1d2
838cd23
e3dd1d2
69fcd44
 
e3dd1d2
ea56470
c4b1964
ea56470
e3dd1d2
ea56470
 
 
 
e3dd1d2
ea56470
 
 
7d886a8
69fcd44
7d886a8
 
e3dd1d2
ea56470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838cd23
ea56470
 
 
e3dd1d2
 
ea56470
e3dd1d2
ea56470
e3dd1d2
ea56470
 
 
e3dd1d2
ea56470
 
 
 
 
 
 
 
 
 
 
e3dd1d2
ea56470
e3dd1d2
 
 
 
 
 
 
 
 
 
 
 
ea56470
 
 
 
 
e3dd1d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea56470
 
 
 
 
 
 
e3dd1d2
 
 
 
 
69fcd44
7d886a8
00fd6a4
 
 
 
 
 
 
69fcd44
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00fd6a4
7d886a8
 
f5d3b25
 
 
1d4dc07
 
 
838cd23
 
1d4dc07
 
 
 
 
 
 
f5d3b25
7d886a8
 
1d4dc07
 
 
 
69fcd44
1d4dc07
 
04aa1ba
 
 
1d4dc07
 
 
 
 
7d886a8
838cd23
 
 
 
 
1d4dc07
838cd23
1d4dc07
 
 
 
 
 
 
 
838cd23
1d4dc07
 
 
 
838cd23
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
1d4dc07
 
 
 
 
04aa1ba
1d4dc07
 
 
 
4b28fb0
 
 
 
 
1d4dc07
4b28fb0
1d4dc07
4b28fb0
 
 
1d4dc07
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4dc07
 
 
4b28fb0
 
 
 
 
 
 
 
1d4dc07
4b28fb0
 
 
 
 
 
 
f5d3b25
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
1d4dc07
 
 
 
 
 
 
7d886a8
1d4dc07
 
f5d3b25
4b28fb0
 
 
7d886a8
 
1d4dc07
 
7d886a8
1d4dc07
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
1d4dc07
 
c4b1964
7d886a8
 
 
c4b1964
69fcd44
7d886a8
e3dd1d2
 
7d886a8
 
 
 
1d4dc07
 
 
 
838cd23
1d4dc07
 
 
 
 
 
 
 
 
 
838cd23
 
1d4dc07
04aa1ba
1d4dc07
 
04aa1ba
838cd23
04aa1ba
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439ebb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439ebb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
838cd23
04aa1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
838cd23
04aa1ba
 
 
 
 
 
 
 
 
 
838cd23
04aa1ba
 
 
 
 
 
1d4dc07
04aa1ba
 
1d4dc07
838cd23
 
 
 
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
 
 
 
 
 
1d4dc07
04aa1ba
1d4dc07
 
04aa1ba
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
1d4dc07
 
 
04aa1ba
1d4dc07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04aa1ba
 
 
 
1d4dc07
 
 
04aa1ba
1d4dc07
 
 
 
 
 
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96e9099
 
c4b1964
 
f5d3b25
c4b1964
f5d3b25
 
 
96e9099
69fcd44
96e9099
 
 
1d4dc07
 
04aa1ba
 
 
1d4dc07
4b28fb0
 
96e9099
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
c4b1964
 
 
69fcd44
f5d3b25
 
 
 
 
 
 
 
 
69fcd44
7d886a8
838cd23
69fcd44
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
from fastapi import FastAPI, HTTPException, Header, Response
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import google.generativeai as genai
import httpx
import os
from dotenv import load_dotenv
from duckduckgo_search import DDGS
from typing import Optional, List, Dict, Any
import logging
import re
import asyncio
import threading
import time
import hashlib
import json
from functools import wraps
from collections import OrderedDict
from dataclasses import dataclass, field

# Load environment variables from .env file
load_dotenv()


import spacy
from rake_nltk import Rake
import nltk
from cache.chromadb_cache import ChromaDBSearchCache
from search_optimizer import (
    has_meaningful_conversation_history,
    hybrid_search_decision,
    extract_search_terms,
    format_search_context
)

nltk.download('stopwords')
nltk.download('punkt_tab')

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="Enhanced Chat API with Dynamic Model Selection",
    description="API with query classification and dynamic model loading for QA/Summarization",
    version="3.0.0"
)

# Configure CORS with restricted origins for security
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://huggingface.co",
        "https://*.hf.space",
        "http://localhost:3000",
        "http://localhost:8000",
        "http://127.0.0.1:3000",
        "http://127.0.0.1:8000"
    ],
    allow_methods=["POST", "GET"],
    allow_headers=["Content-Type", "Authorization"],
)

# Request/Response models
class ChatRequest(BaseModel):
    prompt: str
    max_new_tokens: int = 500
    use_search: bool = True
    temperature: float = 0.7
    user_id: Optional[str] = None
    history: Optional[List[Dict[str, str]]] = None
    force_search: Optional[bool] = None
    search_decision_mode: str = "balanced"  # conservative, balanced, aggressive

class ChatResponse(BaseModel):
    response: str
    search_results: Optional[List[Dict[str, Any]]] = None
    search_decision: Optional[Dict[str, Any]] = None
    cache_info: Optional[Dict[str, Any]] = None

class SearchRequest(BaseModel):
    query: str
    max_results: int = 5


# Configure Google AI
try:
    genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
except KeyError:
    logger.error("CRITICAL: GOOGLE_API_KEY environment variable not set.")
    raise # Exit if API key is not set

# Initialize the Generative Model
model = genai.GenerativeModel('gemini-1.5-flash')

# Global NLP tools
nlp = spacy.load("en_core_web_sm")
rake = Rake()

# ===== Phase 3c: ChromaDB Vector Database Cache System =====

# Universal ChromaDB search cache - single global instance for all users
# Vector database provides better semantic matching and persistent storage
universal_search_cache = None

def get_universal_cache() -> ChromaDBSearchCache:
    """Get the universal ChromaDB search cache instance"""
    global universal_search_cache
    if universal_search_cache is None:
        # Initialize ChromaDB cache with environment configuration
        cache_db_path = os.getenv('CHROMADB_PATH', 'cache_db')
        cache_results_path = os.getenv('CACHE_RESULTS_PATH', 'cache_results')
        embedding_model = os.getenv('CACHE_EMBEDDING_MODEL', 'all-MiniLM-L6-v2')
        
        universal_search_cache = ChromaDBSearchCache(
            max_size=1000,  # Large cache size
            default_ttl=3600,  # 1 hour TTL
            cache_db_path=cache_db_path,
            cache_results_path=cache_results_path,
            embedding_model=embedding_model,
            similarity_threshold=0.7
        )
        logger.info(f"Initialized ChromaDB universal cache: {cache_db_path}")
    
    return universal_search_cache

# ===== End Phase 3c ChromaDB Cache System =====




def normalize_user_id(user_id: Optional[str]) -> Optional[str]:
    """Normalize user_id to None for anonymous requests"""
    if user_id is None or user_id.strip() == "":
        return None
    return user_id.strip()

def validate_user_id(user_id: Optional[str]) -> Optional[str]:
    """Validate user_id format and return normalized value"""
    # Normalize to None for anonymous users
    user_id = normalize_user_id(user_id)
    
    if user_id is None:
        return None  # Anonymous user
    
    # Validate format: non-empty string, max 255 chars, alphanumeric + hyphens + underscores
    if len(user_id) > 255:
        raise HTTPException(status_code=400, detail="user_id must be 255 characters or less")
    
    # Check allowed characters
    if not re.match(r'^[a-zA-Z0-9_-]+$', user_id):
        raise HTTPException(status_code=400, detail="user_id can only contain alphanumeric characters, hyphens, and underscores")
    
    return user_id

def run_in_threadpool(func):
    """Decorator to run synchronous model inference in thread pool"""
    @wraps(func)
    async def wrapper(*args, **kwargs):
        loop = asyncio.get_event_loop()
        return await loop.run_in_executor(None, func, *args, **kwargs)
    return wrapper

async def search_brave(query: str, max_results: int = 5) -> List[Dict[str, Any]]:
    """Search using Brave Search API with async HTTP client"""
    try:
        # Check for API key in environment variable first, then fallback to hardcoded
        api_key = os.getenv('BRAVE_API_KEY')
        
        if not api_key:
            logger.error("No Brave API key available")
            return []
        
        headers = {
            'Accept': 'application/json',
            'Accept-Encoding': 'gzip',
            'X-Subscription-Token': api_key
        }
        
        params = {
            'q': query,
            'count': max_results,
            'safesearch': 'moderate',
            'search_lang': 'en',
            'country': 'US'
        }
        
        
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(
                'https://api.search.brave.com/res/v1/web/search',
                headers=headers,
                params=params
            )
            
            response.raise_for_status()
            
            data = response.json()
            
            web_results = data.get('web', {})
            raw_results = web_results.get('results', [])
            
            results = []
            for result in raw_results:
                results.append({
                    "title": result.get("title", ""),
                    "body": re.sub(r'\s+', ' ', result.get("description", "")).strip(),
                    "href": result.get("url", ""),
                    "source": "Brave"
                })
            
            return results[:max_results]
        
    except Exception as e:
        logger.error(f"Brave Search error: {e}")
        logger.error(f"Brave Search error type: {type(e).__name__}")
        import traceback
        logger.error(f"Brave Search traceback: {traceback.format_exc()}")
        return []

async def search_duckduckgo(query: str, max_results: int = 5) -> List[Dict[str, Any]]:
    """Search using DuckDuckGo with async execution and timeout handling"""
    try:
        # Run DuckDuckGo search in thread pool with timeout
        loop = asyncio.get_event_loop()
        results = await asyncio.wait_for(
            loop.run_in_executor(None, _sync_duckduckgo_search, query, max_results),
            timeout=8.0  # 8 second timeout for Hugging Face compatibility
        )
        return results
    except asyncio.TimeoutError:
        logger.warning(f"DuckDuckGo search timed out for query: {query}")
        return []
    except Exception as e:
        logger.error(f"DuckDuckGo Search error: {e}")
        return []

def _sync_duckduckgo_search(query: str, max_results: int) -> List[Dict[str, Any]]:
    """Synchronous DuckDuckGo search helper with retry logic"""
    max_retries = 2
    for attempt in range(max_retries):
        try:
            # Configure DDGS with more conservative settings for hosted environments
            with DDGS(timeout=5) as ddgs:
                results = []
                search_results = ddgs.text(
                    query, 
                    safesearch='moderate', 
                    max_results=max_results,
                    region='us-en'  # Specify region to potentially avoid some blocks
                )
                
                for result in search_results:
                    results.append({
                        "title": result.get("title", ""),
                        "body": re.sub(r'\s+', ' ', result.get("body", "")).strip(),
                        "href": result.get("href", ""),
                        "source": "DuckDuckGo"
                    })
                
                logger.info(f"DuckDuckGo search successful on attempt {attempt + 1}")
                return results
                
        except Exception as e:
            logger.warning(f"DuckDuckGo attempt {attempt + 1} failed: {e}")
            if attempt == max_retries - 1:  # Last attempt
                logger.error(f"DuckDuckGo search failed after {max_retries} attempts")
                raise
            # Wait briefly before retry
            import time
            time.sleep(1)
    
    return []

async def search_web_combined(query: str, max_results: int = 10) -> List[Dict[str, Any]]:
    """Combined web search with resilient fallback strategy"""
    try:
        logger.info(f"Combined Search: Starting search for '{query}'")
        
        # Run both searches concurrently with timeout protection
        brave_task = asyncio.create_task(search_brave(query, 6))  # Get more from Brave as primary
        duckduckgo_task = asyncio.create_task(search_duckduckgo(query, 4))  # Fewer from DDG as backup
        
        # Wait for both searches to complete with overall timeout
        try:
            brave_results, duckduckgo_results = await asyncio.wait_for(
                asyncio.gather(brave_task, duckduckgo_task, return_exceptions=True),
                timeout=12.0  # Overall timeout for both searches
            )
        except asyncio.TimeoutError:
            logger.warning("Combined search timed out, cancelling remaining tasks")
            brave_task.cancel()
            duckduckgo_task.cancel()
            brave_results, duckduckgo_results = [], []
        
        # Handle exceptions and log results
        if isinstance(brave_results, Exception):
            logger.error(f"Brave search failed: {brave_results}")
            brave_results = []
        else:
            logger.info(f"Brave search returned {len(brave_results)} results")
            
        if isinstance(duckduckgo_results, Exception):
            logger.error(f"DuckDuckGo search failed: {duckduckgo_results}")
            duckduckgo_results = []
        else:
            logger.info(f"DuckDuckGo search returned {len(duckduckgo_results)} results")
        
        # If both searches fail, return empty with warning
        if not brave_results and not duckduckgo_results:
            logger.warning(f"All search engines failed for query: {query}")
            return []
        
        # Combine results
        combined_results = brave_results + duckduckgo_results
        
        # Remove duplicates based on URL
        seen_urls = set()
        unique_results = []
        
        for result in combined_results:
            url = result.get("href", "")
            if url and url not in seen_urls:
                seen_urls.add(url)
                unique_results.append(result)
        
        # Return top results up to max_results
        final_results = unique_results[:max_results]
        logger.info(f"Combined Search: Returning {len(final_results)} total unique results")
        
        # Log search engine performance
        brave_count = len([r for r in final_results if r.get('source') == 'Brave'])
        ddg_count = len([r for r in final_results if r.get('source') == 'DuckDuckGo'])
        logger.info(f"Search distribution: Brave={brave_count}, DuckDuckGo={ddg_count}")
        
        return final_results
        
    except Exception as e:
        logger.error(f"Combined search error: {e}")
        return []


def preprocess_text(text: str) -> str:
    """Use spaCy for fast text cleaning/normalization"""
    doc = nlp(text)
    # Lemmatize and remove stopwords
    return " ".join([
        token.lemma_ for token in doc
        if not token.is_stop and not token.is_punct
    ])[:2048]

def format_conversation_history(history: Optional[List[Dict[str, str]]], max_entries: int = 10) -> str:
    """Format conversation history for inclusion in AI prompt"""
    if not history:
        return ""
    
    try:
        formatted_entries = []
        # Take the most recent entries up to max_entries
        recent_history = history[-max_entries:] if len(history) > max_entries else history
        
        for entry in recent_history:
            # Handle both formats: {"role": "user/assistant", "content": "..."} 
            # and {"user": "...", "assistant": "..."}
            if "role" in entry and "content" in entry:
                role = entry["role"].title()  # User or Assistant
                content = entry["content"].strip()
                if content:
                    formatted_entries.append(f"{role}: {content}")
            elif "user" in entry and "assistant" in entry:
                user_msg = entry["user"].strip()
                assistant_msg = entry["assistant"].strip()
                if user_msg and assistant_msg:
                    formatted_entries.append(f"User: {user_msg}")
                    formatted_entries.append(f"Assistant: {assistant_msg}")
        
        if formatted_entries:
            return "\n".join(formatted_entries)
        return ""
        
    except Exception as e:
        logger.warning(f"Error formatting conversation history: {e}")
        return ""






    
@app.on_event("startup")
async def startup_event():
    """Perform startup tasks like NLP model loading"""
    logger.info("Starting NLP model loading...")
    # spaCy and NLTK data are loaded implicitly on first use or by spacy.load
    
    # Test analytics database connection
    try:
        from analytics.database import test_connection
        analytics_connected = await test_connection()
        if analytics_connected:
            logger.info("Analytics database connection successful")
        else:
            logger.warning("Analytics database connection failed - analytics disabled")
    except Exception as e:
        logger.warning(f"Analytics initialization failed: {e}")
    
    logger.info("Startup complete - NLP models ready")

@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest, 
                       response: Response,
                       user_agent: str = Header(None),
                       x_session_id: str = Header(None)):
    """Enhanced chat endpoint with dynamic model selection and combined search"""
    logger.info(f"Request: {request.prompt}")
    
    # Validate and extract user_id
    user_id = validate_user_id(request.user_id)
    
    # Analytics setup
    session_id = x_session_id
    message_id = None
    start_time = None
    
    try:
        # Import analytics (with fallback if not available)
        try:
            from analytics.collectors import create_session, get_session, track_message, PerformanceTimer
            analytics_available = True
        except ImportError:
            logger.warning("Analytics not available")
            analytics_available = False
            
            # Create fallback PerformanceTimer when analytics unavailable
            class PerformanceTimer:
                def __init__(self):
                    self.start_time = None
                    self.end_time = None
                
                def __enter__(self):
                    import time
                    self.start_time = time.time()
                    return self
                
                def __exit__(self, exc_type, exc_val, exc_tb):
                    import time
                    self.end_time = time.time()
                
                @property
                def duration_ms(self) -> int:
                    if self.start_time and self.end_time:
                        return int((self.end_time - self.start_time) * 1000)
                    return 0
        
        # Start performance timing
        with PerformanceTimer() as timer:
            # Handle session management
            if analytics_available:
                if not session_id:
                    # Create new session
                    session = await create_session(user_agent=user_agent, user_id=user_id)
                    session_id = session.session_id
                else:
                    # Get existing session or create new one if not found
                    session = await get_session(session_id)
                    if not session:
                        session = await create_session(user_agent=user_agent, user_id=user_id)
                        session_id = session.session_id
            
            search_results = []
            search_context = ""
            search_decision = None
            cache_info = None
            
            # Phase 3: Get universal cache for result caching
            search_cache = get_universal_cache()
            
            # Phase 3b: Context-Aware Request Flow Optimization
            logger.info(f"Use Search : {request.use_search}")
            has_history = has_meaningful_conversation_history(request.history)
            logger.info(f"Has meaningful conversation history: {has_history}")
            
            if request.use_search:
                # Check if search should be forced (overrides all optimizations)
                if request.force_search:
                    search_decision = {
                        "should_search": True,
                        "reason": "Search forced by user",
                        "confidence": 1.0,
                        "flow_type": "forced"
                    }
                    perform_search = True
                    logger.info(f"Using forced search flow")
                elif not has_history:
                    # First Message (No History): Cache-first approach
                    logger.info(f"Using cache-first flow (no conversation history)")
                    search_terms = extract_search_terms(request.prompt.lower(), nlp, rake)
                    logger.info(f"Extract search terms successful: {search_terms}")
                    
                    # Try to get from cache first (skip search decision for performance)
                    cached_entry = search_cache.get(search_terms, use_semantic_matching=True, similarity_threshold=0.7)
                    
                    if cached_entry:
                        # Cache hit! Use cached results, no search needed
                        search_results = cached_entry.results
                        search_context = format_search_context(search_results)
                        cache_info = {
                            "cache_hit": True,
                            "cached_query": cached_entry.search_query,
                            "cache_age_seconds": int(time.time() - cached_entry.timestamp),
                            "hit_count": cached_entry.hit_count,
                            "flow_type": "cache_first_hit",
                            "cache_type": "chromadb_vector"
                        }
                        search_decision = {
                            "should_search": False,
                            "reason": "Cache hit in cache-first flow",
                            "confidence": 1.0,
                            "flow_type": "cache_first_hit",
                            "cache_type": "chromadb_vector"
                        }
                        perform_search = False
                        logger.info(f"ChromaDB Cache-first HIT: Using cached results (age: {cache_info['cache_age_seconds']}s, hits: {cached_entry.hit_count})")
                    else:
                        # Cache miss - perform web search without search decision overhead
                        logger.info(f"ChromaDB Cache-first MISS: Performing web search")
                        search_query = " ".join(search_terms) or request.prompt
                        search_results = await search_web_combined(search_query, 10)
                        search_context = format_search_context(search_results)
                        
                        # Store results in cache if search was successful
                        if search_results:
                            search_cache.put(search_terms, search_query, search_results)
                            logger.info(f"Cached search results in universal cache for future use")
                        
                        cache_info = {
                            "cache_hit": False,
                            "stored_in_cache": len(search_results) > 0,
                            "flow_type": "cache_first_miss",
                            "cache_type": "chromadb_vector"
                        }
                        search_decision = {
                            "should_search": True,
                            "reason": "Cache miss in cache-first flow",
                            "confidence": 1.0,
                            "flow_type": "cache_first_miss",
                            "cache_type": "chromadb_vector"
                        }
                        perform_search = True
                else:
                    # Follow-up Messages (Has History): Search decision first
                    logger.info(f"Using search-decision-first flow (has conversation history)")
                    # Use hybrid intelligent search decision (Phase 2: AI-enhanced)
                    search_decision = await hybrid_search_decision(
                        request.prompt, 
                        request.history, 
                        request.search_decision_mode,
                        nlp,
                        model
                    )
                    search_decision["flow_type"] = "search_decision_first"
                    perform_search = search_decision["should_search"]
                    
                    if perform_search:
                        # Search needed - check cache before web search
                        search_terms = extract_search_terms(request.prompt.lower(), nlp, rake)
                        logger.info(f"Extract search terms successful: {search_terms}")
                        
                        # Try to get from cache first
                        cached_entry = search_cache.get(search_terms, use_semantic_matching=True, similarity_threshold=0.7)
                        
                        if cached_entry:
                            # Cache hit! Use cached results
                            search_results = cached_entry.results
                            search_context = format_search_context(search_results)
                            cache_info = {
                                "cache_hit": True,
                                    "cached_query": cached_entry.search_query,
                                "cache_age_seconds": int(time.time() - cached_entry.timestamp),
                                "hit_count": cached_entry.hit_count,
                                "flow_type": "search_decision_cache_hit",
                                "cache_type": "chromadb_vector"
                            }
                            logger.info(f"ChromaDB Search-decision flow Cache HIT: Using cached results (age: {cache_info['cache_age_seconds']}s, hits: {cached_entry.hit_count})")
                        else:
                            # Cache miss - perform web search
                            logger.info(f"ChromaDB Search-decision flow Cache MISS: Performing web search")
                            search_query = " ".join(search_terms) or request.prompt
                            search_results = await search_web_combined(search_query, 10)
                            search_context = format_search_context(search_results)
                            
                            # Store results in cache if search was successful
                            if search_results:
                                search_cache.put(search_terms, search_query, search_results)
                                logger.info(f"Cached search results in universal cache for future use")
                            
                            cache_info = {
                                "cache_hit": False,
                                    "stored_in_cache": len(search_results) > 0,
                                "flow_type": "search_decision_cache_miss",
                                "cache_type": "chromadb_vector"
                            }
                    else:
                        # Search not needed based on conversation context
                        logger.info(f"Search skipped: {search_decision['reason']}")
                        cache_info = {
                            "search_skipped": True,
                            "flow_type": "search_decision_skip"
                        }
                
                logger.info(f"Search Decision: {search_decision}")
                
                if perform_search:
                    logger.info(f"Search processing complete - Results: {len(search_results)}")
            else:
                logger.info(f"Search disabled by request")
                cache_info = {"search_disabled": True}

            logger.info(f"Search Context: {search_context}")
            
            # Format conversation history
            conversation_history = format_conversation_history(request.history, max_entries=10)
            logger.info(f"Conversation History: {len(request.history or [])} entries")
            
            # Create a prompt for the AI model with conversation history
            if conversation_history:
                prompt_template = f"""
                You are having a conversation with a user. Here is the conversation history:

                Conversation History:
                ---
                {conversation_history}
                ---
                
                Based on the following context from web pages I have read and the conversation history above, please answer the user's question.
                If the context does not contain the answer and you cannot answer based on the conversation history, say that you don't have enough information.

                Context:
                ---
                {search_context}
                ---

                Question: {request.prompt}
                
                Answer:
                """
            else:
                prompt_template = f"""
                Based on the following context from web pages I have read, please answer the user's question.
                If the context does not contain the answer, say that you don't have enough information.

                Context:
                ---
                {search_context}
                ---

                Question: {request.prompt}
                
                Answer:
                """

            response_text = await run_gemini_inference(prompt_template)

        # Track message analytics
        if analytics_available and session_id:
            message = await track_message(
                session_id=session_id,
                prompt_length=len(request.prompt),
                response_length=len(response_text),
                response_time_ms=timer.duration_ms,
                used_search=request.use_search,
                max_tokens=request.max_new_tokens,
                temperature=request.temperature,
                success=True,
                user_id=user_id
            )
            if message:
                message_id = message.message_id

        # Add session ID to response headers
        if session_id:
            response.headers["X-Session-ID"] = session_id

        # Prepare response
        chat_response = ChatResponse(
            response=response_text,
            search_results=search_results,
            search_decision=search_decision,
            cache_info=cache_info
        )

        return chat_response

    except Exception as e:
        # Track failed message
        if analytics_available and session_id:
            await track_message(
                session_id=session_id,
                prompt_length=len(request.prompt),
                response_length=0,
                response_time_ms=timer.duration_ms if 'timer' in locals() else 0,
                used_search=request.use_search,
                max_tokens=request.max_new_tokens,
                temperature=request.temperature,
                success=False,
                error_message=str(e),
                user_id=user_id
            )
        
        logger.error(f"Chat error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/search")
async def search_endpoint(request: SearchRequest):
    """Search endpoint with combined search engines"""
    try:
        results = await search_web_combined(request.query, request.max_results)
        return {"results": results}
    except Exception as e:
        logger.error(f"Search endpoint error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/stats")
async def analytics_stats():
    """Get basic analytics statistics"""
    try:
        from analytics.dashboard import get_basic_stats
        stats = await get_basic_stats()
        return stats
    except Exception as e:
        logger.error(f"Analytics stats error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/dashboard")
async def analytics_dashboard():
    """Get HTML analytics dashboard"""
    try:
        from analytics.dashboard import get_dashboard_data
        from fastapi.responses import HTMLResponse
        
        # Get dashboard data including user metrics
        data = await get_dashboard_data()
        
        # Get user statistics for the dashboard
        from analytics.dashboard import get_user_statistics, get_authenticated_vs_anonymous_metrics
        user_stats = await get_user_statistics()
        comparison_stats = await get_authenticated_vs_anonymous_metrics()
        
        # Create HTML dashboard
        html_content = f"""
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Atlas Analytics Dashboard</title>
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
            <style>
                body {{
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    margin: 0;
                    padding: 20px;
                    background-color: #f5f5f5;
                }}
                .container {{
                    max-width: 1200px;
                    margin: 0 auto;
                }}
                .header {{
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 30px;
                    border-radius: 10px;
                    margin-bottom: 30px;
                    text-align: center;
                }}
                .stats-grid {{
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                    gap: 20px;
                    margin-bottom: 30px;
                }}
                .stat-card {{
                    background: white;
                    padding: 25px;
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    text-align: center;
                }}
                .stat-number {{
                    font-size: 2.5em;
                    font-weight: bold;
                    color: #667eea;
                    margin-bottom: 10px;
                }}
                .stat-label {{
                    color: #666;
                    font-size: 0.9em;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                }}
                .chart-container {{
                    background: white;
                    padding: 25px;
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    margin-bottom: 20px;
                }}
                .chart-title {{
                    font-size: 1.2em;
                    font-weight: bold;
                    margin-bottom: 20px;
                    color: #333;
                }}
                .refresh-btn {{
                    background: #667eea;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-size: 1em;
                    margin-bottom: 20px;
                }}
                .refresh-btn:hover {{
                    background: #5a6fd8;
                }}
                .error {{
                    background: #fee;
                    color: #c33;
                    padding: 15px;
                    border-radius: 5px;
                    margin: 10px 0;
                }}
                .last-updated {{
                    text-align: center;
                    color: #666;
                    font-size: 0.9em;
                    margin-top: 20px;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>🚀 Atlas Analytics Dashboard</h1>
                    <p>Real-time insights into your chat application</p>
                </div>
                
                <button class="refresh-btn" onclick="location.reload()">🔄 Refresh Data</button>
                
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-number">{data.get('basic', {}).get('total_messages', 0)}</div>
                        <div class="stat-label">Total Messages</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">{data.get('basic', {}).get('total_sessions', 0)}</div>
                        <div class="stat-label">Total Sessions</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">{data.get('basic', {}).get('active_sessions', 0)}</div>
                        <div class="stat-label">Active Sessions</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">{data.get('basic', {}).get('messages_today', 0)}</div>
                        <div class="stat-label">Messages Today</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">{data.get('basic', {}).get('search_usage_percentage', 0)}%</div>
                        <div class="stat-label">Search Usage</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">{data.get('basic', {}).get('average_response_time_ms', 0)}ms</div>
                        <div class="stat-label">Avg Response Time</div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">🔓 Anonymous Usage Overview</div>
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('anonymous_sessions', 0)}</div>
                            <div class="stat-label">Anonymous Sessions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('anonymous_messages', 0)}</div>
                            <div class="stat-label">Anonymous Messages</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{round(100 - user_stats.get('authenticated_session_percentage', 0), 1)}%</div>
                            <div class="stat-label">Anonymous Session %</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{round(100 - user_stats.get('authenticated_message_percentage', 0), 1)}%</div>
                            <div class="stat-label">Anonymous Message %</div>
                        </div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">👥 User Analytics</div>
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('unique_authenticated_users', 0)}</div>
                            <div class="stat-label">Unique Users</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('authenticated_sessions', 0)}</div>
                            <div class="stat-label">Authenticated Sessions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('anonymous_sessions', 0)}</div>
                            <div class="stat-label">Anonymous Sessions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('authenticated_session_percentage', 0)}%</div>
                            <div class="stat-label">Auth Session %</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('authenticated_messages', 0)}</div>
                            <div class="stat-label">Authenticated Messages</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('anonymous_messages', 0)}</div>
                            <div class="stat-label">Anonymous Messages</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('authenticated_message_percentage', 0)}%</div>
                            <div class="stat-label">Auth Message %</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">{user_stats.get('anonymous_messages', 0) + user_stats.get('authenticated_messages', 0)}</div>
                            <div class="stat-label">Total Messages</div>
                        </div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">🔍 User Filtering</div>
                    <div style="margin-bottom: 20px;">
                        <input type="text" id="userIdInput" placeholder="Enter user ID to filter analytics" 
                               style="padding: 10px; border: 1px solid #ddd; border-radius: 5px; width: 300px; margin-right: 10px;">
                        <button onclick="filterByUser()" style="padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 5px; cursor: pointer;">
                            Filter Analytics
                        </button>
                        <button onclick="clearFilter()" style="padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; margin-left: 10px;">
                            Clear Filter
                        </button>
                    </div>
                    <div id="userFilterResults" style="display: none;">
                        <h4>User-Specific Analytics</h4>
                        <div id="userStatsGrid" class="stats-grid"></div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">📊 Hourly Message Activity (Last 24 Hours)</div>
                    <canvas id="hourlyChart" width="400" height="200"></canvas>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">⚡ Performance Metrics</div>
                    <canvas id="performanceChart" width="400" height="200"></canvas>
                </div>
                
                <div class="chart-container">
                    <div class="chart-title">👤 Authenticated vs Anonymous Comparison</div>
                    <canvas id="comparisonChart" width="400" height="200"></canvas>
                </div>
                
                <div class="last-updated">
                    Last updated: {data.get('generated_at', 'Unknown')}
                </div>
            </div>
            
            <script>
                // Hourly Chart
                const hourlyData = {data.get('hourly', [])};
                const hourlyLabels = hourlyData.map(d => d.hour);
                const hourlyMessages = hourlyData.map(d => d.message_count);
                const hourlySearches = hourlyData.map(d => d.search_count);
                
                new Chart(document.getElementById('hourlyChart'), {{
                    type: 'line',
                    data: {{
                        labels: hourlyLabels,
                        datasets: [{{
                            label: 'Messages',
                            data: hourlyMessages,
                            borderColor: '#667eea',
                            backgroundColor: 'rgba(102, 126, 234, 0.1)',
                            tension: 0.4
                        }}, {{
                            label: 'With Search',
                            data: hourlySearches,
                            borderColor: '#f093fb',
                            backgroundColor: 'rgba(240, 147, 251, 0.1)',
                            tension: 0.4
                        }}]
                    }},
                    options: {{
                        responsive: true,
                        scales: {{
                            y: {{
                                beginAtZero: true
                            }}
                        }}
                    }}
                }});
                
                // Performance Chart
                const perfData = {data.get('performance', {})};
                new Chart(document.getElementById('performanceChart'), {{
                    type: 'bar',
                    data: {{
                        labels: ['P50', 'P90', 'P95', 'Error Rate %'],
                        datasets: [{{
                            label: 'Performance Metrics',
                            data: [
                                perfData.response_time_p50 || 0,
                                perfData.response_time_p90 || 0,
                                perfData.response_time_p95 || 0,
                                perfData.error_rate_percentage || 0
                            ],
                            backgroundColor: [
                                'rgba(102, 126, 234, 0.8)',
                                'rgba(240, 147, 251, 0.8)',
                                'rgba(255, 159, 64, 0.8)',
                                'rgba(255, 99, 132, 0.8)'
                            ]
                        }}]
                    }},
                    options: {{
                        responsive: true,
                        scales: {{
                            y: {{
                                beginAtZero: true
                            }}
                        }}
                    }}
                }});
                
                // Comparison Chart
                const comparisonData = {comparison_stats};
                new Chart(document.getElementById('comparisonChart'), {{
                    type: 'bar',
                    data: {{
                        labels: ['Sessions', 'Messages', 'Avg Response Time (ms)', 'Search Usage %'],
                        datasets: [{{
                            label: 'Authenticated Users',
                            data: [
                                comparisonData.authenticated?.sessions || 0,
                                comparisonData.authenticated?.messages || 0,
                                comparisonData.authenticated?.avg_response_time_ms || 0,
                                comparisonData.authenticated?.search_usage_percentage || 0
                            ],
                            backgroundColor: 'rgba(102, 126, 234, 0.8)'
                        }}, {{
                            label: 'Anonymous Users',
                            data: [
                                comparisonData.anonymous?.sessions || 0,
                                comparisonData.anonymous?.messages || 0,
                                comparisonData.anonymous?.avg_response_time_ms || 0,
                                comparisonData.anonymous?.search_usage_percentage || 0
                            ],
                            backgroundColor: 'rgba(255, 159, 64, 0.8)'
                        }}]
                    }},
                    options: {{
                        responsive: true,
                        scales: {{
                            y: {{
                                beginAtZero: true
                            }}
                        }}
                    }}
                }});
                
                // User filtering functions
                async function filterByUser() {{
                    const userId = document.getElementById('userIdInput').value.trim();
                    if (!userId) {{
                        alert('Please enter a user ID');
                        return;
                    }}
                    
                    try {{
                        const response = await fetch(`/analytics/user/${{encodeURIComponent(userId)}}`);
                        const userData = await response.json();
                        
                        if (userData.error) {{
                            alert(`Error: ${{userData.error}}`);
                            return;
                        }}
                        
                        displayUserStats(userData);
                    }} catch (error) {{
                        alert(`Error fetching user data: ${{error.message}}`);
                    }}
                }}
                
                function displayUserStats(userData) {{
                    const resultsDiv = document.getElementById('userFilterResults');
                    const statsGrid = document.getElementById('userStatsGrid');
                    
                    statsGrid.innerHTML = `
                        <div class="stat-card">
                            <div class="stat-number">${{userData.total_sessions || 0}}</div>
                            <div class="stat-label">User Sessions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${{userData.total_messages || 0}}</div>
                            <div class="stat-label">User Messages</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${{userData.search_usage_percentage || 0}}%</div>
                            <div class="stat-label">Search Usage</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${{userData.avg_response_time_ms || 0}}ms</div>
                            <div class="stat-label">Avg Response Time</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${{userData.avg_messages_per_session || 0}}</div>
                            <div class="stat-label">Avg Msgs/Session</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${{userData.active_sessions || 0}}</div>
                            <div class="stat-label">Active Sessions</div>
                        </div>
                    `;
                    
                    resultsDiv.style.display = 'block';
                }}
                
                function clearFilter() {{
                    document.getElementById('userIdInput').value = '';
                    document.getElementById('userFilterResults').style.display = 'none';
                }}
            </script>
        </body>
        </html>
        """
        
        return HTMLResponse(content=html_content)
        
    except Exception as e:
        logger.error(f"Analytics dashboard error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/users")
async def analytics_users():
    """Get overall user statistics including authenticated vs anonymous metrics"""
    try:
        from analytics.dashboard import get_user_statistics
        stats = await get_user_statistics()
        return stats
    except Exception as e:
        logger.error(f"Analytics users error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/user/{user_id}")
async def analytics_user(user_id: str):
    """Get analytics for a specific user"""
    try:
        # Validate user_id
        if not user_id or not isinstance(user_id, str) or len(user_id.strip()) == 0:
            raise HTTPException(status_code=400, detail="Invalid user_id provided")
        
        from analytics.dashboard import get_user_analytics
        stats = await get_user_analytics(user_id.strip())
        return stats
    except Exception as e:
        logger.error(f"Analytics user error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/comparison")
async def analytics_comparison():
    """Get detailed comparison metrics between authenticated and anonymous users"""
    try:
        from analytics.dashboard import get_authenticated_vs_anonymous_metrics
        stats = await get_authenticated_vs_anonymous_metrics()
        return stats
    except Exception as e:
        logger.error(f"Analytics comparison error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/export")
async def analytics_export(format: str = "json", days: int = 7, user_id: Optional[str] = None):
    """Export analytics data in JSON or CSV format with optional user_id filtering"""
    try:
        from analytics.database import get_sessions_collection, get_messages_collection
        from fastapi.responses import StreamingResponse
        from datetime import datetime, timedelta
        import json
        import csv
        import io
        
        # Validate format
        if format not in ["json", "csv"]:
            raise HTTPException(status_code=400, detail="Format must be 'json' or 'csv'")
        
        # Calculate date range
        end_date = datetime.utcnow()
        start_date = end_date - timedelta(days=days)
        
        # Get collections
        sessions_collection = await get_sessions_collection()
        messages_collection = await get_messages_collection()
        
        if sessions_collection is None or messages_collection is None:
            raise HTTPException(status_code=500, detail="Database not available")
        
        # Build filters with optional user_id
        session_filter = {"start_time": {"$gte": start_date, "$lte": end_date}}
        message_filter = {"timestamp": {"$gte": start_date, "$lte": end_date}}
        
        if user_id is not None and user_id.strip():
            user_id = user_id.strip()
            session_filter["user_id"] = user_id
            message_filter["user_id"] = user_id
        
        # Get data
        sessions_cursor = sessions_collection.find(session_filter)
        sessions_data = await sessions_cursor.to_list(None)
        
        messages_cursor = messages_collection.find(message_filter)
        messages_data = await messages_cursor.to_list(None)
        
        # Convert ObjectId to string for JSON serialization
        for session in sessions_data:
            session["_id"] = str(session["_id"])
            if "start_time" in session:
                session["start_time"] = session["start_time"].isoformat()
            if "end_time" in session and session["end_time"]:
                session["end_time"] = session["end_time"].isoformat()
        
        for message in messages_data:
            message["_id"] = str(message["_id"])
            if "timestamp" in message:
                message["timestamp"] = message["timestamp"].isoformat()
        
        export_data = {
            "export_info": {
                "generated_at": end_date.isoformat(),
                "date_range": {
                    "start": start_date.isoformat(),
                    "end": end_date.isoformat(),
                    "days": days
                },
                "filters": {
                    "user_id": user_id if user_id and user_id.strip() else None
                },
                "counts": {
                    "sessions": len(sessions_data),
                    "messages": len(messages_data)
                }
            },
            "sessions": sessions_data,
            "messages": messages_data
        }
        
        if format == "json":
            # Return JSON
            json_str = json.dumps(export_data, indent=2, default=str)
            
            def generate():
                yield json_str
            
            # Generate filename with optional user_id
            filename_suffix = f"_user_{user_id}" if user_id and user_id.strip() else ""
            filename = f"atlas_analytics_{start_date.strftime('%Y%m%d')}_{end_date.strftime('%Y%m%d')}{filename_suffix}.json"
            
            return StreamingResponse(
                generate(),
                media_type="application/json",
                headers={"Content-Disposition": f"attachment; filename={filename}"}
            )
        
        elif format == "csv":
            # Create CSV with separate sheets for sessions and messages
            output = io.StringIO()
            
            # Write export info
            output.write(f"# Atlas Analytics Export\\n")
            output.write(f"# Generated: {export_data['export_info']['generated_at']}\\n")
            output.write(f"# Date Range: {export_data['export_info']['date_range']['start']} to {export_data['export_info']['date_range']['end']}\\n")
            output.write(f"# Sessions: {export_data['export_info']['counts']['sessions']}, Messages: {export_data['export_info']['counts']['messages']}\\n")
            output.write("\\n")
            
            # Sessions CSV
            output.write("=== SESSIONS ===\\n")
            if sessions_data:
                fieldnames = sessions_data[0].keys()
                writer = csv.DictWriter(output, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerows(sessions_data)
            
            output.write("\\n=== MESSAGES ===\\n")
            if messages_data:
                fieldnames = messages_data[0].keys()
                writer = csv.DictWriter(output, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerows(messages_data)
            
            def generate():
                yield output.getvalue()
            
            # Generate filename with optional user_id
            filename_suffix = f"_user_{user_id}" if user_id and user_id.strip() else ""
            filename = f"atlas_analytics_{start_date.strftime('%Y%m%d')}_{end_date.strftime('%Y%m%d')}{filename_suffix}.csv"
            
            return StreamingResponse(
                generate(),
                media_type="text/csv",
                headers={"Content-Disposition": f"attachment; filename={filename}"}
            )
        
    except Exception as e:
        logger.error(f"Analytics export error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/analytics/cache")
async def analytics_cache():
    """Get universal ChromaDB cache analytics and performance metrics"""
    try:
        # Get universal cache instance
        search_cache = get_universal_cache()
        
        # Get cache stats
        cache_stats = search_cache.get_stats()
        
        # Get popular queries from ChromaDB
        popular_queries = search_cache.get_popular_queries(limit=10)
        
        # Determine cache effectiveness
        hit_rate = cache_stats.get("hit_rate_percentage", 0)
        cache_effectiveness = "High" if hit_rate > 60 else "Medium" if hit_rate > 30 else "Low"
        
        return {
            "cache_statistics": cache_stats,
            "popular_queries": popular_queries,
            "cache_effectiveness": cache_effectiveness,
            "memory_efficiency": {
                "entries_per_mb": cache_stats["cache_size"] / max(0.1, cache_stats["memory_usage_mb"]),
                "avg_entry_size_kb": (cache_stats["memory_usage_mb"] * 1024) / max(1, cache_stats["cache_size"])
            },
            "vector_database_info": {
                "embedding_model": cache_stats.get("embedding_model", "unknown"),
                "similarity_threshold": cache_stats.get("similarity_threshold", 0.7),
                "persistent_storage": cache_stats.get("persistent_storage", False),
                "database_path": cache_stats.get("database_path", "unknown")
            }
        }
            
    except Exception as e:
        logger.error(f"ChromaDB cache analytics error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/analytics/cache/clear")
async def clear_cache(cache_type: str = "expired"):
    """Clear universal ChromaDB cache data - for maintenance and testing"""
    try:
        if cache_type not in ["expired", "all"]:
            raise HTTPException(status_code=400, detail="cache_type must be 'expired' or 'all'")
        
        # Get cache instance
        search_cache = get_universal_cache()
        
        cache_stats_before = search_cache.get_stats()
        
        if cache_type == "expired":
            search_cache.clear_expired()
            action_taken = "Cleared expired entries from ChromaDB universal cache"
        elif cache_type == "all":
            search_cache.clear_all()
            action_taken = "Cleared all entries from ChromaDB universal cache"
        
        cache_stats_after = search_cache.get_stats()
        
        return {
            "action": cache_type,
            "message": action_taken,
            "cache_type": "chromadb_vector",
            "before": {
                "cache_size": cache_stats_before["cache_size"],
                "memory_usage_mb": cache_stats_before["memory_usage_mb"]
            },
            "after": {
                "cache_size": cache_stats_after["cache_size"],
                "memory_usage_mb": cache_stats_after["memory_usage_mb"]
            },
            "entries_removed": cache_stats_before["cache_size"] - cache_stats_after["cache_size"],
            "memory_freed_mb": cache_stats_before["memory_usage_mb"] - cache_stats_after["memory_usage_mb"]
        }
        
    except Exception as e:
        logger.error(f"ChromaDB cache clear error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
async def root():
    """Enhanced health check with model status"""
    return {
        "message": "Enhanced Chat API with Gemini and Combined Search is running!",
        "models": {
            "gemini_loaded": True, # Gemini is always loaded via API
            "model_type": "gemini-1.5-flash",
            "capabilities": ["question_answering", "summarization", "explanation", "web_search_augmentation"]
        },
        "search_engines": ["Brave", "DuckDuckGo"],
        "endpoints": {
            "chat": "/chat",
            "search": "/search",
            "analytics_stats": "/analytics/stats",
            "analytics_dashboard": "/analytics/dashboard",
            "analytics_users": "/analytics/users",
            "analytics_user": "/analytics/user/{user_id}",
            "analytics_comparison": "/analytics/comparison",
            "analytics_export": "/analytics/export",
            "analytics_cache": "/analytics/cache",
            "cache_clear": "/analytics/cache/clear",
            "docs": "/docs"
        },
        "cache_system": {
            "enabled": True,
            "cache_type": "chromadb_vector",
            "cache_size": get_universal_cache().get_stats().get("cache_size", 0),
            "max_size": get_universal_cache().max_size,
            "semantic_similarity": True,
            "vector_similarity": True,
            "persistent_storage": True,
            "ttl_management": True,
            "memory_efficient": True,
            "embedding_model": get_universal_cache().get_stats().get("embedding_model", "all-MiniLM-L6-v2")
        }
    }


async def run_gemini_inference(prompt_text: str) -> str:
    """Run Gemini model inference"""
    try:
        response = await model.generate_content_async(prompt_text)
        return response.text
    except Exception as e:
        logger.error(f"Gemini inference error: {e}")
        raise


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