File size: 67,110 Bytes
ea46ec8
 
 
 
 
 
 
 
4498d8e
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
4c07e01
ea46ec8
 
4498d8e
4c07e01
 
 
 
 
 
 
 
ea46ec8
4c07e01
ea46ec8
4498d8e
ea46ec8
4498d8e
 
 
 
 
 
 
ea46ec8
4498d8e
 
 
 
 
 
 
 
ea46ec8
 
4498d8e
 
ea46ec8
 
4498d8e
ea46ec8
 
4498d8e
 
ea46ec8
 
4498d8e
ea46ec8
4498d8e
ea46ec8
 
 
4498d8e
ea46ec8
 
4498d8e
ea46ec8
 
 
 
 
 
 
 
 
 
2c26464
 
 
ea46ec8
2c26464
ea46ec8
 
 
 
 
 
2c26464
 
4498d8e
ea46ec8
4498d8e
 
 
 
 
 
 
 
 
 
 
ea46ec8
2c26464
ea46ec8
 
 
2c26464
ea46ec8
 
 
 
 
2c26464
ea46ec8
2c26464
ea46ec8
 
 
4498d8e
ea46ec8
 
 
 
 
 
2c26464
ea46ec8
 
 
2c26464
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
254afdc
 
 
4498d8e
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
4498d8e
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254afdc
 
4498d8e
254afdc
4498d8e
254afdc
 
 
 
 
 
 
4498d8e
254afdc
 
 
 
 
 
 
 
 
 
4498d8e
254afdc
 
 
 
4498d8e
254afdc
4498d8e
254afdc
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
254afdc
 
 
 
 
 
4498d8e
254afdc
 
 
4498d8e
254afdc
 
4498d8e
254afdc
 
4498d8e
254afdc
 
4498d8e
 
254afdc
4498d8e
254afdc
4498d8e
254afdc
 
 
 
 
 
4498d8e
254afdc
 
 
4498d8e
254afdc
4498d8e
254afdc
4498d8e
254afdc
 
 
4498d8e
254afdc
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
254afdc
4498d8e
254afdc
 
 
 
4498d8e
 
254afdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
ea46ec8
 
4498d8e
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
ea46ec8
4498d8e
 
 
ea46ec8
 
4498d8e
ea46ec8
 
4498d8e
 
ea46ec8
 
4498d8e
 
 
 
 
 
 
 
ea46ec8
 
 
 
254afdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
4c07e01
ea46ec8
 
4c07e01
 
 
 
 
 
ea46ec8
4c07e01
ea46ec8
 
 
43c3569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c07e01
 
 
 
ea46ec8
 
4c07e01
ea46ec8
 
4c07e01
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
4498d8e
 
 
ea46ec8
 
2c26464
4498d8e
2c26464
 
ea46ec8
4498d8e
ea46ec8
 
 
4498d8e
ea46ec8
 
4498d8e
 
ea46ec8
 
4498d8e
2c26464
 
ea46ec8
 
 
 
 
 
2c26464
4498d8e
2c26464
 
4498d8e
2c26464
 
ea46ec8
4498d8e
ea46ec8
 
 
4498d8e
 
ea46ec8
4498d8e
 
 
ea46ec8
 
4498d8e
 
 
ea46ec8
4498d8e
ea46ec8
 
4498d8e
ea46ec8
4498d8e
 
 
 
ea46ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
254afdc
4498d8e
 
254afdc
4498d8e
254afdc
 
 
 
 
 
4498d8e
e142284
 
4498d8e
e142284
254afdc
e142284
 
 
 
4498d8e
 
e142284
254afdc
e142284
 
 
254afdc
ea46ec8
 
 
 
4498d8e
ea46ec8
 
 
 
 
 
 
 
 
254afdc
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
 
 
4498d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
 
 
4498d8e
 
 
 
 
 
 
ea46ec8
 
 
4c07e01
 
 
 
43c3569
 
 
 
4498d8e
4c07e01
43c3569
 
 
 
 
4c07e01
43c3569
4c07e01
43c3569
4c07e01
ea46ec8
4c07e01
ea46ec8
 
 
 
 
 
 
 
 
4c07e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
4498d8e
 
 
 
2c26464
 
 
 
 
 
 
4498d8e
2c26464
4498d8e
2c26464
 
4498d8e
2c26464
4498d8e
2c26464
 
 
 
 
4498d8e
2c26464
 
 
4498d8e
 
2c26464
ea46ec8
 
 
 
 
 
 
 
 
 
 
2c26464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea46ec8
 
 
 
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
from fastapi import FastAPI, HTTPException, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
import asyncio
import json
from datetime import datetime
import time
from typing import List, Dict, Any, Optional
import os
from dotenv import load_dotenv
import plotly
import plotly.graph_objects as go

load_dotenv()

from src.agent.research_agent import Web3ResearchAgent
from src.api.airaa_integration import AIRAAIntegration  
from src.utils.logger import get_logger
from src.utils.config import config
from src.visualizations import CryptoVisualizations

logger = get_logger(__name__)

app = FastAPI(
    title="Web3 Research Co-Pilot",
    description="Professional cryptocurrency research assistant",
    version="2.0.0"
)

# Pydantic models
class QueryRequest(BaseModel):
    query: str
    chat_history: Optional[List[Dict[str, str]]] = []

class QueryResponse(BaseModel):
    success: bool
    response: str
    sources: Optional[List[str]] = []
    metadata: Optional[Dict[str, Any]] = {}
    visualizations: Optional[List[str]] = []
    error: Optional[str] = None

class Web3CoPilotService:
    def __init__(self):
        try:
            logger.info("Initializing Web3 Research Service...")
            logger.info(f"Environment check - GEMINI_API_KEY present: {bool(config.GEMINI_API_KEY)}")
            
            if config.GEMINI_API_KEY:
                logger.info("AI research capabilities enabled")
                try:
                    self.agent = Web3ResearchAgent()
                    self.enabled = self.agent.enabled
                    logger.info(f"Web3ResearchAgent initialized - enabled: {self.enabled}")
                except Exception as e:
                    logger.error(f"Failed to initialize Web3ResearchAgent: {e}")
                    self.agent = None
                    self.enabled = False
            else:
                logger.warning("AI research capabilities disabled - GEMINI_API_KEY not configured")
                self.agent = None
                self.enabled = False
            
            # Initialize integrations
            logger.info("Initializing external integrations...")
            try:
                self.airaa = AIRAAIntegration()
            except Exception as e:
                logger.warning("External integration unavailable")
                self.airaa = None
            
            # Initialize visualization tools
            try:
                self.viz = CryptoVisualizations()
            except Exception as e:
                logger.warning("Visualization tools unavailable")
                self.viz = None
                
            logger.info(f"Service initialized successfully (AI enabled: {self.enabled})")
            
        except Exception as e:
            logger.error(f"Service initialization failed")
            self.enabled = False
            self.agent = None
            self.airaa = None
            self.viz = None
    
    async def process_query(self, query: str) -> QueryResponse:
        """Process research query with comprehensive analysis"""
        logger.info("Processing research request...")
        
        if not query.strip():
            logger.warning("Empty query received")
            return QueryResponse(
                success=False,
                response="Please provide a research query.", 
                error="Empty query"
            )
            
        try:
            if not self.enabled:
                logger.info("Processing in limited mode")
                response = """**Research Assistant - Limited Mode**

API access available for basic cryptocurrency data:
β€’ Market prices and statistics
β€’ DeFi protocol information  
β€’ Network gas fees

Configure GEMINI_API_KEY environment variable for full AI analysis."""
                return QueryResponse(success=True, response=response, sources=["System"])
            
            logger.info("πŸ€– Processing with AI research agent...")
            logger.info(f"πŸ› οΈ Available tools: {[tool.name for tool in self.agent.tools] if self.agent else []}")
            
            result = await self.agent.research_query(query)
            logger.info(f"πŸ”„ Agent research completed: success={result.get('success')}")
            
            if result.get("success"):
                response = result.get("result", "No analysis generated")
                sources = result.get("sources", [])
                metadata = result.get("metadata", {})
                
                logger.info(f"πŸ“Š Response generated: {len(response)} chars, {len(sources)} sources")
                
                # Check for chart data and generate visualizations
                visualizations = []
                chart_data = await self._extract_chart_data_from_response(response)
                if chart_data:
                    chart_html = await self._generate_chart_from_data(chart_data)
                    if chart_html:
                        visualizations.append(chart_html)
                        logger.info("βœ… Chart generated from structured data")
                
                # Clean the response for user display
                cleaned_response = self._clean_agent_response(response)
                    
                # Generate visualizations if relevant data is available  
                if metadata:
                    logger.info("πŸ“ˆ Checking for visualization data...")
                    vis_html = await self._generate_visualizations(metadata, query)
                    if vis_html:
                        visualizations.append(vis_html)
                        logger.info("βœ… Visualization generated")
                
                # Send to AIRAA if enabled
                if self.airaa and self.airaa.enabled:
                    try:
                        await self.airaa.send_research_data(query, response)
                        logger.info("πŸ“€ Data sent to AIRAA")
                    except Exception as e:
                        logger.warning(f"⚠️ AIRAA integration failed: {e}")
                
                return QueryResponse(
                    success=True, 
                    response=cleaned_response, 
                    sources=sources, 
                    metadata=metadata,
                    visualizations=visualizations
                )
            else:
                error_msg = result.get("error", "Research analysis failed")
                logger.error(f"❌ Research failed: {error_msg}")
                return QueryResponse(success=False, response=error_msg, error=error_msg)
            
        except Exception as e:
            logger.error(f"πŸ’₯ Query processing error: {e}", exc_info=True)
            error_msg = f"Processing error: {str(e)}"
            return QueryResponse(success=False, response=error_msg, error=error_msg)
    
    async def _generate_visualizations(self, metadata: Dict[str, Any], query: str) -> Optional[str]:
        """Generate visualizations based on query and metadata"""
        try:
            # Check for price data
            if 'price_data' in metadata:
                symbol = self._extract_symbol_from_query(query)
                fig = self.visualizer.create_price_chart(metadata['price_data'], symbol)
                return plotly.io.to_html(fig, include_plotlyjs='cdn', div_id='price_chart')
            
            # Check for market data
            elif 'market_data' in metadata:
                fig = self.visualizer.create_market_overview(metadata['market_data'])
                return plotly.io.to_html(fig, include_plotlyjs='cdn', div_id='market_overview')
            
            # Check for DeFi data
            elif 'defi_data' in metadata:
                fig = self.visualizer.create_defi_tvl_chart(metadata['defi_data'])
                return plotly.io.to_html(fig, include_plotlyjs='cdn', div_id='defi_chart')
            
            return None
            
        except Exception as e:
            logger.error(f"Visualization generation failed: {e}")
            return None
    
    def _extract_symbol_from_query(self, query: str) -> str:
        """Extract cryptocurrency symbol from query"""
        symbols = ['BTC', 'ETH', 'ADA', 'SOL', 'AVAX', 'MATIC', 'DOT', 'LINK']
        query_upper = query.upper()
        for symbol in symbols:
            if symbol in query_upper:
                return symbol
        return 'BTC'  # Default
    
    async def _extract_chart_data_from_response(self, response: str) -> Optional[Dict[str, Any]]:
        """Extract chart data JSON from agent response"""
        try:
            import re
            import json
            
            logger.info(f"πŸ” Checking response for chart data (length: {len(response)} chars)")
            
            # Look for JSON objects containing chart_type - find opening brace and matching closing brace
            chart_data_found = None
            lines = response.split('\n')
            
            for i, line in enumerate(lines):
                if '"chart_type"' in line and line.strip().startswith('{'):
                    # Found potential start of chart JSON
                    json_start = i
                    brace_count = 0
                    json_lines = []
                    
                    for j in range(i, len(lines)):
                        current_line = lines[j]
                        json_lines.append(current_line)
                        
                        # Count braces to find matching close
                        brace_count += current_line.count('{') - current_line.count('}')
                        
                        if brace_count == 0:
                            # Found complete JSON object
                            json_text = '\n'.join(json_lines)
                            try:
                                chart_data = json.loads(json_text.strip())
                                if chart_data.get("chart_type") and chart_data.get("chart_type") != "error":
                                    logger.info(f"βœ… Found valid chart data: {chart_data.get('chart_type')}")
                                    return chart_data
                            except json.JSONDecodeError:
                                # Try without newlines
                                try:
                                    json_text_clean = json_text.replace('\n', '').replace('  ', ' ')
                                    chart_data = json.loads(json_text_clean)
                                    if chart_data.get("chart_type") and chart_data.get("chart_type") != "error":
                                        logger.info(f"βœ… Found valid chart data (cleaned): {chart_data.get('chart_type')}")
                                        return chart_data
                                except json.JSONDecodeError:
                                    continue
                            break
            
            # Fallback to original regex approach for single-line JSON
            json_pattern = r'\{[^{}]*"chart_type"[^{}]*\}|\{(?:[^{}]|\{[^{}]*\})*"chart_type"(?:[^{}]|\{[^{}]*\})*\}'
            matches = re.findall(json_pattern, response, re.DOTALL)
            
            logger.info(f"   Found {len(matches)} potential chart data objects")
            
            for match in matches:
                try:
                    # Clean up the JSON
                    cleaned_match = match.replace('\\"', '"').replace('\\n', '\n')
                    chart_data = json.loads(cleaned_match)
                    
                    if chart_data.get("chart_type") and chart_data.get("chart_type") != "error":
                        logger.info(f"βœ… Valid chart data found: {chart_data.get('chart_type')}")
                        return chart_data
                        
                except json.JSONDecodeError:
                    continue
                    
            logger.info("⚠️ No valid chart data found in response")
            return None
            
        except Exception as e:
            logger.error(f"Chart data extraction error: {e}")
            return None
    
    async def _generate_chart_from_data(self, chart_data: Dict[str, Any]) -> Optional[str]:
        """Generate HTML visualization from chart data"""
        try:
            if not self.viz:
                logger.warning("Visualization tools not available")
                return None
                
            chart_type = chart_data.get("chart_type")
            data = chart_data.get("data", {})
            config = chart_data.get("config", {})
            
            logger.info(f"Generating {chart_type} chart with data keys: {list(data.keys())}")
            
            if chart_type == "price_chart":
                fig = self.viz.create_price_chart(data, data.get("symbol", "BTC"))
            elif chart_type == "market_overview":
                fig = self.viz.create_market_overview(data.get("coins", []))
            elif chart_type == "defi_tvl":
                fig = self.viz.create_defi_tvl_chart(data.get("protocols", []))
            elif chart_type == "portfolio_pie":
                # Convert allocation data to the expected format
                allocations = {item["name"]: item["value"] for item in data.get("allocations", [])}
                fig = self.viz.create_portfolio_pie_chart(allocations)
            elif chart_type == "gas_tracker":
                fig = self.viz.create_gas_tracker(data)
            else:
                logger.warning(f"Unknown chart type: {chart_type}")
                return None
                
            # Convert to HTML - use div_id and config for embedding
            chart_id = f'chart_{chart_type}_{int(time.time())}'
            
            # Generate HTML with inline Plotly for reliable rendering
            html = fig.to_html(
                include_plotlyjs='inline',  # Embed Plotly directly - no CDN issues
                div_id=chart_id,
                config={'responsive': True, 'displayModeBar': False}
            )
            
            # With inline Plotly, we need to extract the body content only
            import re
            # Extract everything between <body> and </body>
            body_match = re.search(r'<body[^>]*>(.*?)</body>', html, re.DOTALL)
            if body_match:
                chart_html = body_match.group(1).strip()
                logger.info(f"βœ… Chart HTML generated ({len(chart_html)} chars) - inline format")
                return chart_html
            else:
                # Fallback - return the full HTML minus the html/head/body tags
                # Remove full document structure, keep only the content
                cleaned_html = re.sub(r'<html[^>]*>.*?<body[^>]*>', '', html, flags=re.DOTALL)
                cleaned_html = re.sub(r'</body>.*?</html>', '', cleaned_html, flags=re.DOTALL)
                logger.info(f"βœ… Chart HTML generated ({len(cleaned_html)} chars) - cleaned format")
                return cleaned_html.strip()
            
        except Exception as e:
            logger.error(f"Chart generation error: {e}")
            return None
    def _clean_agent_response(self, response: str) -> str:
        """Clean agent response by removing JSON data blocks"""
        try:
            import re
            
            # Method 1: Remove complete JSON objects with balanced braces that contain chart_type
            lines = response.split('\n')
            cleaned_lines = []
            skip_mode = False
            brace_count = 0
            
            for line in lines:
                if not skip_mode:
                    if '"chart_type"' in line and line.strip().startswith('{'):
                        # Found start of chart JSON - start skipping
                        skip_mode = True
                        brace_count = line.count('{') - line.count('}')
                        if brace_count == 0:
                            # Single line JSON, skip this line
                            skip_mode = False
                        continue
                    else:
                        cleaned_lines.append(line)
                else:
                    # In skip mode - count braces to find end
                    brace_count += line.count('{') - line.count('}')
                    if brace_count <= 0:
                        # Found end of JSON block
                        skip_mode = False
                    # Skip this line in any case
            
            cleaned = '\n'.join(cleaned_lines)
            
            # Method 2: Fallback regex for any remaining JSON patterns
            json_patterns = [
                r'\{[^{}]*"chart_type"[^{}]*\}',  # Simple single-line JSON
                r'```json\s*\{.*?"chart_type".*?\}\s*```',  # Markdown JSON blocks
            ]
            
            for pattern in json_patterns:
                cleaned = re.sub(pattern, '', cleaned, flags=re.DOTALL)
            
            # Clean up extra whitespace
            cleaned = re.sub(r'\n\s*\n\s*\n+', '\n\n', cleaned)
            cleaned = cleaned.strip()
            
            return cleaned
            
        except Exception as e:
            logger.error(f"Response cleaning error: {e}")
            return response

# Initialize service
service = Web3CoPilotService()

@app.get("/", response_class=HTMLResponse)
async def get_homepage(request: Request):
    """Serve minimalist, professional interface"""
    html_content = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Web3 Research Co-Pilot</title>
        <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22><path fill=%22%2300d4aa%22 d=%22M12 2L2 7v10c0 5.5 3.8 7.7 9 9 5.2-1.3 9-3.5 9-9V7l-10-5z%22/></svg>">
        <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/components/prism-core.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/plugins/autoloader/prism-autoloader.min.js"></script>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/themes/prism-tomorrow.min.css" rel="stylesheet">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        
        <style>
            :root {
                --primary: #0066ff;
                --primary-dark: #0052cc;
                --accent: #00d4aa;
                --background: #000000;
                --surface: #111111;
                --surface-elevated: #1a1a1a;
                --text: #ffffff;
                --text-secondary: #a0a0a0;
                --text-muted: #666666;
                --border: rgba(255, 255, 255, 0.08);
                --border-focus: rgba(0, 102, 255, 0.3);
                --shadow: rgba(0, 0, 0, 0.4);
                --success: #00d4aa;
                --warning: #ffa726;
                --error: #f44336;
            }
            
            [data-theme="light"] {
                --background: #ffffff;
                --surface: #f8f9fa;
                --surface-elevated: #ffffff;
                --text: #1a1a1a;
                --text-secondary: #4a5568;
                --text-muted: #718096;
                --border: rgba(0, 0, 0, 0.08);
                --border-focus: rgba(0, 102, 255, 0.3);
                --shadow: rgba(0, 0, 0, 0.1);
            }

            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
                transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', system-ui, sans-serif;
                background: var(--background);
                color: var(--text);
                line-height: 1.5;
                min-height: 100vh;
                font-weight: 400;
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
            }

            .container {
                max-width: 1000px;
                margin: 0 auto;
                padding: 2rem 1.5rem;
            }

            .header {
                text-align: center;
                margin-bottom: 2.5rem;
            }
            .header-content {
                display: flex;
                justify-content: space-between;
                align-items: center;
                max-width: 100%;
            }
            .header-text {
                flex: 1;
                text-align: center;
            }
            .theme-toggle {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: 8px;
                padding: 0.75rem;
                color: var(--text);
                cursor: pointer;
                transition: all 0.2s ease;
                font-size: 1.1rem;
                min-width: 44px;
                height: 44px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .theme-toggle:hover {
                background: var(--surface-elevated);
                border-color: var(--primary);
                transform: translateY(-1px);
            }

            .header h1 {
                font-size: 2.25rem;
                font-weight: 600;
                color: var(--text);
                margin-bottom: 0.5rem;
                letter-spacing: -0.025em;
            }

            .header .brand {
                color: var(--primary);
            }

            .header p {
                color: var(--text-secondary);
                font-size: 1rem;
                font-weight: 400;
            }

            .status {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: 12px;
                padding: 1rem 1.5rem;
                margin-bottom: 2rem;
                text-align: center;
                transition: all 0.2s ease;
            }

            .status.online {
                border-color: var(--success);
                background: linear-gradient(135deg, rgba(0, 212, 170, 0.05), rgba(0, 212, 170, 0.02));
            }

            .status.offline {
                border-color: var(--error);
                background: linear-gradient(135deg, rgba(244, 67, 54, 0.05), rgba(244, 67, 54, 0.02));
            }

            .status.checking {
                border-color: var(--warning);
                background: linear-gradient(135deg, rgba(255, 167, 38, 0.05), rgba(255, 167, 38, 0.02));
                animation: pulse 2s infinite;
            }

            @keyframes pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.8; }
            }

            .chat-interface {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: 16px;
                overflow: hidden;
                margin-bottom: 2rem;
                backdrop-filter: blur(20px);
            }

            .chat-messages {
                height: 480px;
                overflow-y: auto;
                padding: 2rem;
                background: linear-gradient(180deg, var(--background), var(--surface));
            }

            .chat-messages::-webkit-scrollbar {
                width: 3px;
            }

            .chat-messages::-webkit-scrollbar-track {
                background: transparent;
            }

            .chat-messages::-webkit-scrollbar-thumb {
                background: var(--border);
                border-radius: 2px;
            }

            .message {
                margin-bottom: 2rem;
                opacity: 0;
                animation: messageSlide 0.4s cubic-bezier(0.2, 0, 0.2, 1) forwards;
            }

            @keyframes messageSlide {
                from { 
                    opacity: 0; 
                    transform: translateY(20px) scale(0.98); 
                }
                to { 
                    opacity: 1; 
                    transform: translateY(0) scale(1); 
                }
            }

            .message.user {
                text-align: right;
            }

            .message.assistant {
                text-align: left;
            }

            .message-content {
                display: inline-block;
                max-width: 75%;
                padding: 1.25rem 1.5rem;
                border-radius: 24px;
                font-size: 0.95rem;
                line-height: 1.6;
                position: relative;
            }

            .message.user .message-content {
                background: linear-gradient(135deg, var(--primary), var(--primary-dark));
                color: #ffffff;
                border-bottom-right-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 102, 255, 0.2);
            }

            .message.assistant .message-content {
                background: var(--surface-elevated);
                color: var(--text);
                border-bottom-left-radius: 8px;
                border: 1px solid var(--border);
            }
            /* Enhanced text formatting for better UX */
            .message-content h1, .message-content h2, .message-content h3, .message-content h4, .message-content h5, .message-content h6 {
                color: var(--accent);
                margin: 1.5rem 0 0.75rem 0;
                font-weight: 600;
                line-height: 1.3;
                letter-spacing: -0.025em;
            }
            .message-content h1 { 
                font-size: 1.35rem; 
                border-bottom: 2px solid var(--accent);
                padding-bottom: 0.5rem;
            }
            .message-content h2 { 
                font-size: 1.2rem; 
                border-bottom: 1px solid var(--border);
                padding-bottom: 0.25rem;
            }
            .message-content h3 { font-size: 1.1rem; }
            .message-content h4 { font-size: 1rem; }
            .message-content h5 { font-size: 0.95rem; }
            .message-content h6 { font-size: 0.9rem; opacity: 0.9; }
            
            .message-content p {
                margin: 0.875rem 0;
                line-height: 1.65;
                text-align: justify;
                text-justify: inter-word;
            }
            
            .message-content ul, .message-content ol {
                margin: 1rem 0;
                padding-left: 1.75rem;
            }
            
            .message-content ul {
                list-style-type: none;
            }
            
            .message-content ul li::before {
                content: 'β€’';
                color: var(--accent);
                font-weight: bold;
                position: absolute;
                margin-left: -1.25rem;
            }
            
            .message-content ol li {
                list-style-type: decimal;
                color: var(--text);
            }
            
            .message-content li {
                margin: 0.5rem 0;
                line-height: 1.6;
                position: relative;
            }
            
            .message-content strong, .message-content b {
                color: var(--accent);
                font-weight: 650;
                text-shadow: 0 0 2px rgba(0, 212, 170, 0.3);
            }
            
            .message-content em, .message-content i {
                color: var(--text-secondary);
                font-style: italic;
                font-weight: 450;
            }
            
            .message-content code {
                background: linear-gradient(135deg, rgba(0, 102, 255, 0.12), rgba(0, 212, 170, 0.08));
                border: 1px solid rgba(0, 102, 255, 0.25);
                padding: 0.2rem 0.5rem;
                border-radius: 6px;
                font-family: 'SF Mono', 'Monaco', 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
                font-size: 0.875rem;
                color: var(--accent);
                font-weight: 500;
                letter-spacing: 0.025em;
                box-shadow: 0 1px 3px rgba(0, 102, 255, 0.1);
            }
            
            .message-content pre {
                background: linear-gradient(135deg, var(--background), var(--surface));
                border: 1px solid var(--border);
                border-radius: 10px;
                padding: 1.25rem;
                margin: 1.5rem 0;
                overflow-x: auto;
                font-family: 'SF Mono', 'Monaco', 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
                font-size: 0.875rem;
                line-height: 1.5;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                position: relative;
            }
            
            .message-content pre code {
                background: none;
                border: none;
                padding: 0;
                border-radius: 0;
                box-shadow: none;
                color: var(--text);
            }
            
            .message-content blockquote {
                border-left: 4px solid var(--accent);
                background: rgba(0, 212, 170, 0.05);
                padding: 1rem 1.5rem;
                margin: 1.5rem 0;
                color: var(--text-secondary);
                font-style: italic;
                border-radius: 0 8px 8px 0;
                position: relative;
            }
            
            .message-content blockquote::before {
                content: '"';
                font-size: 3rem;
                color: var(--accent);
                position: absolute;
                top: -0.5rem;
                left: 0.5rem;
                opacity: 0.3;
                font-family: Georgia, serif;
            }
            
            .message-content a {
                color: var(--primary);
                text-decoration: none;
                font-weight: 500;
                border-bottom: 1px solid transparent;
                transition: all 0.2s ease;
            }
            
            .message-content a:hover {
                color: var(--accent);
                border-bottom-color: var(--accent);
            }
            
            .message-content table {
                width: 100%;
                border-collapse: collapse;
                margin: 1.5rem 0;
                background: var(--surface-elevated);
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }
            
            .message-content th, .message-content td {
                padding: 0.875rem;
                text-align: left;
                border-bottom: 1px solid var(--border);
            }
            
            .message-content th {
                background: var(--surface);
                font-weight: 600;
                color: var(--accent);
            }
            
            .message-content tr:last-child td {
                border-bottom: none;
            }
            
            .message-content hr {
                border: none;
                height: 2px;
                background: linear-gradient(90deg, transparent, var(--border), transparent);
                margin: 2rem 0;
            }
            
            /* Number formatting for crypto values */
            .message-content .crypto-value {
                font-family: 'SF Mono', monospace;
                font-weight: 600;
                color: var(--accent);
                background: rgba(0, 212, 170, 0.1);
                padding: 0.1rem 0.3rem;
                border-radius: 4px;
            }
            
            /* Highlight important information */
            .message-content .highlight {
                background: linear-gradient(135deg, rgba(0, 102, 255, 0.15), rgba(0, 212, 170, 0.1));
                padding: 0.75rem 1rem;
                border-radius: 8px;
                border-left: 3px solid var(--accent);
                margin: 1rem 0;
            }

            .message-meta {
                font-size: 0.75rem;
                color: var(--text-muted);
                margin-top: 0.5rem;
                font-weight: 500;
            }

            .sources {
                margin-top: 1rem;
                padding-top: 1rem;
                border-top: 1px solid var(--border);
                font-size: 0.8rem;
                color: var(--text-secondary);
            }

            .sources span {
                display: inline-block;
                background: rgba(0, 102, 255, 0.1);
                border: 1px solid rgba(0, 102, 255, 0.2);
                padding: 0.25rem 0.75rem;
                border-radius: 6px;
                margin: 0.25rem 0.5rem 0.25rem 0;
                font-weight: 500;
                font-size: 0.75rem;
            }

            .input-area {
                padding: 2rem;
                background: linear-gradient(180deg, var(--surface), var(--surface-elevated));
                border-top: 1px solid var(--border);
            }

            .input-container {
                display: flex;
                gap: 1rem;
                align-items: stretch;
            }

            .input-field {
                flex: 1;
                padding: 1rem 1.5rem;
                background: var(--background);
                border: 2px solid var(--border);
                border-radius: 28px;
                color: var(--text);
                font-size: 0.95rem;
                outline: none;
                transition: all 0.2s cubic-bezier(0.2, 0, 0.2, 1);
                font-weight: 400;
            }

            .input-field:focus {
                border-color: var(--primary);
                box-shadow: 0 0 0 4px var(--border-focus);
                background: var(--surface);
            }

            .input-field::placeholder {
                color: var(--text-muted);
                font-weight: 400;
            }

            .send-button {
                padding: 1rem 2rem;
                background: linear-gradient(135deg, var(--primary), var(--primary-dark));
                color: #ffffff;
                border: none;
                border-radius: 28px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.2s cubic-bezier(0.2, 0, 0.2, 1);
                font-size: 0.95rem;
                box-shadow: 0 4px 12px rgba(0, 102, 255, 0.2);
            }

            .send-button:hover:not(:disabled) {
                transform: translateY(-2px);
                box-shadow: 0 8px 24px rgba(0, 102, 255, 0.3);
            }

            .send-button:active {
                transform: translateY(0);
            }

            .send-button:disabled {
                opacity: 0.6;
                cursor: not-allowed;
                transform: none;
                box-shadow: 0 4px 12px rgba(0, 102, 255, 0.1);
            }

            .examples {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
                gap: 1rem;
                margin-top: 1rem;
            }

            .example {
                background: linear-gradient(135deg, var(--surface), var(--surface-elevated));
                border: 1px solid var(--border);
                border-radius: 12px;
                padding: 1.5rem;
                cursor: pointer;
                transition: all 0.3s cubic-bezier(0.2, 0, 0.2, 1);
                position: relative;
                overflow: hidden;
            }

            .example::before {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(0, 102, 255, 0.05), transparent);
                transition: left 0.5s ease;
            }

            .example:hover::before {
                left: 100%;
            }

            .example:hover {
                border-color: var(--primary);
                transform: translateY(-4px);
                box-shadow: 0 12px 32px rgba(0, 0, 0, 0.2);
                background: linear-gradient(135deg, var(--surface-elevated), var(--surface));
            }

            .example-title {
                font-weight: 600;
                color: var(--text);
                margin-bottom: 0.5rem;
                font-size: 0.95rem;
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
            .example-title i {
                color: var(--primary);
                font-size: 1rem;
                width: 20px;
                text-align: center;
            }

            .example-desc {
                font-size: 0.85rem;
                color: var(--text-secondary);
                font-weight: 400;
            }

            .loading {
                display: inline-flex;
                align-items: center;
                gap: 0.5rem;
                color: var(--text-secondary);
                font-weight: 500;
            }

            .loading::after {
                content: '';
                width: 14px;
                height: 14px;
                border: 2px solid currentColor;
                border-top-color: transparent;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }

            @keyframes spin {
                to { transform: rotate(360deg); }
            }
            .loading-indicator {
                display: none;
                background: var(--surface-elevated);
                border: 1px solid var(--border);
                border-radius: 12px;
                padding: 1.5rem;
                margin: 1rem 0;
                text-align: center;
                color: var(--text-secondary);
            }
            .loading-indicator.active {
                display: block;
            }
            .loading-spinner {
                display: inline-block;
                width: 20px;
                height: 20px;
                border: 2px solid var(--border);
                border-top-color: var(--primary);
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-right: 0.5rem;
            }
            .status-indicator {
                position: fixed;
                top: 20px;
                right: 20px;
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: 8px;
                padding: 0.75rem 1rem;
                font-size: 0.85rem;
                color: var(--text-secondary);
                opacity: 0;
                transform: translateY(-10px);
                transition: all 0.3s ease;
                z-index: 1000;
            }
            .status-indicator.show {
                opacity: 1;
                transform: translateY(0);
            }
            .status-indicator.processing {
                border-color: var(--primary);
                background: linear-gradient(135deg, rgba(0, 102, 255, 0.05), rgba(0, 102, 255, 0.02));
            }

            .visualization-container {
                margin: 1.5rem 0;
                background: var(--surface-elevated);
                border-radius: 12px;
                padding: 1.5rem;
                border: 1px solid var(--border);
            }

            .welcome {
                text-align: center;
                padding: 4rem 2rem;
                color: var(--text-secondary);
            }

            .welcome h3 {
                font-size: 1.25rem;
                font-weight: 600;
                margin-bottom: 0.5rem;
                color: var(--text);
            }

            .welcome p {
                font-size: 0.95rem;
                font-weight: 400;
            }

            @media (max-width: 768px) {
                .container {
                    padding: 1rem;
                }
                
                .header-content {
                    flex-direction: column;
                    gap: 1rem;
                }
                
                .header-text {
                    text-align: center;
                }
                
                .header h1 {
                    font-size: 1.75rem;
                }
                
                .chat-messages {
                    height: 400px;
                    padding: 1.5rem;
                }
                
                .message-content {
                    max-width: 85%;
                    padding: 1rem 1.25rem;
                }
                
                .input-area {
                    padding: 1.5rem;
                }
                
                .input-container {
                    flex-direction: column;
                    gap: 0.75rem;
                }
                
                .send-button {
                    align-self: stretch;
                }
                
                .examples {
                    grid-template-columns: 1fr;
                }
            }
        </style>
    </head>
    <body>
        <div id="statusIndicator" class="status-indicator">
            <span id="statusText">Ready</span>
        </div>
        
        <div class="container">
            <div class="header">
                <div class="header-content">
                    <div class="header-text">
                        <h1><span class="brand">Web3</span> Research Co-Pilot</h1>
                        <p>Professional cryptocurrency analysis and market intelligence</p>
                    </div>
                    <button id="themeToggle" class="theme-toggle" title="Toggle theme">
                        <i class="fas fa-moon"></i>
                    </button>
                </div>
            </div>

            <div id="status" class="status checking">
                <span>Initializing research systems...</span>
            </div>

            <div class="chat-interface">
                <div id="chatMessages" class="chat-messages">
                    <div class="welcome">
                        <h3>Welcome to Web3 Research Co-Pilot</h3>
                        <p>Ask about market trends, DeFi protocols, or blockchain analytics</p>
                    </div>
                </div>
                <div id="loadingIndicator" class="loading-indicator">
                    <div class="loading-spinner"></div>
                    <span id="loadingText">Processing your research query...</span>
                </div>
                <div class="input-area">
                    <div class="input-container">
                        <input 
                            type="text" 
                            id="queryInput" 
                            class="input-field"
                            placeholder="Research Bitcoin trends, analyze DeFi yields, compare protocols..."
                            maxlength="500"
                        >
                        <button id="sendBtn" class="send-button">Research</button>
                    </div>
                </div>
            </div>

            <div class="examples">
                <div class="example" onclick="setQuery('Analyze Bitcoin price trends and institutional adoption patterns')">
                    <div class="example-title"><i class="fas fa-chart-line"></i> Market Analysis</div>
                    <div class="example-desc">Bitcoin trends, institutional flows, and market sentiment analysis</div>
                </div>
                <div class="example" onclick="setQuery('Compare top DeFi protocols by TVL, yield, and risk metrics across chains')">
                    <div class="example-title"><i class="fas fa-coins"></i> DeFi Intelligence</div>
                    <div class="example-desc">Protocol comparison, yield analysis, and cross-chain opportunities</div>
                </div>
                <div class="example" onclick="setQuery('Evaluate Ethereum Layer 2 scaling solutions and adoption metrics')">
                    <div class="example-title"><i class="fas fa-layer-group"></i> Layer 2 Research</div>
                    <div class="example-desc">Scaling solutions, transaction costs, and ecosystem growth</div>
                </div>
                <div class="example" onclick="setQuery('Find optimal yield farming strategies with risk assessment')">
                    <div class="example-title"><i class="fas fa-seedling"></i> Yield Optimization</div>
                    <div class="example-desc">Cross-chain opportunities, APY tracking, and risk analysis</div>
                </div>
                <div class="example" onclick="setQuery('Track whale movements and large Bitcoin transactions today')">
                    <div class="example-title"><i class="fas fa-fish"></i> Whale Tracking</div>
                    <div class="example-desc">Large transactions, wallet analysis, and market impact</div>
                </div>
                <div class="example" onclick="setQuery('Analyze gas fees and network congestion across blockchains')">
                    <div class="example-title"><i class="fas fa-tachometer-alt"></i> Network Analytics</div>
                    <div class="example-desc">Gas prices, network utilization, and cost comparisons</div>
                </div>
            </div>
        </div>

        <script>
            // Configure marked.js for better markdown rendering
            if (typeof marked !== 'undefined') {
                marked.setOptions({
                    breaks: true,
                    gfm: true,
                    highlight: function(code, lang) {
                        if (typeof Prism !== 'undefined' && lang && Prism.languages[lang]) {
                            return Prism.highlight(code, Prism.languages[lang], lang);
                        }
                        return code;
                    },
                    sanitize: false,
                    smartLists: true,
                    smartypants: true
                });
            }

            let chatHistory = [];
            let messageCount = 0;

            async function checkStatus() {
                console.log('Checking system status...');
                try {
                    const response = await fetch('/status');
                    console.log('Status response:', response.status, response.statusText);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    const status = await response.json();
                    console.log('Status data:', status);
                    
                    const statusDiv = document.getElementById('status');
                    
                    // Check if system is operational (either fully enabled or in limited mode)
                    if (status.enabled) {
                        if (status.gemini_configured) {
                            console.log('βœ… System is fully operational');
                            statusDiv.className = 'status online';
                            statusDiv.innerHTML = `
                                <span>Research systems online</span>
                                <div style="margin-top: 0.5rem; font-size: 0.85rem; opacity: 0.8;">
                                    Tools: ${status.tools_available.join(' β€’ ')}
                                </div>
                            `;
                        } else {
                            console.log('⚠️ System is in limited mode');
                            statusDiv.className = 'status offline';
                            statusDiv.innerHTML = `
                                <span>Limited mode - Configure GEMINI_API_KEY for full functionality</span>
                                <div style="margin-top: 0.5rem; font-size: 0.85rem; opacity: 0.8;">
                                    Available: ${status.tools_available.join(' β€’ ')}
                                </div>
                            `;
                        }
                    } else {
                        console.log('❌ System is disabled');
                        statusDiv.className = 'status offline';
                        statusDiv.innerHTML = '<span>System disabled</span>';
                    }
                } catch (error) {
                    console.error('❌ Status check failed:', error);
                    const statusDiv = document.getElementById('status');
                    statusDiv.className = 'status offline';
                    statusDiv.innerHTML = `<span>Connection error: ${error.message}</span>`;
                    
                    // Retry after 5 seconds
                    setTimeout(() => {
                        console.log('πŸ”„ Retrying status check...');
                        checkStatus();
                    }, 5000);
                }
            }

            async function sendQuery() {
                const input = document.getElementById('queryInput');
                const sendBtn = document.getElementById('sendBtn');
                const loadingIndicator = document.getElementById('loadingIndicator');
                const statusIndicator = document.getElementById('statusIndicator');
                const statusText = document.getElementById('statusText');
                const query = input.value.trim();

                if (!query) {
                    showStatus('Please enter a research query', 'warning');
                    return;
                }

                console.log('Sending research query');
                addMessage('user', query);
                input.value = '';

                // Update UI states
                sendBtn.disabled = true;
                sendBtn.innerHTML = '<span class="loading">Processing</span>';
                loadingIndicator.classList.add('active');
                showStatus('Processing research query...', 'processing');

                try {
                    console.log('Making API request...');
                    const requestStart = Date.now();
                    
                    const response = await fetch('/query', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ query, chat_history: chatHistory })
                    });

                    const requestTime = Date.now() - requestStart;
                    console.log(`Request completed in ${requestTime}ms`);

                    if (!response.ok) {
                        throw new Error(`Request failed with status ${response.status}`);
                    }

                    const result = await response.json();
                    console.log('Response received successfully');

                    if (result.success) {
                        addMessage('assistant', result.response, result.sources, result.visualizations);
                        showStatus('Research complete', 'success');
                        console.log('Analysis completed successfully');
                    } else {
                        console.log('Analysis request failed');
                        addMessage('assistant', result.response || 'Analysis temporarily unavailable. Please try again.', [], []);
                        showStatus('Request failed', 'error');
                    }
                } catch (error) {
                    console.error('Request error occurred');
                    addMessage('assistant', 'Connection error. Please check your network and try again.');
                    showStatus('Connection error', 'error');
                } finally {
                    // Reset UI states
                    sendBtn.disabled = false;
                    sendBtn.innerHTML = 'Research';
                    loadingIndicator.classList.remove('active');
                    input.focus();
                    console.log('Request completed');
                    
                    // Hide status after delay
                    setTimeout(() => hideStatus(), 3000);
                }
            }

            function addMessage(sender, content, sources = [], visualizations = []) {
                const messagesDiv = document.getElementById('chatMessages');
                
                // Clear welcome message
                if (messageCount === 0) {
                    messagesDiv.innerHTML = '';
                }
                messageCount++;

                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${sender}`;

                let sourcesHtml = '';
                if (sources && sources.length > 0) {
                    sourcesHtml = `
                        <div class="sources">
                            Sources: ${sources.map(s => `<span>${s}</span>`).join('')}
                        </div>
                    `;
                }

                let visualizationHtml = '';
                if (visualizations && visualizations.length > 0) {
                    console.log('Processing visualizations:', visualizations.length);
                    visualizationHtml = visualizations.map((viz, index) => {
                        console.log(`Visualization ${index}:`, viz.substring(0, 100));
                        return `<div class="visualization-container" id="viz-${Date.now()}-${index}">${viz}</div>`;
                    }).join('');
                }

                // Format content based on sender with enhanced markdown processing
                let formattedContent = content;
                if (sender === 'assistant') {
                    // Enhanced markdown to HTML conversion for assistant responses
                    try {
                        // Use marked.js if available
                        if (typeof marked !== 'undefined') {
                            formattedContent = marked.parse(content);
                        } else {
                            throw new Error('marked.js not available');
                        }
                    } catch (error) {
                        // Simple fallback formatting if marked.js fails
                        console.warn('Markdown parsing failed, using simple fallback:', error);
                        formattedContent = content
                            .replace(/\n\n/g, '<br><br>')
                            .replace(/\n/g, '<br>')
                            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                            .replace(/\*(.*?)\*/g, '<em>$1</em>')
                            .replace(/`(.*?)`/g, '<code>$1</code>');
                    }
                    }
                } else {
                    // Simple user message formatting
                    formattedContent = content
                        .replace(/\n/g, '<br>')
                        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                        .replace(/\*(.*?)\*/g, '<em>$1</em>')
                        .replace(/`(.*?)`/g, '<code>$1</code>');
                }

                messageDiv.innerHTML = `
                    <div class="message-content">
                        ${formattedContent}
                        ${sourcesHtml}
                    </div>
                    ${visualizationHtml}
                    <div class="message-meta">${new Date().toLocaleTimeString()}</div>
                `;

                messagesDiv.appendChild(messageDiv);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;

                // Apply syntax highlighting to code blocks
                if (typeof Prism !== 'undefined') {
                    Prism.highlightAllUnder(messageDiv);
                }

                // Execute any scripts in the visualizations after DOM insertion
                if (visualizations && visualizations.length > 0) {
                    console.log('Executing visualization scripts...');
                    setTimeout(() => {
                        const scripts = messageDiv.querySelectorAll('script');
                        console.log(`Found ${scripts.length} scripts to execute`);
                        
                        scripts.forEach((script, index) => {
                            console.log(`Executing script ${index}:`, script.textContent.substring(0, 200) + '...');
                            try {
                                // Execute script in global context using Function constructor
                                const scriptFunction = new Function(script.textContent);
                                scriptFunction.call(window);
                                console.log(`Script ${index} executed successfully`);
                            } catch (error) {
                                console.error(`Script ${index} execution error:`, error);
                                console.error(`Script content preview:`, script.textContent.substring(0, 500));
                            }
                        });
                        console.log('All visualization scripts executed');
                    }, 100);
                }

                chatHistory.push({ role: sender, content });
                if (chatHistory.length > 20) chatHistory = chatHistory.slice(-20);
            }

            function setQuery(query) {
                document.getElementById('queryInput').value = query;
                setTimeout(() => sendQuery(), 100);
            }
            
            // Status management functions
            function showStatus(message, type = 'info') {
                const statusIndicator = document.getElementById('statusIndicator');
                const statusText = document.getElementById('statusText');
                
                statusText.textContent = message;
                statusIndicator.className = `status-indicator show ${type}`;
            }
            
            function hideStatus() {
                const statusIndicator = document.getElementById('statusIndicator');
                statusIndicator.classList.remove('show');
            }

            // Theme toggle functionality
            function toggleTheme() {
                const currentTheme = document.documentElement.getAttribute('data-theme');
                const newTheme = currentTheme === 'light' ? 'dark' : 'light';
                const themeIcon = document.querySelector('#themeToggle i');
                
                document.documentElement.setAttribute('data-theme', newTheme);
                localStorage.setItem('theme', newTheme);
                
                // Update icon
                if (newTheme === 'light') {
                    themeIcon.className = 'fas fa-sun';
                } else {
                    themeIcon.className = 'fas fa-moon';
                }
            }
            
            // Initialize theme
            function initializeTheme() {
                const savedTheme = localStorage.getItem('theme') || 'dark';
                const themeIcon = document.querySelector('#themeToggle i');
                
                document.documentElement.setAttribute('data-theme', savedTheme);
                
                if (savedTheme === 'light') {
                    themeIcon.className = 'fas fa-sun';
                } else {
                    themeIcon.className = 'fas fa-moon';
                }
            }

            // Event listeners
            document.getElementById('queryInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') sendQuery();
            });

            document.getElementById('sendBtn').addEventListener('click', (e) => {
                console.log('Research button clicked');
                e.preventDefault();
                sendQuery();
            });
            
            document.getElementById('themeToggle').addEventListener('click', toggleTheme);

            // Initialize
            document.addEventListener('DOMContentLoaded', () => {
                console.log('πŸš€ Web3 Research Co-Pilot - Application initializing...');
                console.log('πŸ“ Current URL:', window.location.href);
                console.log('🌐 User Agent:', navigator.userAgent.substring(0, 100));
                
                // Test basic functionality
                const statusDiv = document.getElementById('status');
                console.log('πŸ“‹ Status div found:', !!statusDiv);
                
                initializeTheme();
                
                // Immediate status check for debugging
                console.log('πŸ” Starting immediate status check...');
                checkStatus();
                
                // Also do a delayed check
                setTimeout(() => {
                    console.log('πŸ” Starting delayed status check...');
                    checkStatus();
                }, 2000);
                
                document.getElementById('queryInput').focus();
                console.log('βœ… Application initialization complete');
            });
        </script>
    </body>
    </html>
    """
    return HTMLResponse(content=html_content)

@app.get("/status")
async def get_status():
    """System status endpoint with detailed debugging information"""
    try:
        gemini_configured = bool(config.GEMINI_API_KEY)
        service_enabled = service.enabled
        agent_available = service.agent is not None
        
        status = {
            "enabled": service_enabled,
            "gemini_configured": gemini_configured,
            "agent_available": agent_available,
            "tools_available": ["Market Data", "DeFi Analytics", "Network Metrics"],
            "airaa_enabled": service.airaa.enabled if service.airaa else False,
            "timestamp": datetime.now().isoformat(),
            "version": "2.0.0",
            "debug_info": {
                "gemini_key_length": len(config.GEMINI_API_KEY) if config.GEMINI_API_KEY else 0,
                "service_enabled": service_enabled,
                "agent_initialized": agent_available
            }
        }
        logger.info(f"Status check - Enabled: {service_enabled}, Gemini: {gemini_configured}")
        return status
    except Exception as e:
        logger.error(f"Status endpoint error: {e}")
        return {
            "enabled": False,
            "gemini_configured": False,
            "agent_available": False,
            "tools_available": [],
            "airaa_enabled": False,
            "timestamp": datetime.now().isoformat(),
            "version": "2.0.0",
            "error": str(e)
        }

@app.post("/query", response_model=QueryResponse)
async def process_query(request: QueryRequest):
    """Process research query with sanitized logging"""
    # Log incoming request without exposing sensitive data
    query_preview = request.query[:50] + "..." if len(request.query) > 50 else request.query
    logger.info(f"Query received: {query_preview}")
    
    start_time = datetime.now()
    
    try:
        # Process the query
        result = await service.process_query(request.query)
        
        # Log result without sensitive details
        processing_time = (datetime.now() - start_time).total_seconds()
        logger.info(f"Query processed in {processing_time:.2f}s - Success: {result.success}")
        
        if result.success:
            logger.info(f"Response generated: {len(result.response)} characters")
        else:
            logger.info("Query processing failed")
        
        return result
        
    except Exception as e:
        processing_time = (datetime.now() - start_time).total_seconds()
        logger.error(f"Query processing error after {processing_time:.2f}s")
        
        return QueryResponse(
            success=False,
            response="We're experiencing technical difficulties. Please try again in a moment.",
            error="System temporarily unavailable"
        )

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "service_enabled": service.enabled,
        "version": "2.0.0"
    }

@app.get("/debug/tools")
async def debug_tools():
    """Debug endpoint to test tool availability and functionality"""
    try:
        if not service.enabled or not service.agent:
            return {
                "success": False,
                "error": "AI agent not enabled",
                "tools_available": False,
                "gemini_configured": bool(config.GEMINI_API_KEY)
            }
        
        tools_info = []
        for tool in service.agent.tools:
            tools_info.append({
                "name": tool.name,
                "description": getattr(tool, 'description', 'No description'),
                "enabled": getattr(tool, 'enabled', True)
            })
        
        # Test a simple API call
        test_result = None
        try:
            test_result = await service.process_query("What is the current Bitcoin price?")
        except Exception as e:
            test_result = {"error": str(e)}
        
        return {
            "success": True,
            "tools_count": len(service.agent.tools),
            "tools_info": tools_info,
            "test_query_result": {
                "success": test_result.success if hasattr(test_result, 'success') else False,
                "response_length": len(test_result.response) if hasattr(test_result, 'response') else 0,
                "sources": test_result.sources if hasattr(test_result, 'sources') else [],
                "error": test_result.error if hasattr(test_result, 'error') else None
            },
            "gemini_configured": bool(config.GEMINI_API_KEY),
            "timestamp": datetime.now().isoformat()
        }
    except Exception as e:
        logger.error(f"Debug tools error: {e}")
        return {
            "success": False,
            "error": str(e),
            "timestamp": datetime.now().isoformat()
        }

if __name__ == "__main__":
    import uvicorn
    logger.info("Starting Web3 Research Co-Pilot...")
    uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")