Spaces:
Sleeping

File size: 61,805 Bytes
8ad2676
 
 
ec5955b
 
 
 
 
7851df6
8ad2676
 
 
 
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
8ad2676
 
 
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
ec5955b
 
 
7851df6
ec5955b
 
 
 
 
 
7851df6
ec5955b
7851df6
ec5955b
7851df6
ec5955b
 
 
 
 
 
7851df6
ec5955b
 
 
 
 
 
 
8ad2676
ec5955b
8ad2676
ec5955b
 
 
7851df6
ec5955b
 
 
 
 
8ad2676
 
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ad2676
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
ec5955b
 
 
 
8ad2676
ec5955b
8ad2676
ec5955b
 
7851df6
ec5955b
 
 
 
7851df6
8ad2676
 
 
ec5955b
 
8ad2676
ec5955b
8ad2676
 
 
 
 
 
 
 
ec5955b
8ad2676
ec5955b
8ad2676
 
 
 
7851df6
 
8ad2676
 
 
ec5955b
7851df6
8ad2676
 
ec5955b
7851df6
 
8ad2676
 
 
 
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
8ad2676
 
 
 
7851df6
 
8ad2676
 
7851df6
 
8ad2676
 
 
ec5955b
 
 
 
 
7851df6
ec5955b
7851df6
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
 
ec5955b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
ec5955b
7851df6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto');
const { HfInference } = require('@huggingface/inference');
const axios = require('axios');
const NodeCache = require('node-cache');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 7860;

// Initialize caching system for web search results
const searchCache = new NodeCache({
  stdTTL: parseInt(process.env.WEB_SEARCH_CACHE_TTL) || 1800, // 30 minutes default
  checkperiod: 600, // Check for expired keys every 10 minutes
  useClones: false
});

// Chat history storage directory
const CHAT_HISTORY_DIR = path.join(__dirname, 'chat_history');

// Ensure chat history directory exists
async function ensureChatHistoryDir() {
  try {
    await fs.access(CHAT_HISTORY_DIR);
  } catch {
    await fs.mkdir(CHAT_HISTORY_DIR, { recursive: true });
  }
}

// Chat history data structures and utilities
function generateSessionId() {
  return crypto.randomUUID();
}

function getUserHistoryFile(userId) {
  return path.join(CHAT_HISTORY_DIR, `user_${userId}.json`);
}

async function loadUserHistory(userId) {
  try {
    const historyFile = getUserHistoryFile(userId);
    const data = await fs.readFile(historyFile, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    // Return empty history structure if file doesn't exist
    return {
      userId,
      sessions: {},
      metadata: {
        totalMessages: 0,
        totalSessions: 0,
        createdAt: new Date().toISOString(),
        lastActivity: new Date().toISOString()
      }
    };
  }
}

async function saveUserHistory(userId, history) {
  try {
    const historyFile = getUserHistoryFile(userId);
    history.metadata.lastActivity = new Date().toISOString();
    await fs.writeFile(historyFile, JSON.stringify(history, null, 2));
    return true;
  } catch (error) {
    console.error('Error saving user history:', error);
    return false;
  }
}

function createChatSession(title = null) {
  const sessionId = generateSessionId();
  return {
    id: sessionId,
    title: title || `Chat ${new Date().toLocaleDateString()}`,
    messages: [],
    metadata: {
      createdAt: new Date().toISOString(),
      lastActivity: new Date().toISOString(),
      messageCount: 0,
      totalTokens: 0,
      avgResponseTime: 0
    }
  };
}

function addMessageToSession(session, message, sender, metadata = {}) {
  const messageObj = {
    id: crypto.randomUUID(),
    content: message,
    sender, // 'user' or 'bot'
    timestamp: new Date().toISOString(),
    metadata: {
      ...metadata,
      tokens: metadata.tokens || 0,
      responseTime: metadata.responseTime || 0
    }
  };

  session.messages.push(messageObj);
  session.metadata.lastActivity = new Date().toISOString();
  session.metadata.messageCount = session.messages.length;

  if (metadata.tokens) {
    session.metadata.totalTokens += metadata.tokens;
  }

  if (metadata.responseTime && sender === 'bot') {
    const botMessages = session.messages.filter(m => m.sender === 'bot');
    const totalResponseTime = botMessages.reduce((sum, m) => sum + (m.metadata.responseTime || 0), 0);
    session.metadata.avgResponseTime = Math.round(totalResponseTime / botMessages.length);
  }

  // Auto-generate title from first user message if not set
  if (!session.title || session.title.startsWith('Chat ')) {
    const firstUserMessage = session.messages.find(m => m.sender === 'user');
    if (firstUserMessage) {
      session.title = firstUserMessage.content.substring(0, 50) +
                     (firstUserMessage.content.length > 50 ? '...' : '');
    }
  }

  return messageObj;
}

// =================================================================
// WEB SEARCH SERVICE WITH MULTIPLE PROVIDERS
// =================================================================

// Web Search Service Class
class UGAWebSearchService {
  constructor() {
    this.enableWebSearch = process.env.ENABLE_WEB_SEARCH === 'true';
    this.googleApiKey = process.env.GOOGLE_SEARCH_API_KEY;
    this.googleEngineId = process.env.GOOGLE_SEARCH_ENGINE_ID;
    this.bingApiKey = process.env.BING_SEARCH_API_KEY;
    this.searxngUrl = process.env.SEARXNG_URL || 'https://searx.org';
  }

  // Generate cache key for search queries
  generateCacheKey(query, searchType = 'general') {
    return `search:${searchType}:${crypto.createHash('md5').update(query.toLowerCase()).digest('hex')}`;
  }

  // UGA-specific search domains and filters
  // Enhanced query building for more specific searches
  enhanceSearchQuery(originalQuery, agentType) {
    const lowerQuery = originalQuery.toLowerCase();

    // Detect specific information types and add targeted keywords
    const enhancements = {
      hours: ['hours', 'open', 'close', 'schedule', 'time', 'operating'],
      location: ['where', 'location', 'address', 'building', 'room'],
      contact: ['phone', 'email', 'contact', 'number'],
      dates: ['when', 'date', 'deadline', 'calendar'],
      costs: ['cost', 'price', 'fee', 'tuition', 'expense'],
      requirements: ['requirement', 'prerequisite', 'need', 'must'],
      events: ['event', 'happening', 'schedule', 'calendar']
    };

    let enhancedQuery = originalQuery;

    // Add specific terms based on query content
    for (const [category, keywords] of Object.entries(enhancements)) {
      if (keywords.some(keyword => lowerQuery.includes(keyword))) {
        switch (category) {
          case 'hours':
            enhancedQuery += ' hours schedule operating times open close';
            break;
          case 'location':
            enhancedQuery += ' location address building campus map';
            break;
          case 'contact':
            enhancedQuery += ' contact phone email information';
            break;
          case 'dates':
            enhancedQuery += ' date calendar schedule deadline';
            break;
          case 'costs':
            enhancedQuery += ' cost price fee tuition expense budget';
            break;
          case 'requirements':
            enhancedQuery += ' requirements prerequisites needed criteria';
            break;
          case 'events':
            enhancedQuery += ' events calendar schedule happening activities';
            break;
        }
        break; // Only add one enhancement category
      }
    }

    return enhancedQuery;
  }

  getUGASearchFilters(agentType) {
    const filters = {
      academic: {
        sites: ['uga.edu', 'bulletin.uga.edu', 'reg.uga.edu', 'admissions.uga.edu'],
        keywords: ['University of Georgia', 'UGA', 'course', 'degree', 'academic', 'registration']
      },
      student_life: {
        sites: ['uga.edu', 'housing.uga.edu', 'dining.uga.edu', 'rec.uga.edu', 'studentaffairs.uga.edu'],
        keywords: ['University of Georgia', 'UGA', 'campus', 'student life', 'housing', 'dining', 'events']
      },
      athletics: {
        sites: ['georgiadogs.com', 'uga.edu', 'sec.espn.com'],
        keywords: ['Georgia Bulldogs', 'UGA athletics', 'Georgia football', 'Georgia basketball', 'SEC']
      },
      general: {
        sites: ['uga.edu', 'georgiadogs.com'],
        keywords: ['University of Georgia', 'UGA']
      }
    };
    return filters[agentType] || filters.general;
  }

  // Google Custom Search API
  async searchGoogle(query, agentType = 'general') {
    if (!this.googleApiKey || !this.googleEngineId) {
      throw new Error('Google Search API not configured');
    }

    const filters = this.getUGASearchFilters(agentType);
    const specificQuery = this.enhanceSearchQuery(query, agentType);
    const enhancedQuery = `${specificQuery} ${filters.keywords.join(' OR ')}`;

    try {
      const response = await axios.get('https://www.googleapis.com/customsearch/v1', {
        params: {
          key: this.googleApiKey,
          cx: this.googleEngineId,
          q: enhancedQuery,
          num: 8,
          safe: 'active'
        },
        timeout: 10000
      });

      return this.formatSearchResults(response.data.items || [], 'google', agentType);
    } catch (error) {
      console.error('Google Search API error:', error.message);
      throw error;
    }
  }

  // Bing Search API
  async searchBing(query, agentType = 'general') {
    if (!this.bingApiKey) {
      throw new Error('Bing Search API not configured');
    }

    const filters = this.getUGASearchFilters(agentType);
    const enhancedQuery = `${query} ${filters.keywords.join(' OR ')}`;

    try {
      const response = await axios.get('https://api.bing.microsoft.com/v7.0/search', {
        headers: {
          'Ocp-Apim-Subscription-Key': this.bingApiKey
        },
        params: {
          q: enhancedQuery,
          count: 8,
          safeSearch: 'Moderate',
          responseFilter: 'Webpages'
        },
        timeout: 10000
      });

      return this.formatSearchResults(response.data.webPages?.value || [], 'bing', agentType);
    } catch (error) {
      console.error('Bing Search API error:', error.message);
      throw error;
    }
  }

  // SearXNG (Free/Open Source Search)
  async searchSearXNG(query, agentType = 'general') {
    const filters = this.getUGASearchFilters(agentType);
    const enhancedQuery = `${query} ${filters.keywords.join(' OR ')}`;

    try {
      const response = await axios.get(`${this.searxngUrl}/search`, {
        params: {
          q: enhancedQuery,
          format: 'json',
          engines: 'google,bing,duckduckgo',
          safesearch: 1
        },
        timeout: 15000,
        headers: {
          'User-Agent': 'UGA-AI-Assistant/1.0'
        }
      });

      return this.formatSearchResults(response.data.results || [], 'searxng', agentType);
    } catch (error) {
      console.error('SearXNG Search error:', error.message);
      throw error;
    }
  }

  // Format search results consistently across providers
  formatSearchResults(results, provider, agentType) {
    const filters = this.getUGASearchFilters(agentType);

    const formatted = results.slice(0, 6).map(result => {
      let title, url, snippet;

      if (provider === 'google') {
        title = result.title;
        url = result.link;
        snippet = result.snippet;
      } else if (provider === 'bing') {
        title = result.name;
        url = result.url;
        snippet = result.snippet;
      } else if (provider === 'searxng') {
        title = result.title;
        url = result.url;
        snippet = result.content;
      }

      // Score relevance based on UGA domains and keywords
      let relevanceScore = 0;
      if (filters.sites.some(site => url.includes(site))) {
        relevanceScore += 10;
      }
      if (filters.keywords.some(keyword =>
        title.toLowerCase().includes(keyword.toLowerCase()) ||
        snippet.toLowerCase().includes(keyword.toLowerCase())
      )) {
        relevanceScore += 5;
      }

      return {
        title: title || 'No title',
        url: url || '',
        snippet: snippet || 'No description available',
        provider,
        relevanceScore,
        timestamp: new Date().toISOString()
      };
    });

    // Sort by relevance score
    return formatted.sort((a, b) => b.relevanceScore - a.relevanceScore);
  }

  // Main search function with fallback providers
  async search(query, agentType = 'general') {
    if (!this.enableWebSearch) {
      return {
        results: [],
        fromCache: false,
        provider: 'disabled',
        message: 'Web search is disabled'
      };
    }

    // Check cache first
    const cacheKey = this.generateCacheKey(query, agentType);
    const cachedResults = searchCache.get(cacheKey);

    if (cachedResults) {
      console.log(`πŸ” Returning cached search results for: ${query}`);
      return {
        results: cachedResults.results,
        fromCache: true,
        provider: cachedResults.provider,
        timestamp: cachedResults.timestamp,
        cacheKey
      };
    }

    console.log(`πŸ” Searching web for: ${query} (agent: ${agentType})`);

    // Try different search providers in order of preference
    const providers = [
      { name: 'google', method: () => this.searchGoogle(query, agentType) },
      { name: 'bing', method: () => this.searchBing(query, agentType) },
      { name: 'searxng', method: () => this.searchSearXNG(query, agentType) }
    ];

    for (const provider of providers) {
      try {
        const results = await provider.method();

        if (results && results.length > 0) {
          // Cache successful results
          const searchData = {
            results,
            provider: provider.name,
            timestamp: new Date().toISOString(),
            query,
            agentType
          };

          searchCache.set(cacheKey, searchData);

          console.log(`βœ… Search successful with ${provider.name}: ${results.length} results`);
          return {
            results,
            fromCache: false,
            provider: provider.name,
            timestamp: searchData.timestamp,
            cacheKey
          };
        }
      } catch (error) {
        console.error(`❌ ${provider.name} search failed:`, error.message);
        continue; // Try next provider
      }
    }

    // If all providers fail, return empty results
    console.log('❌ All search providers failed');
    return {
      results: [],
      fromCache: false,
      provider: 'none',
      error: 'All search providers unavailable',
      timestamp: new Date().toISOString()
    };
  }

  // Get search suggestions for UGA-specific topics
  getUGASearchSuggestions(agentType) {
    const suggestions = {
      academic: [
        'UGA course registration dates',
        'UGA degree requirements',
        'UGA academic calendar 2024',
        'UGA faculty directory',
        'UGA graduation requirements'
      ],
      student_life: [
        'UGA dining hours',
        'UGA campus events this week',
        'UGA housing application',
        'UGA recreation center hours',
        'UGA student organizations'
      ],
      athletics: [
        'Georgia Bulldogs football schedule',
        'UGA basketball tickets',
        'Georgia Bulldogs latest news',
        'Sanford Stadium events',
        'UGA athletics scores'
      ],
      general: [
        'UGA campus map',
        'UGA contact information',
        'UGA admissions requirements',
        'UGA news and announcements',
        'UGA academic programs'
      ]
    };
    return suggestions[agentType] || suggestions.general;
  }

  // Search specifically for current UGA information
  async searchCurrentUGAInfo(topic, agentType = 'general') {
    const currentYear = new Date().getFullYear();
    const currentMonth = new Date().toLocaleString('default', { month: 'long' });

    const timeBasedQuery = `UGA ${topic} ${currentYear} ${currentMonth} current latest`;
    return await this.search(timeBasedQuery, agentType);
  }

  // Get cache statistics
  getCacheStats() {
    return {
      keys: searchCache.keys().length,
      hits: searchCache.getStats().hits,
      misses: searchCache.getStats().misses,
      ksize: searchCache.getStats().ksize,
      vsize: searchCache.getStats().vsize
    };
  }

  // Clear cache (admin function)
  clearCache() {
    searchCache.flushAll();
    return { message: 'Search cache cleared successfully' };
  }
}

// Initialize the web search service
const webSearchService = new UGAWebSearchService();

// =================================================================
// END WEB SEARCH SERVICE
// =================================================================

// Middleware
app.use(cors({ origin: '*', credentials: true }));
app.use(express.json({ limit: '10mb' }));
app.use(express.static('.'));

// Initialize Hugging Face client
let hfClient = null;
if (process.env.HUGGINGFACE_API_KEY) {
  hfClient = new HfInference(process.env.HUGGINGFACE_API_KEY);
}

// UGA Specialized Agents Configuration
// Load enhanced UGA agents and comprehensive knowledge
const UGA_ENHANCED_AGENTS = require('./uga-enhanced-agents.js');
const UGA_KNOWLEDGE = require('./uga-comprehensive-knowledge.js');

const UGA_AGENTS = UGA_ENHANCED_AGENTS;

// Enhanced Agent Selection Logic
function selectAgent(message) {
  const messageLower = message.toLowerCase();
  const scores = {};

  // High-priority keywords that should strongly influence agent selection
  const priorityKeywords = {
    'student_life': ['dining', 'food', 'meal', 'eat', 'housing', 'dorm', 'residence', 'clubs', 'organizations', 'greek'],
    'athletics': ['football', 'basketball', 'sports', 'athletics', 'game', 'schedule', 'tickets', 'bulldogs', 'dawgs'],
    'academic': ['course', 'class', 'degree', 'major', 'graduation', 'gpa', 'transcript', 'registration', 'professor'],
    'general': ['admissions', 'apply', 'contact', 'directions', 'map', 'location', 'visit']
  };

  // Calculate relevance scores for each agent
  Object.keys(UGA_AGENTS).forEach(agentKey => {
    const agent = UGA_AGENTS[agentKey];
    scores[agentKey] = 0;

    // Check priority keywords first (higher weight)
    if (priorityKeywords[agentKey]) {
      priorityKeywords[agentKey].forEach(keyword => {
        if (messageLower.includes(keyword)) {
          scores[agentKey] += 3; // Higher weight for priority keywords
        }
      });
    }

    // Check regular domain keywords
    agent.domains.forEach(domain => {
      if (messageLower.includes(domain)) {
        scores[agentKey] += 1;
      }
    });
  });

  // Find the agent with the highest score
  const bestAgent = Object.keys(scores).reduce((a, b) =>
    scores[a] > scores[b] ? a : b
  );

  // If no specific matches found, use general agent
  return scores[bestAgent] > 0 ? bestAgent : 'general';
}

// Function to extract relevant UGA knowledge based on message content
function getRelevantUGAKnowledge(message, agentType) {
  const messageLower = message.toLowerCase();
  let relevantKnowledge = [];

  // Extract relevant knowledge sections based on agent type and message content
  try {
    switch (agentType) {
      case 'academic':
        if (UGA_KNOWLEDGE.academics) {
          if (messageLower.includes('college') || messageLower.includes('school') || messageLower.includes('department')) {
            relevantKnowledge.push('COLLEGES & SCHOOLS:');
            Object.keys(UGA_KNOWLEDGE.academics.colleges).forEach(collegeName => {
              const college = UGA_KNOWLEDGE.academics.colleges[collegeName];
              relevantKnowledge.push(`- ${collegeName}: ${college.description}`);
              if (college.popular_majors) {
                relevantKnowledge.push(`  Popular majors: ${college.popular_majors.join(', ')}`);
              }
            });
          }
          if (messageLower.includes('graduation') || messageLower.includes('requirement') || messageLower.includes('credit')) {
            relevantKnowledge.push('\nGRADUATION REQUIREMENTS:');
            relevantKnowledge.push(`- Total hours: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.total_hours}`);
            relevantKnowledge.push(`- Core curriculum: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.core_curriculum} hours`);
            relevantKnowledge.push(`- GPA requirement: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.gpa_requirement}`);
            relevantKnowledge.push(`- Residency: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.residency_requirement}`);
          }
        }
        break;

      case 'student_life':
        if (UGA_KNOWLEDGE.student_life) {
          if (messageLower.includes('dining') || messageLower.includes('food') || messageLower.includes('meal')) {
            relevantKnowledge.push('DINING OPTIONS:');
            relevantKnowledge.push(`- Dining halls: ${UGA_KNOWLEDGE.student_life.dining.dining_halls.join(', ')}`);
            relevantKnowledge.push(`- Popular spots: ${UGA_KNOWLEDGE.student_life.dining.popular_spots.join(', ')}`);
          }
          if (messageLower.includes('housing') || messageLower.includes('dorm') || messageLower.includes('residence')) {
            relevantKnowledge.push('HOUSING:');
            relevantKnowledge.push(`- Residence halls: ${UGA_KNOWLEDGE.student_life.housing.residence_halls.join(', ')}`);
            relevantKnowledge.push(`- Housing types: ${UGA_KNOWLEDGE.student_life.housing.housing_types.join(', ')}`);
          }
          if (messageLower.includes('organization') || messageLower.includes('club') || messageLower.includes('greek')) {
            relevantKnowledge.push('STUDENT ORGANIZATIONS:');
            relevantKnowledge.push(`- Total: ${UGA_KNOWLEDGE.student_life.organizations.total_count}`);
            relevantKnowledge.push(`- Greek life: ${UGA_KNOWLEDGE.student_life.organizations.greek_life.fraternities} fraternities, ${UGA_KNOWLEDGE.student_life.organizations.greek_life.sororities} sororities`);
          }
        }
        break;

      case 'athletics':
        if (UGA_KNOWLEDGE.athletics) {
          if (messageLower.includes('football')) {
            relevantKnowledge.push('FOOTBALL:');
            relevantKnowledge.push(`- Stadium: ${UGA_KNOWLEDGE.athletics.sports.football.stadium} (capacity: ${UGA_KNOWLEDGE.athletics.sports.football.capacity.toLocaleString()})`);
            relevantKnowledge.push(`- Coach: ${UGA_KNOWLEDGE.athletics.sports.football.coach}`);
            relevantKnowledge.push(`- National Championships: ${UGA_KNOWLEDGE.athletics.sports.football.national_championships.join(', ')}`);
          }
          if (messageLower.includes('basketball')) {
            relevantKnowledge.push('BASKETBALL:');
            relevantKnowledge.push(`- Arena: ${UGA_KNOWLEDGE.athletics.sports.basketball.mens.arena} (capacity: ${UGA_KNOWLEDGE.athletics.sports.basketball.mens.capacity.toLocaleString()})`);
            relevantKnowledge.push(`- Men's Coach: ${UGA_KNOWLEDGE.athletics.sports.basketball.mens.coach}`);
            relevantKnowledge.push(`- Women's Coach: ${UGA_KNOWLEDGE.athletics.sports.basketball.womens.coach}`);
          }
        }
        break;

      case 'general':
        if (UGA_KNOWLEDGE.campus || UGA_KNOWLEDGE.admissions) {
          if (messageLower.includes('location') || messageLower.includes('address') || messageLower.includes('athens')) {
            relevantKnowledge.push('CAMPUS LOCATION:');
            relevantKnowledge.push(`- Location: ${UGA_KNOWLEDGE.campus.location.city}, ${UGA_KNOWLEDGE.campus.location.state}`);
            relevantKnowledge.push(`- Size: ${UGA_KNOWLEDGE.campus.size.total_acres} acres`);
            relevantKnowledge.push(`- Students: ${UGA_KNOWLEDGE.campus.size.students}`);
          }
          if (messageLower.includes('admission') || messageLower.includes('apply') || messageLower.includes('tuition')) {
            relevantKnowledge.push('ADMISSIONS:');
            relevantKnowledge.push(`- Acceptance rate: ${UGA_KNOWLEDGE.admissions.undergraduate.acceptance_rate}`);
            relevantKnowledge.push(`- SAT range: ${UGA_KNOWLEDGE.admissions.undergraduate.middle_50_sat}`);
            relevantKnowledge.push(`- In-state tuition: ${UGA_KNOWLEDGE.admissions.tuition_and_fees.in_state_undergraduate}`);
          }
        }
        break;
    }
  } catch (error) {
    console.log('Knowledge extraction error:', error.message);
  }

  return relevantKnowledge.length > 0 ? relevantKnowledge.join('\n') : null;
}

// Enhanced function to determine if web search should be used
function shouldUseWebSearch(message) {
  const messageLower = message.toLowerCase();

  // Keywords that suggest current/real-time information is needed
  const currentInfoKeywords = [
    'current', 'today', 'now', 'latest', 'recent', 'this week', 'this month', 'this year',
    'hours', 'schedule', 'deadline', 'when', 'what time', 'how much', 'cost',
    'events', 'happening', 'open', 'closed', 'available', 'score', 'news',
    '2024', '2025', 'spring', 'fall', 'summer'
  ];

  // UGA-specific topics that benefit from current information
  const ugaTopics = [
    'registration', 'enrollment', 'tuition', 'fees', 'dining', 'housing',
    'football', 'basketball', 'game', 'ticket', 'event', 'deadline',
    'faculty', 'professor', 'course', 'class', 'calendar'
  ];

  // Check if message contains current info keywords
  const hasCurrentKeywords = currentInfoKeywords.some(keyword =>
    messageLower.includes(keyword)
  );

  // Check if message contains UGA topics
  const hasUGATopic = ugaTopics.some(topic =>
    messageLower.includes(topic)
  );

  // Use web search if asking for current info OR UGA-specific topics
  return hasCurrentKeywords || hasUGATopic;
}

// Enhanced function to extract search query from user message
function extractSearchQuery(message, agentType) {
  // Remove common question words and focus on the core topic
  const cleanMessage = message
    .toLowerCase()
    .replace(/^(what|when|where|how|why|can you|tell me|find|search)\s+/g, '')
    .replace(/\b(about|for|on|the|a|an|is|are|were|was)\b/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();

  // Add UGA context to make search more specific
  return `UGA ${cleanMessage}`;
}

// Enhanced Hugging Face integration with agent support and web search
async function callHuggingFace(message, agentType = null) {
  if (!hfClient) {
    throw new Error('Hugging Face API key not configured');
  }

  const model = process.env.HUGGINGFACE_MODEL || 'meta-llama/Llama-3.1-8B-Instruct';
  const startTime = Date.now();

  // Select agent if not specified
  if (!agentType) {
    agentType = selectAgent(message);
  }

  const agent = UGA_AGENTS[agentType] || UGA_AGENTS.general;

  console.log(`πŸ€— ${agent.emoji} Calling Hugging Face with ${agent.name} (${model})`);

  // Extract relevant UGA knowledge for the message
  const ugaKnowledge = getRelevantUGAKnowledge(message, agentType);

  // Check if we should use web search
  let searchResults = null;
  let enhancedMessage = message;

  // Build enhanced message with UGA knowledge
  if (ugaKnowledge) {
    enhancedMessage = `User Question: ${message}

Relevant UGA Knowledge:
${ugaKnowledge}

Please use the above UGA knowledge to provide an accurate, helpful response. Keep responses concise (2-3 sentences max).`;
  }

  if (shouldUseWebSearch(message)) {
    try {
      console.log(`πŸ” ${agent.emoji} Performing web search for enhanced response`);
      const searchQuery = extractSearchQuery(message, agentType);
      const searchResponse = await webSearchService.search(searchQuery, agentType);

      if (searchResponse.results && searchResponse.results.length > 0) {
        searchResults = searchResponse;

        // Create detailed context from search results
        const searchContext = searchResponse.results
          .slice(0, 5) // Top 5 results for better coverage
          .map((result, index) => {
            return `Result ${index + 1}:
Title: ${result.title}
URL: ${result.url}
Content: ${result.snippet}
Source: ${result.displayLink || 'N/A'}`;
          })
          .join('\n\n');

        // Enhanced AI prompt for better search result analysis
        enhancedMessage = `User Question: ${message}

${ugaKnowledge ? `UGA Knowledge Base Information:\n${ugaKnowledge}\n\n` : ''}Current Real-Time Search Results:
${searchContext}

CRITICAL INSTRUCTIONS FOR AI RESPONSE:
1. EXTRACT SPECIFIC DETAILS: Look for exact times, hours, dates, locations, phone numbers, addresses, prices, and specific requirements in the search results
2. PRIORITIZE CURRENT INFORMATION: Focus on the most recent and up-to-date information from official UGA sources
3. BE PRECISE: If asking about hours, provide the exact operating hours. If asking about locations, provide specific building names and addresses
4. SYNTHESIZE MULTIPLE SOURCES: Combine information from different search results to give a complete answer
5. CITE AUTHORITATIVE SOURCES: Prioritize uga.edu, dining.uga.edu, georgiadogs.com, and other official UGA domains
6. PROVIDE ACTIONABLE INFORMATION: Include relevant links, phone numbers, or next steps when available
7. HANDLE MISSING INFO: If specific details aren't found, clearly state what information is not available and suggest where to find it
8. FORMAT CLEARLY: Present information in a clear, organized manner with specific details highlighted

EXAMPLE GOOD RESPONSES:
- "The Dining Commons is open Monday-Friday 7:00 AM - 9:00 PM, Saturday-Sunday 8:00 AM - 8:00 PM. Contact: (706) 542-1234. Full hours: dining.uga.edu/hours"
- "Registration deadline is March 15, 2024. Requirements include 2.5 GPA minimum. Apply at: reg.uga.edu/registration"

Please provide the most specific, detailed, and actionable answer possible using the search results above.`;
      }
    } catch (searchError) {
      console.error(`πŸ” Search failed for ${agent.name}:`, searchError.message);
      // Continue without search results
    }
  }

  try {
    const response = await hfClient.chatCompletion({
      model: model,
      messages: [
        {
          role: 'system',
          content: agent.systemPrompt
        },
        {
          role: 'user',
          content: enhancedMessage
        }
      ],
      max_tokens: parseInt(process.env.HUGGINGFACE_MAX_TOKENS) || 400,
      temperature: parseFloat(process.env.HUGGINGFACE_TEMPERATURE) || 0.7,
      top_p: parseFloat(process.env.HUGGINGFACE_TOP_P) || 0.9
    });

    const responseTime = Date.now() - startTime;
    const content = response.choices[0].message.content;

    console.log(`βœ… ${agent.emoji} ${agent.name} response: ${content.length} chars in ${responseTime}ms`);

    return {
      content: content,
      metadata: {
        model: model,
        responseTime: responseTime,
        tokens: response.usage?.total_tokens || 0,
        provider: 'huggingface',
        agent: agentType,
        agentName: agent.name,
        agentEmoji: agent.emoji,
        searchUsed: searchResults !== null,
        searchProvider: searchResults?.provider,
        searchFromCache: searchResults?.fromCache
      }
    };
  } catch (error) {
    console.error('❌ Hugging Face API error:', error.message);
    throw new Error(`Hugging Face API error: ${error.message}`);
  }
}

// Enhanced Ollama integration with agent support and web search
async function callOllama(message, agentType = null) {
  const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
  const model = process.env.LOCAL_AI_MODEL || 'tinyllama';

  const startTime = Date.now();

  // Select agent if not specified
  if (!agentType) {
    agentType = selectAgent(message);
  }

  const agent = UGA_AGENTS[agentType] || UGA_AGENTS.general;

  console.log(`πŸ€– ${agent.emoji} Calling Ollama with ${agent.name}: ${ollamaUrl}/api/generate (${model})`);

  // Extract relevant UGA knowledge for the message
  const ugaKnowledge = getRelevantUGAKnowledge(message, agentType);

  // Check if we should use web search
  let searchResults = null;
  let enhancedPrompt = `${agent.systemPrompt}

${ugaKnowledge ? `Relevant UGA Knowledge:\n${ugaKnowledge}\n\n` : ''}Question: ${message}

Answer:`;

  if (shouldUseWebSearch(message)) {
    try {
      console.log(`πŸ” ${agent.emoji} Performing web search for enhanced response`);
      const searchQuery = extractSearchQuery(message, agentType);
      const searchResponse = await webSearchService.search(searchQuery, agentType);

      if (searchResponse.results && searchResponse.results.length > 0) {
        searchResults = searchResponse;

        // Create detailed context from search results
        const searchContext = searchResponse.results
          .slice(0, 5) // Top 5 results for better coverage
          .map((result, index) => {
            return `Result ${index + 1}:
Title: ${result.title}
URL: ${result.url}
Content: ${result.snippet}
Source: ${result.displayLink || 'N/A'}`;
          })
          .join('\n\n');

        enhancedPrompt = `${agent.systemPrompt}

${ugaKnowledge ? `UGA Knowledge Base Information:\n${ugaKnowledge}\n\n` : ''}Current Real-Time Search Results:
${searchContext}

Question: ${message}

INSTRUCTIONS FOR RESPONSE:
1. Analyze all search results carefully to find the most accurate and current information
2. Synthesize information from multiple sources when possible
3. Prioritize official UGA sources (uga.edu, georgiadogs.com) over third-party sources
4. Include specific details like dates, times, locations when available in search results
5. Provide 2-3 of the most relevant and useful source links
6. Keep response informative but concise (2-3 sentences maximum)

Answer using both the UGA knowledge base and current search results:`;
      }
    } catch (searchError) {
      console.error(`πŸ” Search failed for ${agent.name}:`, searchError.message);
      // Continue without search results
    }
  }

  const response = await fetch(`${ollamaUrl}/api/generate`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: model,
      prompt: enhancedPrompt,
      stream: false,
      options: {
        temperature: 0.7,
        top_p: 0.9,
        top_k: 40
      }
    }),
    timeout: 30000 // 30 second timeout
  });

  if (!response.ok) {
    throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  const responseTime = Date.now() - startTime;

  console.log(`βœ… ${agent.emoji} ${agent.name} response: ${data.response.length} chars in ${responseTime}ms`);

  return {
    content: data.response,
    metadata: {
      model: model,
      responseTime: responseTime,
      tokens: data.eval_count || 0,
      provider: 'ollama',
      agent: agentType,
      agentName: agent.name,
      agentEmoji: agent.emoji,
      searchUsed: searchResults !== null,
      searchProvider: searchResults?.provider,
      searchFromCache: searchResults?.fromCache
    }
  };
}

// Smart AI router with agent support and fallback mechanism
async function callAI(message, agentType = null) {
  const useHuggingFace = process.env.USE_HUGGINGFACE === 'true';
  const useOllama = process.env.USE_LOCAL_AI === 'true';

  // Auto-select agent if not specified
  if (!agentType) {
    agentType = selectAgent(message);
  }

  const agent = UGA_AGENTS[agentType] || UGA_AGENTS.general;

  console.log(`🧠 AI Router - Agent: ${agent.emoji} ${agent.name}, HuggingFace: ${useHuggingFace}, Ollama: ${useOllama}`);

  // Primary choice: Hugging Face if enabled and configured
  if (useHuggingFace && process.env.HUGGINGFACE_API_KEY) {
    try {
      return await callHuggingFace(message, agentType);
    } catch (error) {
      console.error('❌ Hugging Face failed, trying fallback...', error.message);

      // Fallback to Ollama if available
      if (useOllama) {
        try {
          return await callOllama(message, agentType);
        } catch (ollamaError) {
          console.error('❌ Ollama fallback also failed:', ollamaError.message);
          throw new Error('Both Hugging Face and Ollama services are unavailable');
        }
      } else {
        throw error;
      }
    }
  }

  // Primary choice: Ollama if Hugging Face is not enabled
  if (useOllama) {
    try {
      return await callOllama(message, agentType);
    } catch (error) {
      console.error('❌ Ollama failed, trying fallback...', error.message);

      // Fallback to Hugging Face if available
      if (process.env.HUGGINGFACE_API_KEY) {
        try {
          return await callHuggingFace(message, agentType);
        } catch (hfError) {
          console.error('❌ Hugging Face fallback also failed:', hfError.message);
          throw new Error('Both Ollama and Hugging Face services are unavailable');
        }
      } else {
        throw error;
      }
    }
  }

  throw new Error('No AI services are enabled. Please configure either Ollama or Hugging Face.');
}

// =================================================================
// WEB SEARCH API ENDPOINTS
// =================================================================

// Direct web search endpoint
app.post('/api/search', async (req, res) => {
  try {
    const { query, agentType = 'general' } = req.body;

    if (!query || typeof query !== 'string' || query.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid search query is required'
      });
    }

    console.log(`πŸ” Direct search request: "${query}" (agent: ${agentType})`);

    const searchResults = await webSearchService.search(query.trim(), agentType);

    res.json({
      success: true,
      data: {
        query: query.trim(),
        agentType,
        results: searchResults.results,
        fromCache: searchResults.fromCache,
        provider: searchResults.provider,
        timestamp: searchResults.timestamp,
        totalResults: searchResults.results.length
      }
    });

  } catch (error) {
    console.error('❌ Search API error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Search service unavailable',
      details: error.message
    });
  }
});

// Current UGA info search endpoint
app.post('/api/search/current', async (req, res) => {
  try {
    const { topic, agentType = 'general' } = req.body;

    if (!topic || typeof topic !== 'string' || topic.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid topic is required'
      });
    }

    console.log(`πŸ” Current UGA info search: "${topic}" (agent: ${agentType})`);

    const searchResults = await webSearchService.searchCurrentUGAInfo(topic.trim(), agentType);

    res.json({
      success: true,
      data: {
        topic: topic.trim(),
        agentType,
        results: searchResults.results,
        fromCache: searchResults.fromCache,
        provider: searchResults.provider,
        timestamp: searchResults.timestamp,
        totalResults: searchResults.results.length
      }
    });

  } catch (error) {
    console.error('❌ Current search API error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Current search service unavailable',
      details: error.message
    });
  }
});

// Get search suggestions for agent types
app.get('/api/search/suggestions/:agentType?', (req, res) => {
  try {
    const { agentType = 'general' } = req.params;
    const suggestions = webSearchService.getUGASearchSuggestions(agentType);

    res.json({
      success: true,
      data: {
        agentType,
        suggestions,
        totalSuggestions: suggestions.length
      }
    });
  } catch (error) {
    console.error('❌ Search suggestions error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get search suggestions',
      details: error.message
    });
  }
});

// Search cache management endpoints
app.get('/api/search/cache/stats', (req, res) => {
  try {
    const stats = webSearchService.getCacheStats();
    res.json({
      success: true,
      data: {
        cache: stats,
        cacheEnabled: process.env.ENABLE_WEB_SEARCH === 'true',
        cacheTTL: process.env.WEB_SEARCH_CACHE_TTL || 1800
      }
    });
  } catch (error) {
    console.error('❌ Cache stats error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get cache statistics'
    });
  }
});

app.post('/api/search/cache/clear', (req, res) => {
  try {
    const result = webSearchService.clearCache();
    console.log('πŸ—‘οΈ Search cache cleared by admin request');
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('❌ Cache clear error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to clear search cache'
    });
  }
});

// Web search status and configuration
app.get('/api/search/status', (req, res) => {
  try {
    const status = {
      enabled: process.env.ENABLE_WEB_SEARCH === 'true',
      providers: {
        google: !!(process.env.GOOGLE_SEARCH_API_KEY && process.env.GOOGLE_SEARCH_ENGINE_ID),
        bing: !!process.env.BING_SEARCH_API_KEY,
        searxng: !!process.env.SEARXNG_URL
      },
      cache: {
        enabled: true,
        ttl: process.env.WEB_SEARCH_CACHE_TTL || 1800,
        stats: webSearchService.getCacheStats()
      }
    };

    res.json({
      success: true,
      data: status
    });
  } catch (error) {
    console.error('❌ Search status error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get search status'
    });
  }
});

// =================================================================
// END WEB SEARCH API ENDPOINTS
// =================================================================

// Enhanced health check for both services
app.get('/health', async (req, res) => {
  try {
    const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
    const response = await fetch(`${ollamaUrl}/api/tags`, { timeout: 5000 });

    res.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      ollama: response.ok ? 'connected' : 'error',
      model: process.env.LOCAL_AI_MODEL || 'tinyllama'
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      error: error.message,
      ollama: 'disconnected'
    });
  }
});

// Enhanced AI Chat endpoint with agent support and history
app.post('/api/chat', async (req, res) => {
  try {
    const { message, sessionId, userId, agentType } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    console.log(`πŸ“ Processing: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    // Use the smart AI router with agent support
    const result = await callAI(message.trim(), agentType);

    // Save to chat history if userId and sessionId are provided
    if (userId && sessionId) {
      try {
        const userHistory = await loadUserHistory(userId);

        // Get or create session
        let session = userHistory.sessions[sessionId];
        if (!session) {
          session = createChatSession();
          session.id = sessionId;
          userHistory.sessions[sessionId] = session;
          userHistory.metadata.totalSessions++;
        }

        // Add user message
        addMessageToSession(session, message.trim(), 'user');

        // Add bot response with agent information
        addMessageToSession(session, result.content, 'bot', result.metadata);

        // Update user metadata
        userHistory.metadata.totalMessages += 2;

        // Save updated history
        await saveUserHistory(userId, userHistory);
      } catch (historyError) {
        console.error('Error saving to chat history:', historyError);
        // Continue with response even if history save fails
      }
    }

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ AI Error:', error.message);

    // Return error instead of fallback to ensure real AI is working
    res.status(500).json({
      success: false,
      error: 'AI service unavailable',
      details: error.message,
      message: 'Please ensure AI service is running'
    });
  }
});

// Get available agents
app.get('/api/agents', (req, res) => {
  const agents = Object.keys(UGA_AGENTS).map(key => {
    const agent = UGA_AGENTS[key];
    return {
      id: key,
      name: agent.name,
      emoji: agent.emoji,
      domains: agent.domains,
      description: agent.systemPrompt.split('\n')[0].replace('You are the ', '').replace('You are a ', '')
    };
  });

  res.json({
    success: true,
    data: {
      agents,
      totalAgents: agents.length,
      defaultAgent: 'general'
    }
  });
});

// Agent-specific chat endpoints
app.post('/api/chat/academic', async (req, res) => {
  try {
    const { message, sessionId, userId } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    console.log(`πŸ“ Processing with Academic Advisor: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    const result = await callAI(message.trim(), 'academic');

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ Academic Advisor Error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Academic advisor service unavailable',
      details: error.message
    });
  }
});

app.post('/api/chat/student-life', async (req, res) => {
  try {
    const { message, sessionId, userId } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    console.log(`πŸ“ Processing with Student Life Guide: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    const result = await callAI(message.trim(), 'student_life');

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ Student Life Guide Error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Student life guide service unavailable',
      details: error.message
    });
  }
});

app.post('/api/chat/athletics', async (req, res) => {
  try {
    const { message, sessionId, userId } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    console.log(`πŸ“ Processing with Athletics Assistant: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    const result = await callAI(message.trim(), 'athletics');

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ Athletics Assistant Error:', error.message);
    res.status(500).json({
      success: false,
      error: 'Athletics assistant service unavailable',
      details: error.message
    });
  }
});

app.post('/api/chat/general', async (req, res) => {
  try {
    const { message, sessionId, userId } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    console.log(`πŸ“ Processing with General Helper: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    const result = await callAI(message.trim(), 'general');

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ General Helper Error:', error.message);
    res.status(500).json({
      success: false,
      error: 'General helper service unavailable',
      details: error.message
    });
  }
});

// New endpoint specifically for Hugging Face (with agent support)
app.post('/api/chat/huggingface', async (req, res) => {
  try {
    const { message, agentType } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    if (!process.env.HUGGINGFACE_API_KEY) {
      return res.status(400).json({
        success: false,
        error: 'Hugging Face API key not configured'
      });
    }

    console.log(`πŸ“ Processing with Hugging Face: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    const result = await callHuggingFace(message.trim(), agentType);

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ Hugging Face Error:', error.message);

    res.status(500).json({
      success: false,
      error: 'Hugging Face service unavailable',
      details: error.message,
      message: 'Please check your Hugging Face API key and model configuration'
    });
  }
});

// New endpoint specifically for Ollama (with agent support)
app.post('/api/chat/ollama', async (req, res) => {
  try {
    const { message, agentType } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Valid message is required'
      });
    }

    console.log(`πŸ“ Processing with Ollama: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);

    const result = await callOllama(message.trim(), agentType);

    res.json({
      success: true,
      response: result.content,
      metadata: result.metadata,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('❌ Ollama Error:', error.message);

    res.status(500).json({
      success: false,
      error: 'Ollama service unavailable',
      details: error.message,
      message: 'Please ensure Ollama is running with the correct model'
    });
  }
});

// Chat History API Endpoints

// Get user's chat sessions
app.get('/api/history/sessions/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const userHistory = await loadUserHistory(userId);

    // Convert sessions object to array and sort by last activity
    const sessions = Object.values(userHistory.sessions)
      .sort((a, b) => new Date(b.metadata.lastActivity) - new Date(a.metadata.lastActivity));

    res.json({
      success: true,
      data: {
        sessions,
        metadata: userHistory.metadata
      }
    });
  } catch (error) {
    console.error('Error loading chat sessions:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to load chat sessions'
    });
  }
});

// Get specific chat session
app.get('/api/history/session/:userId/:sessionId', async (req, res) => {
  try {
    const { userId, sessionId } = req.params;
    const userHistory = await loadUserHistory(userId);

    const session = userHistory.sessions[sessionId];
    if (!session) {
      return res.status(404).json({
        success: false,
        error: 'Session not found'
      });
    }

    res.json({
      success: true,
      data: session
    });
  } catch (error) {
    console.error('Error loading chat session:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to load chat session'
    });
  }
});

// Create new chat session
app.post('/api/history/session/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { title } = req.body;

    const userHistory = await loadUserHistory(userId);
    const newSession = createChatSession(title);

    userHistory.sessions[newSession.id] = newSession;
    userHistory.metadata.totalSessions++;

    await saveUserHistory(userId, userHistory);

    res.json({
      success: true,
      data: newSession
    });
  } catch (error) {
    console.error('Error creating chat session:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to create chat session'
    });
  }
});

// Update chat session (rename, etc.)
app.put('/api/history/session/:userId/:sessionId', async (req, res) => {
  try {
    const { userId, sessionId } = req.params;
    const { title } = req.body;

    const userHistory = await loadUserHistory(userId);
    const session = userHistory.sessions[sessionId];

    if (!session) {
      return res.status(404).json({
        success: false,
        error: 'Session not found'
      });
    }

    if (title) {
      session.title = title;
      session.metadata.lastActivity = new Date().toISOString();
    }

    await saveUserHistory(userId, userHistory);

    res.json({
      success: true,
      data: session
    });
  } catch (error) {
    console.error('Error updating chat session:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to update chat session'
    });
  }
});

// Delete chat session
app.delete('/api/history/session/:userId/:sessionId', async (req, res) => {
  try {
    const { userId, sessionId } = req.params;
    const userHistory = await loadUserHistory(userId);

    if (!userHistory.sessions[sessionId]) {
      return res.status(404).json({
        success: false,
        error: 'Session not found'
      });
    }

    // Update metadata
    const session = userHistory.sessions[sessionId];
    userHistory.metadata.totalMessages -= session.metadata.messageCount;
    userHistory.metadata.totalSessions--;

    delete userHistory.sessions[sessionId];
    await saveUserHistory(userId, userHistory);

    res.json({
      success: true,
      message: 'Session deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting chat session:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to delete chat session'
    });
  }
});

// Search chat history
app.get('/api/history/search/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { q: query, limit = 50 } = req.query;

    if (!query || query.trim().length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Search query is required'
      });
    }

    const userHistory = await loadUserHistory(userId);
    const searchResults = [];
    const searchTerm = query.toLowerCase();

    // Search through all sessions and messages
    Object.values(userHistory.sessions).forEach(session => {
      // Check session title
      if (session.title.toLowerCase().includes(searchTerm)) {
        searchResults.push({
          type: 'session',
          sessionId: session.id,
          title: session.title,
          lastActivity: session.metadata.lastActivity,
          messageCount: session.metadata.messageCount
        });
      }

      // Check messages
      session.messages.forEach(message => {
        if (message.content.toLowerCase().includes(searchTerm)) {
          searchResults.push({
            type: 'message',
            sessionId: session.id,
            sessionTitle: session.title,
            messageId: message.id,
            content: message.content,
            sender: message.sender,
            timestamp: message.timestamp,
            // Highlight the search term (simple implementation)
            highlight: message.content.substring(
              Math.max(0, message.content.toLowerCase().indexOf(searchTerm) - 50),
              Math.min(message.content.length, message.content.toLowerCase().indexOf(searchTerm) + searchTerm.length + 50)
            )
          });
        }
      });
    });

    // Sort by relevance (sessions first, then by timestamp)
    searchResults.sort((a, b) => {
      if (a.type !== b.type) {
        return a.type === 'session' ? -1 : 1;
      }
      const aTime = new Date(a.timestamp || a.lastActivity);
      const bTime = new Date(b.timestamp || b.lastActivity);
      return bTime - aTime;
    });

    res.json({
      success: true,
      data: {
        query,
        results: searchResults.slice(0, parseInt(limit)),
        totalResults: searchResults.length
      }
    });
  } catch (error) {
    console.error('Error searching chat history:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to search chat history'
    });
  }
});

// Export chat history
app.get('/api/history/export/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { format = 'json', sessionId } = req.query;

    const userHistory = await loadUserHistory(userId);

    let exportData;
    if (sessionId) {
      // Export specific session
      const session = userHistory.sessions[sessionId];
      if (!session) {
        return res.status(404).json({
          success: false,
          error: 'Session not found'
        });
      }
      exportData = session;
    } else {
      // Export all history
      exportData = userHistory;
    }

    if (format === 'json') {
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Content-Disposition', `attachment; filename="chat-history-${userId}-${Date.now()}.json"`);
      res.json(exportData);
    } else if (format === 'txt') {
      // Convert to plain text format
      let textContent = '';

      if (sessionId) {
        const session = exportData;
        textContent = `Chat Session: ${session.title}\n`;
        textContent += `Created: ${new Date(session.metadata.createdAt).toLocaleString()}\n`;
        textContent += `Messages: ${session.metadata.messageCount}\n\n`;

        session.messages.forEach(msg => {
          textContent += `[${new Date(msg.timestamp).toLocaleString()}] ${msg.sender.toUpperCase()}: ${msg.content}\n\n`;
        });
      } else {
        textContent = `Chat History Export for User: ${userId}\n`;
        textContent += `Export Date: ${new Date().toLocaleString()}\n`;
        textContent += `Total Sessions: ${exportData.metadata.totalSessions}\n`;
        textContent += `Total Messages: ${exportData.metadata.totalMessages}\n\n`;

        Object.values(exportData.sessions).forEach(session => {
          textContent += `=== ${session.title} ===\n`;
          textContent += `Created: ${new Date(session.metadata.createdAt).toLocaleString()}\n\n`;

          session.messages.forEach(msg => {
            textContent += `[${new Date(msg.timestamp).toLocaleString()}] ${msg.sender.toUpperCase()}: ${msg.content}\n\n`;
          });

          textContent += '\n---\n\n';
        });
      }

      res.setHeader('Content-Type', 'text/plain');
      res.setHeader('Content-Disposition', `attachment; filename="chat-history-${userId}-${Date.now()}.txt"`);
      res.send(textContent);
    } else {
      res.status(400).json({
        success: false,
        error: 'Unsupported export format. Use json or txt.'
      });
    }
  } catch (error) {
    console.error('Error exporting chat history:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to export chat history'
    });
  }
});

// Serve files
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/dashboard', (req, res) => {
  res.sendFile(path.join(__dirname, 'dashboard.html'));
});

app.get('/landing.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'landing.html'));
});

// Start server
app.listen(PORT, '0.0.0.0', async () => {
  // Initialize chat history directory
  await ensureChatHistoryDir();

  console.log(`πŸš€ edi.chat Multi-Agent AI Server running on port ${PORT}`);
  console.log(`πŸ€– Ollama URL: ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`);
  console.log(`πŸ€— HuggingFace: ${process.env.HUGGINGFACE_API_KEY ? 'Enabled' : 'Disabled'}`);
  console.log(`πŸ“¦ Model: ${process.env.LOCAL_AI_MODEL || 'tinyllama'}`);
  console.log(`πŸ’Ύ Chat History: ${CHAT_HISTORY_DIR}`);
  console.log('');

  // Web Search Status
  console.log('πŸ” Web Search Integration:');
  console.log(`   β€’ Status: ${process.env.ENABLE_WEB_SEARCH === 'true' ? 'Enabled' : 'Disabled'}`);
  console.log(`   β€’ Google API: ${process.env.GOOGLE_SEARCH_API_KEY && process.env.GOOGLE_SEARCH_ENGINE_ID ? 'Configured' : 'Not Configured'}`);
  console.log(`   β€’ Bing API: ${process.env.BING_SEARCH_API_KEY ? 'Configured' : 'Not Configured'}`);
  console.log(`   β€’ SearXNG: ${process.env.SEARXNG_URL ? 'Configured' : 'Using Default'}`);
  console.log(`   β€’ Cache TTL: ${process.env.WEB_SEARCH_CACHE_TTL || 1800}s`);
  console.log('');

  console.log('πŸŽ“ UGA Specialized Agents with Real-Time Search:');
  Object.keys(UGA_AGENTS).forEach(key => {
    const agent = UGA_AGENTS[key];
    console.log(`   ${agent.emoji} ${agent.name} (web search enabled)`);
  });
  console.log('');
  console.log(`🌐 Dashboard: http://localhost:${PORT}/dashboard`);
  console.log(`🏠 Landing: http://localhost:${PORT}/landing.html`);
  console.log(`❀️  Health: http://localhost:${PORT}/health`);
  console.log(`πŸ€– Agents API: http://localhost:${PORT}/api/agents`);
  console.log(`πŸ” Search Status: http://localhost:${PORT}/api/search/status`);
  console.log('');
  console.log('πŸ“š Agent Endpoints:');
  console.log(`   β€’ Academic: POST /api/chat/academic`);
  console.log(`   β€’ Student Life: POST /api/chat/student-life`);
  console.log(`   β€’ Athletics: POST /api/chat/athletics`);
  console.log(`   β€’ General: POST /api/chat/general`);
  console.log(`   β€’ Auto-select: POST /api/chat`);
  console.log('');
  console.log('πŸ” Web Search Endpoints:');
  console.log(`   β€’ Direct Search: POST /api/search`);
  console.log(`   β€’ Current Info: POST /api/search/current`);
  console.log(`   β€’ Suggestions: GET /api/search/suggestions/:agentType`);
  console.log(`   β€’ Cache Stats: GET /api/search/cache/stats`);
  console.log(`   β€’ Clear Cache: POST /api/search/cache/clear`);
  console.log('');
  console.log('🧠 Multi-Agent AI Router with Real-Time Web Search & Chat History enabled!');
});