File size: 55,838 Bytes
baf4607
 
0acbfea
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
ce95774
0acbfea
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
ce95774
 
 
0acbfea
 
 
 
 
ce95774
0acbfea
 
 
 
 
ce95774
0acbfea
 
 
 
ce95774
0acbfea
 
 
 
 
ce95774
 
0acbfea
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
 
0acbfea
 
 
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
ce95774
0acbfea
 
 
 
026cf7b
0acbfea
 
 
 
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
ce95774
 
0acbfea
 
 
 
 
ce95774
0acbfea
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
ce95774
 
0acbfea
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
ce95774
 
0acbfea
 
ce95774
0acbfea
 
 
 
ce95774
0acbfea
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
 
 
0acbfea
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
 
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
 
 
 
 
 
 
 
 
 
 
 
 
 
0acbfea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
 
 
 
a992a9a
9f14540
 
 
a992a9a
 
9f14540
a992a9a
 
 
 
9f14540
 
 
a992a9a
 
 
 
 
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a992a9a
 
 
 
 
9f14540
 
a992a9a
 
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a992a9a
 
9f14540
 
 
 
 
 
 
a992a9a
9f14540
 
 
 
 
 
 
 
a992a9a
 
 
9f14540
 
 
 
 
 
 
 
 
a992a9a
 
9f14540
 
 
 
 
 
 
 
a992a9a
 
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a992a9a
 
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a992a9a
 
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a992a9a
9f14540
 
 
 
 
 
 
 
 
 
ce95774
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
9f14540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce95774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baf4607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf4b56
baf4607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d187741
baf4607
 
727d227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baf4607
727d227
 
baf4607
727d227
 
 
 
baf4607
727d227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baf4607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a992a9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baf4607
 
 
a992a9a
baf4607
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
            }
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Agent System - Task Processing & Database Integration</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .system-status {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .status-card {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
        }

        .status-card h3 {
            font-size: 1.1rem;
            margin-bottom: 5px;
        }

        .status-card .value {
            font-size: 1.5rem;
            font-weight: bold;
        }

        .main-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .panel {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
        }

        .panel h2 {
            color: #4a5568;
            margin-bottom: 15px;
            font-size: 1.3rem;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 8px;
        }

        .task-form {
            display: grid;
            gap: 15px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #4a5568;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 10px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #4299e1;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #2d5a27;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
            color: #c53030;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .task-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .task-item {
            background: #f7fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.3s;
        }

        .task-item:hover {
            background: #edf2f7;
            transform: translateX(5px);
        }

        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .task-id {
            font-weight: 600;
            color: #2d3748;
        }

        .task-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-queued { background: #fef5e7; color: #c05621; }
        .status-processing { background: #e6fffa; color: #234e52; }
        .status-completed { background: #f0fff4; color: #22543d; }
        .status-failed { background: #fed7d7; color: #c53030; }

        .agents-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
        }

        .agent-card {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            transition: transform 0.3s;
        }

        .agent-card:hover {
            transform: scale(1.05);
        }

        .agent-name {
            font-weight: 600;
            margin-bottom: 5px;
            color: #2d3748;
        }

        .agent-status {
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 4px;
            display: inline-block;
            margin-bottom: 10px;
        }

        .status-active { background: #c6f6d5; color: #22543d; }
        .status-idle { background: #fed7e2; color: #97266d; }

        .logs-container {
            background: #1a202c;
            color: #e2e8f0;
            border-radius: 8px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
        }

        .log-entry {
            margin-bottom: 5px;
            padding: 2px 0;
        }

        .log-timestamp {
            color: #718096;
            margin-right: 10px;
        }

        .log-level-info { color: #63b3ed; }
        .log-level-success { color: #68d391; }
        .log-level-warning { color: #f6ad55; }
        .log-level-error { color: #fc8181; }

        .database-panel {
            grid-column: 1 / -1;
            margin-top: 20px;
        }

        .db-actions {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .connection-status {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #68d391;
            animation: pulse 2s infinite;
        }

        .status-disconnected {
            background: #fc8181;
        }

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

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .data-table th,
        .data-table td {
            border: 1px solid #e2e8f0;
            padding: 8px 12px;
            text-align: left;
        }

        .data-table th {
            background: #f7fafc;
            font-weight: 600;
            color: #4a5568;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border-radius: 15px;
            padding: 30px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 10px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #a0aec0;
        }

        .close-btn:hover {
            color: #4a5568;
        }

        @media (max-width: 768px) {
            .main-grid {
                grid-template-columns: 1fr;
            }
            
            .status-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .header h1 {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 Advanced Agent System</h1>
            <p>Task Processing Engine with Database Integration</p>
        </div>

        <!-- System Status -->
        <div class="system-status">
            <div class="status-grid">
                <div class="status-card">
                    <h3>Active Agents</h3>
                    <div class="value" id="active-agents">0</div>
                </div>
                <div class="status-card">
                    <h3>Tasks Queued</h3>
                    <div class="value" id="queued-tasks">0</div>
                </div>
                <div class="status-card">
                    <h3>Processing</h3>
                    <div class="value" id="processing-tasks">0</div>
                </div>
                <div class="status-card">
                    <h3>Completed</h3>
                    <div class="value" id="completed-tasks">0</div>
                </div>
                <div class="status-card">
                    <h3>DB Records</h3>
                    <div class="value" id="db-records">0</div>
                </div>
            </div>
        </div>

        <!-- Main Grid -->
        <div class="main-grid">
            <!-- Task Creation Panel -->
            <div class="panel">
                <h2>📝 Create Task</h2>
                <form class="task-form" id="task-form">
                    <div class="form-group">
                        <label for="task-type">Task Type</label>
                        <select id="task-type">
                            <option value="single">Single Task</option>
                            <option value="workflow">Workflow</option>
                            <option value="batch">Batch Processing</option>
                            <option value="scheduled">Scheduled Task</option>
                            <option value="monitoring">Monitoring</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="task-description">Description</label>
                        <textarea id="task-description" rows="3" placeholder="Describe what this task should do..."></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="task-priority">Priority</label>
                        <select id="task-priority">
                            <option value="low">Low</option>
                            <option value="normal" selected>Normal</option>
                            <option value="high">High</option>
                            <option value="urgent">Urgent</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="task-agent">Assign to Agent</label>
                        <select id="task-agent">
                            <option value="">Auto-assign</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Create Task</button>
                </form>
            </div>

            <!-- Active Agents Panel -->
            <div class="panel">
                <h2>🤖 Active Agents</h2>
                <div class="agents-grid" id="agents-container">
                    <!-- Agents will be populated here -->
                </div>
                <button class="btn btn-success" onclick="createAgent()">+ Add Agent</button>
            </div>
        </div>

        <!-- Task Queue Panel -->
        <div class="panel">
            <h2>📋 Task Queue & Processing</h2>
            <div class="task-list" id="task-list">
                <!-- Tasks will be populated here -->
            </div>
        </div>

        <!-- Database Integration Panel -->
        <div class="panel database-panel">
            <h2>🗄️ Database Integration</h2>
            
            <div class="connection-status">
                <div class="status-indicator" id="db-status"></div>
                <span id="db-status-text">Connected to Local Storage</span>
            </div>
            
            <div class="db-actions">
                <button class="btn btn-primary" onclick="initializeDatabase()">Initialize DB</button>
                <button class="btn btn-success" onclick="exportData()">Export Data</button>
                <button class="btn btn-danger" onclick="clearDatabase()">Clear Database</button>
                <button class="btn btn-primary" onclick="showQueryInterface()">Query Interface</button>
            </div>
            
            <div id="db-content">
                <table class="data-table" id="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Updated</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="data-table-body">
                    </tbody>
                </table>
            </div>
        </div>

        <!-- System Logs -->
        <div class="panel">
            <h2>📊 System Logs</h2>
            <div class="logs-container" id="logs-container">
                <!-- Logs will be populated here -->
            </div>
            <button class="btn btn-danger" onclick="clearLogs()">Clear Logs</button>
        </div>
    </div>

    <!-- Modal for Query Interface -->
    <div class="modal" id="query-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Database Query Interface</h2>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <div class="form-group">
                <label for="query-input">SQL-like Query</label>
                <textarea id="query-input" rows="4" placeholder="SELECT * FROM tasks WHERE status = 'completed'"></textarea>
            </div>
            <button class="btn btn-primary" onclick="executeQuery()">Execute Query</button>
            <div id="query-results"></div>
        </div>
    </div>

    <script>
      // Database Manager Class
// Complete DatabaseManager Class for the Agent System
// Add this class BEFORE the TaskProcessingEngine class in your HTML file

class DatabaseManager {
    constructor() {
        this.connected = false;
        this.tables = {
            tasks: 'agent_tasks',
            agents: 'agent_agents',
            logs: 'agent_logs',
            metrics: 'agent_metrics',
            workflows: 'agent_workflows',
            schedules: 'agent_schedules'
        };
        this.init();
    }

    init() {
        try {
            // Check if localStorage is available
            if (typeof Storage !== "undefined") {
                this.connected = true;
                this.initializeTables();
                console.log('✅ Database Manager initialized with localStorage');
            } else {
                console.error('❌ localStorage not supported');
                this.connected = false;
            }
        } catch (error) {
            console.error('❌ Database initialization failed:', error);
            this.connected = false;
        }
    }

    initializeTables() {
        // Initialize empty arrays for each table if they don't exist
        Object.values(this.tables).forEach(tableName => {
            if (!localStorage.getItem(tableName)) {
                localStorage.setItem(tableName, JSON.stringify([]));
            }
        });
    }

    generateId() {
        // Generate unique ID using timestamp and random number
        return `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }

    // CREATE operations
    async insert(tableName, data) {
        try {
            const records = this.getAll(tableName);
            const newRecord = {
                ...data,
                id: data.id || this.generateId(),
                created_at: data.created_at || new Date().toISOString(),
                updated_at: new Date().toISOString()
            };
            
            records.push(newRecord);
            localStorage.setItem(tableName, JSON.stringify(records));
            return newRecord;
        } catch (error) {
            console.error(`Insert failed for table ${tableName}:`, error);
            throw error;
        }
    }

    async insertMany(tableName, dataArray) {
        try {
            const records = this.getAll(tableName);
            const newRecords = dataArray.map(data => ({
                ...data,
                id: data.id || this.generateId(),
                created_at: data.created_at || new Date().toISOString(),
                updated_at: new Date().toISOString()
            }));
            
            records.push(...newRecords);
            localStorage.setItem(tableName, JSON.stringify(records));
            return newRecords;
        } catch (error) {
            console.error(`Batch insert failed for table ${tableName}:`, error);
            throw error;
        }
    }

    // READ operations
    getAll(tableName) {
        try {
            const data = localStorage.getItem(tableName);
            return data ? JSON.parse(data) : [];
        } catch (error) {
            console.error(`Get all failed for table ${tableName}:`, error);
            return [];
        }
    }

    getById(tableName, id) {
        try {
            const records = this.getAll(tableName);
            return records.find(record => record.id === id);
        } catch (error) {
            console.error(`Get by ID failed for table ${tableName}:`, error);
            return null;
        }
    }

    query(tableName, filterFn) {
        try {
            const records = this.getAll(tableName);
            return records.filter(filterFn);
        } catch (error) {
            console.error(`Query failed for table ${tableName}:`, error);
            return [];
        }
    }

    // Advanced query methods
    where(tableName, conditions) {
        try {
            const records = this.getAll(tableName);
            return records.filter(record => {
                return Object.entries(conditions).every(([key, value]) => {
                    if (typeof value === 'object' && value !== null) {
                        // Handle operators like { $gt: 10 }, { $in: ['a', 'b'] }
                        if (value.$gt !== undefined) return record[key] > value.$gt;
                        if (value.$lt !== undefined) return record[key] < value.$lt;
                        if (value.$gte !== undefined) return record[key] >= value.$gte;
                        if (value.$lte !== undefined) return record[key] <= value.$lte;
                        if (value.$in !== undefined) return value.$in.includes(record[key]);
                        if (value.$nin !== undefined) return !value.$nin.includes(record[key]);
                        if (value.$ne !== undefined) return record[key] !== value.$ne;
                    }
                    return record[key] === value;
                });
            });
        } catch (error) {
            console.error(`Where query failed for table ${tableName}:`, error);
            return [];
        }
    }

    // UPDATE operations
    async update(tableName, id, updateData) {
        try {
            const records = this.getAll(tableName);
            const index = records.findIndex(record => record.id === id);
            
            if (index !== -1) {
                records[index] = {
                    ...records[index],
                    ...updateData,
                    updated_at: new Date().toISOString()
                };
                localStorage.setItem(tableName, JSON.stringify(records));
                return records[index];
            }
            return null;
        } catch (error) {
            console.error(`Update failed for table ${tableName}:`, error);
            throw error;
        }
    }

    async updateWhere(tableName, conditions, updateData) {
        try {
            const records = this.getAll(tableName);
            let updatedCount = 0;
            
            const updatedRecords = records.map(record => {
                const matches = Object.entries(conditions).every(([key, value]) => record[key] === value);
                if (matches) {
                    updatedCount++;
                    return {
                        ...record,
                        ...updateData,
                        updated_at: new Date().toISOString()
                    };
                }
                return record;
            });
            
            localStorage.setItem(tableName, JSON.stringify(updatedRecords));
            return updatedCount;
        } catch (error) {
            console.error(`Update where failed for table ${tableName}:`, error);
            throw error;
        }
    }

    // DELETE operations
    async delete(tableName, id) {
        try {
            const records = this.getAll(tableName);
            const filteredRecords = records.filter(record => record.id !== id);
            
            if (filteredRecords.length !== records.length) {
                localStorage.setItem(tableName, JSON.stringify(filteredRecords));
                return true;
            }
            return false;
        } catch (error) {
            console.error(`Delete failed for table ${tableName}:`, error);
            throw error;
        }
    }

    async deleteWhere(tableName, conditions) {
        try {
            const records = this.getAll(tableName);
            const filteredRecords = records.filter(record => {
                return !Object.entries(conditions).every(([key, value]) => record[key] === value);
            });
            
            const deletedCount = records.length - filteredRecords.length;
            localStorage.setItem(tableName, JSON.stringify(filteredRecords));
            return deletedCount;
        } catch (error) {
            console.error(`Delete where failed for table ${tableName}:`, error);
            throw error;
        }
    }

    // UTILITY operations
    async clearTable(tableName) {
        try {
            localStorage.setItem(tableName, JSON.stringify([]));
            return true;
        } catch (error) {
            console.error(`Clear table failed for ${tableName}:`, error);
            throw error;
        }
    }

    async clearAllTables() {
        try {
            Object.values(this.tables).forEach(tableName => {
                localStorage.setItem(tableName, JSON.stringify([]));
            });
            return true;
        } catch (error) {
            console.error('Clear all tables failed:', error);
            throw error;
        }
    }

    getTotalRecords() {
        try {
            let total = 0;
            Object.values(this.tables).forEach(tableName => {
                total += this.getAll(tableName).length;
            });
            return total;
        } catch (error) {
            console.error('Get total records failed:', error);
            return 0;
        }
    }

    getTableStats() {
        try {
            const stats = {};
            Object.entries(this.tables).forEach(([key, tableName]) => {
                stats[key] = {
                    tableName,
                    count: this.getAll(tableName).length
                };
            });
            return stats;
        } catch (error) {
            console.error('Get table stats failed:', error);
            return {};
        }
    }

    // BACKUP and RESTORE operations
    exportData() {
        try {
            const data = {};
            Object.entries(this.tables).forEach(([key, tableName]) => {
                data[key] = this.getAll(tableName);
            });
            
            const exportData = {
                timestamp: new Date().toISOString(),
                version: '1.0',
                data: data
            };
            
            return JSON.stringify(exportData, null, 2);
        } catch (error) {
            console.error('Export data failed:', error);
            throw error;
        }
    }

    async importData(jsonData) {
        try {
            const importData = JSON.parse(jsonData);
            
            if (!importData.data) {
                throw new Error('Invalid import data format');
            }
            
            Object.entries(importData.data).forEach(([key, records]) => {
                if (this.tables[key]) {
                    localStorage.setItem(this.tables[key], JSON.stringify(records));
                }
            });
            
            return true;
        } catch (error) {
            console.error('Import data failed:', error);
            throw error;
        }
    }

    // SEARCH operations
    search(tableName, searchTerm, fields = []) {
        try {
            const records = this.getAll(tableName);
            const searchLower = searchTerm.toString().toLowerCase();
            
            return records.filter(record => {
                if (fields.length === 0) {
                    // Search all fields
                    return Object.values(record).some(value => 
                        value && value.toString().toLowerCase().includes(searchLower)
                    );
                } else {
                    // Search specific fields
                    return fields.some(field => 
                        record[field] && record[field].toString().toLowerCase().includes(searchLower)
                    );
                }
            });
        } catch (error) {
            console.error(`Search failed for table ${tableName}:`, error);
            return [];
        }
    }

    // PAGINATION
    paginate(tableName, page = 1, limit = 10, orderBy = 'created_at', order = 'desc') {
        try {
            const records = this.getAll(tableName);
            
            // Sort records
            const sortedRecords = records.sort((a, b) => {
                const aVal = a[orderBy];
                const bVal = b[orderBy];
                
                if (order === 'desc') {
                    return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
                } else {
                    return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
                }
            });
            
            // Paginate
            const startIndex = (page - 1) * limit;
            const endIndex = startIndex + limit;
            const paginatedRecords = sortedRecords.slice(startIndex, endIndex);
            
            return {
                data: paginatedRecords,
                pagination: {
                    currentPage: page,
                    totalPages: Math.ceil(records.length / limit),
                    totalRecords: records.length,
                    hasNext: endIndex < records.length,
                    hasPrev: page > 1
                }
            };
        } catch (error) {
            console.error(`Pagination failed for table ${tableName}:`, error);
            return { data: [], pagination: {} };
        }
    }

    // VALIDATION
    validateRecord(tableName, record, schema = null) {
        // Basic validation - can be extended with more complex schemas
        if (!record.id) {
            record.id = this.generateId();
        }
        
        if (!record.created_at) {
            record.created_at = new Date().toISOString();
        }
        
        record.updated_at = new Date().toISOString();
        
        return record;
    }

    // CONNECTION status
    isConnected() {
        return this.connected;
    }

    getConnectionInfo() {
        return {
            connected: this.connected,
            type: 'localStorage',
            tables: Object.keys(this.tables).length,
            totalRecords: this.getTotalRecords()
        };
    }
}
            async processTask(task) {
                const processor = this.processors.get(task.type) || this.processors.get('single');
                return await processor.execute(task, this.agentSystem);
            }
        }

        // Base Processor Class
        class BaseProcessor {
            async execute(task, agentSystem) {
                // Simulate processing time
                await new Promise(resolve => setTimeout(resolve, Math.random() * 2000 + 1000));
                
                return {
                    processed: true,
                    result: `Task "${task.description}" completed successfully`,
                    timestamp: new Date().toISOString()
                };
            }
        }

        // Specific Processor Implementations
        class SingleTaskProcessor extends BaseProcessor {
            async execute(task, agentSystem) {
                agentSystem.log(`Processing single task: ${task.id}`, 'info');
                const result = await super.execute(task, agentSystem);
                result.type = 'single_task';
                return result;
            }
        }

        class WorkflowProcessor extends BaseProcessor {
            async execute(task, agentSystem) {
                agentSystem.log(`Processing workflow: ${task.id}`, 'info');
                
                const steps = ['Step 1: Initialize', 'Step 2: Process', 'Step 3: Finalize'];
                const stepResults = [];
                
                for (let i = 0; i < steps.length; i++) {
                    agentSystem.log(`Executing ${steps[i]}`, 'info');
                    await new Promise(resolve => setTimeout(resolve, 800));
                    stepResults.push(`${steps[i]} completed`);
                }
                
                return {
                    processed: true,
                    result: 'Workflow completed successfully',
                    steps: stepResults,
                    timestamp: new Date().toISOString()
                };
            }
        }

        class BatchProcessor extends BaseProcessor {
            async execute(task, agentSystem) {
                agentSystem.log(`Processing batch task: ${task.id}`, 'info');
                
                const batchSize = 5;
                const processed = [];
                
                for (let i = 0; i < batchSize; i++) {
                    agentSystem.log(`Processing batch item ${i + 1}/${batchSize}`, 'info');
                    await new Promise(resolve => setTimeout(resolve, 500));
                    processed.push(`Item ${i + 1} processed`);
                }
                
                return {
                    processed: true,
                    result: `Batch processing completed - ${batchSize} items processed`,
                    items: processed,
                    timestamp: new Date().toISOString()
                };
            }
        }

        class ScheduledProcessor extends BaseProcessor {
    async execute(task, agentSystem) {
        agentSystem.log(`Processing scheduled task: ${task.id}`, 'info');
        const result = await super.execute(task, agentSystem);
        result.type = 'scheduled_task';
        result.scheduledFor = task.parameters?.scheduledTime || 'immediate';
        return result;
    }
}

class MonitoringProcessor extends BaseProcessor {
    async execute(task, agentSystem) {
        agentSystem.log(`Processing monitoring task: ${task.id}`, 'info');
        
        // Simulate monitoring checks
        const checks = ['System Health', 'Database Status', 'Agent Status', 'Task Queue'];
        const results = {};
        
        for (const check of checks) {
            await new Promise(resolve => setTimeout(resolve, 300));
            results[check] = Math.random() > 0.8 ? 'Warning' : 'OK';
        }
        
        return {
            processed: true,
            result: 'Monitoring completed',
            checks: results,
            timestamp: new Date().toISOString()
        };
    }
}

// Enhanced Agent System with proper queue management
class EnhancedAgentSystem {
    constructor() {
        this.db = new DatabaseManager();
        this.taskEngine = null;
        this.agents = new Map();
        this.tasks = [];
        this.logs = [];
        this.isInitialized = false;
        this.processingQueue = false; 
        this.init();
    }

    async init() {
        console.log('🚀 Initializing Enhanced Agent System...');
        
        // Wait for database to be ready
        await new Promise(resolve => {
            const checkDb = () => {
                if (this.db.connected) {
                    resolve();
                } else {
                    setTimeout(checkDb, 100);
                }
            };
            checkDb();
        });

        // FIXED: Initialize Task Processing Engine properly
        this.taskEngine = new TaskProcessingEngine(this);
        
        // Load existing data from database
        await this.loadFromDatabase();
        
        // Initialize default agents
        this.createDefaultAgents();
        
        // Start monitoring
        this.startSystemMonitoring();
        
        // Update UI
        this.updateUI();
        
        this.isInitialized = true;
        this.log('System initialized successfully', 'success');
    }

    async loadFromDatabase() {
        // Load tasks
        const savedTasks = this.db.getAll(this.db.tables.tasks);
        this.tasks = savedTasks.map(task => ({
            ...task,
            createdAt: new Date(task.created_at),
            updatedAt: new Date(task.updated_at)
        }));

        // Load agents
        const savedAgents = this.db.getAll(this.db.tables.agents);
        savedAgents.forEach(agent => {
            this.agents.set(agent.id, {
                ...agent,
                createdAt: new Date(agent.created_at),
                status: 'idle' // Reset status on load
            });
        });

        this.log(`Loaded ${this.tasks.length} tasks and ${this.agents.size} agents from database`, 'info');
    }

    createDefaultAgents() {
        if (this.agents.size === 0) {
            const defaultAgents = [
                { name: 'Task Manager', role: 'coordinator', capabilities: ['task_management', 'workflow'] },
                { name: 'Data Processor', role: 'worker', capabilities: ['data_processing', 'analysis'] },
                { name: 'Web Scraper', role: 'worker', capabilities: ['web_scraping', 'data_extraction'] },
                { name: 'Monitor Agent', role: 'observer', capabilities: ['monitoring', 'alerting'] }
            ];

            defaultAgents.forEach(agentData => {
                this.createAgent(agentData);
            });
        }
    }

    async createAgent(agentData) {
        const agent = {
            id: this.db.generateId(),
            name: agentData.name,
            role: agentData.role || 'worker',
            capabilities: agentData.capabilities || [],
            status: 'idle',
            tasksCompleted: 0,
            tasksInProgress: 0,
            createdAt: new Date()
        };

        this.agents.set(agent.id, agent);
        
        // Save to database
        await this.db.insert(this.db.tables.agents, {
            ...agent,
            createdAt: agent.createdAt.toISOString()
        });

        this.log(`Created agent: ${agent.name}`, 'success');
        this.updateUI();
        return agent;
    }

    async createTask(taskData) {
        const task = {
            id: this.db.generateId(),
            type: taskData.type || 'single',
            description: taskData.description,
            priority: taskData.priority || 'normal',
            assignedAgent: taskData.assignedAgent || null,
            status: 'queued',
            parameters: taskData.parameters || {},
            dependencies: taskData.dependencies || [],
            createdAt: new Date(),
            retries: 0,
            maxRetries: 3
        };

        this.tasks.push(task);
        
        // Save to database
        await this.db.insert(this.db.tables.tasks, {
            ...task,
            createdAt: task.createdAt.toISOString()
        });

        this.log(`Created task: ${task.id} - ${task.description}`, 'info');
        
        // FIXED: Process task if engine is ready and not already processing
        if (this.taskEngine && !this.processingQueue) {
            setTimeout(() => this.processNextTask(), 100);
        }
        
        this.updateUI();
        return task;
    // FIXED VERSION - Replace the processNextTask method with this corrected version

    async processNextTask() {
    if (this.processingQueue) return; // Prevent multiple simultaneous processing
    
    const queuedTasks = this.tasks.filter(task => task.status === 'queued');
    if (queuedTasks.length === 0) return;

    this.processingQueue = true; // Set processing flag
    
    // Sort by priority
    const priorityOrder = { urgent: 4, high: 3, normal: 2, low: 1 };
    queuedTasks.sort((a, b) => priorityOrder[b.priority] - priorityOrder[a.priority]);

    const task = queuedTasks[0];
    
    try {
        // Update task status to processing
        task.status = 'processing';
        await this.db.update(this.db.tables.tasks, task.id, { status: 'processing' });
        this.updateUI(); // Update UI immediately
        
        // Process with task engine
        const result = await this.taskEngine.processTask(task);
        
        // Update task with results
        task.status = 'completed';
        task.result = result;
        task.completedAt = new Date();
        
        await this.db.update(this.db.tables.tasks, task.id, {
            status: 'completed',
            result: JSON.stringify(result),
            completed_at: task.completedAt.toISOString()
        });
        
        this.log(`Task completed: ${task.id}`, 'success');
        
    } catch (error) {
        task.status = 'failed';
        task.error = error.message;
        
        await this.db.update(this.db.tables.tasks, task.id, {
            status: 'failed',
            error: error.message
        });
        
        this.log(`Task failed: ${task.id} - ${error.message}`, 'error');
    }
    
    this.processingQueue = false; // Reset processing flag
    this.updateUI();

    startSystemMonitoring() {
        setInterval(() => {
            this.updateSystemMetrics();
            this.updateUI();
        }, 5000);
    }

    updateSystemMetrics() {
        const metrics = {
            id: this.db.generateId(),
            timestamp: new Date().toISOString(),
            active_agents: Array.from(this.agents.values()).filter(a => a.status === 'active').length,
            queued_tasks: this.tasks.filter(t => t.status === 'queued').length,
            processing_tasks: this.tasks.filter(t => t.status === 'processing').length,
            completed_tasks: this.tasks.filter(t => t.status === 'completed').length,
            failed_tasks: this.tasks.filter(t => t.status === 'failed').length,
            total_db_records: this.db.getTotalRecords()
        };

        // Save metrics to database (keep last 100 entries)
        const savedMetrics = this.db.getAll(this.db.tables.metrics);
        savedMetrics.push(metrics);
        if (savedMetrics.length > 100) {
            savedMetrics.splice(0, savedMetrics.length - 100);
        }
        localStorage.setItem(this.db.tables.metrics, JSON.stringify(savedMetrics));
    }

    log(message, level = 'info') {
        const logEntry = {
            id: this.db.generateId(),
            timestamp: new Date(),
            level: level,
            message: message
        };

        this.logs.push(logEntry);
        
        // Keep only last 100 logs in memory
        if (this.logs.length > 100) {
            this.logs.shift();
        }

        // Save to database
        this.db.insert(this.db.tables.logs, {
            ...logEntry,
            timestamp: logEntry.timestamp.toISOString()
        });

        console.log(`[${level.toUpperCase()}] ${message}`);
        this.updateLogsUI();
    }

    updateUI() {
        this.updateStatusCards();
        this.updateAgentsDisplay();
        this.updateTasksList();
        this.updateDatabaseTable();
    }

    updateStatusCards() {
        const activeAgents = Array.from(this.agents.values()).filter(a => a.status === 'active').length;
        const queuedTasks = this.tasks.filter(t => t.status === 'queued').length;
        const processingTasks = this.tasks.filter(t => t.status === 'processing').length;
        const completedTasks = this.tasks.filter(t => t.status === 'completed').length;
        const dbRecords = this.db.getTotalRecords();

        document.getElementById('active-agents').textContent = activeAgents;
        document.getElementById('queued-tasks').textContent = queuedTasks;
        document.getElementById('processing-tasks').textContent = processingTasks;
        document.getElementById('completed-tasks').textContent = completedTasks;
        document.getElementById('db-records').textContent = dbRecords;
    }

    updateAgentsDisplay() {
        const container = document.getElementById('agents-container');
        container.innerHTML = '';

        Array.from(this.agents.values()).forEach(agent => {
            const agentCard = document.createElement('div');
            agentCard.className = 'agent-card';
            agentCard.innerHTML = `
                <div class="agent-name">${agent.name}</div>
                <div class="agent-status status-${agent.status}">${agent.status}</div>
                <div style="font-size: 12px; color: #666;">
                    <div>Role: ${agent.role}</div>
                    <div>Tasks: ${agent.tasksCompleted || 0}</div>
                </div>
                <button class="btn btn-danger" onclick="agentSystem.deleteAgent('${agent.id}')" style="margin-top: 10px; padding: 5px 10px; font-size: 12px;">Remove</button>
            `;
            container.appendChild(agentCard);
        });

        // Update agent dropdown
        const agentSelect = document.getElementById('task-agent');
        agentSelect.innerHTML = '<option value="">Auto-assign</option>';
        Array.from(this.agents.values()).forEach(agent => {
            const option = document.createElement('option');
            option.value = agent.id;
            option.textContent = agent.name;
            agentSelect.appendChild(option);
        });
    }

    updateTasksList() {
        const container = document.getElementById('task-list');
        container.innerHTML = '';

        // Sort tasks by creation date (newest first)
        const sortedTasks = [...this.tasks].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

        sortedTasks.slice(0, 20).forEach(task => { // Show only last 20 tasks
            const taskItem = document.createElement('div');
            taskItem.className = 'task-item';
            
            const assignedAgent = task.assignedAgent ? 
                this.agents.get(task.assignedAgent)?.name || 'Unknown Agent' : 
                'Auto-assigned';

            taskItem.innerHTML = `
                <div class="task-header">
                    <span class="task-id">${task.id}</span>
                    <span class="task-status status-${task.status}">${task.status}</span>
                </div>
                <div style="margin-bottom: 8px;">
                    <strong>Type:</strong> ${task.type} | 
                    <strong>Priority:</strong> ${task.priority} | 
                    <strong>Agent:</strong> ${assignedAgent}
                </div>
                <div style="margin-bottom: 8px;">
                    <strong>Description:</strong> ${task.description}
                </div>
                <div style="font-size: 12px; color: #666;">
                    <div>Created: ${task.createdAt.toLocaleString()}</div>
                    ${task.completedAt ? `<div>Completed: ${task.completedAt.toLocaleString()}</div>` : ''}
                    ${task.error ? `<div style="color: #c53030;">Error: ${task.error}</div>` : ''}
                </div>
                <div style="margin-top: 10px;">
                    <button class="btn btn-danger" onclick="agentSystem.deleteTask('${task.id}')" style="padding: 5px 10px; font-size: 12px;">Delete</button>
                    ${task.status === 'failed' ? `<button class="btn btn-primary" onclick="agentSystem.retryTask('${task.id}')" style="padding: 5px 10px; font-size: 12px; margin-left: 5px;">Retry</button>` : ''}
                </div>
            `;
            container.appendChild(taskItem);
        });
    }

    updateDatabaseTable() {
        const tbody = document.getElementById('data-table-body');
        tbody.innerHTML = '';

        // Get recent records from all tables
        const allRecords = [];
        Object.entries(this.db.tables).forEach(([tableName, table]) => {
            const records = this.db.getAll(table);
            records.forEach(record => {
                allRecords.push({
                    ...record,
                    table: tableName
                });
            });
        });

        // Sort by creation date and take last 50
        allRecords.sort((a, b) => new Date(b.created_at || b.timestamp) - new Date(a.created_at || a.timestamp));
        allRecords.slice(0, 50).forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.id}</td>
                <td>${record.table}</td>
                <td>${record.status || record.level || 'N/A'}</td>
                <td>${new Date(record.created_at || record.timestamp).toLocaleString()}</td>
                <td>${record.updated_at ? new Date(record.updated_at).toLocaleString() : 'N/A'}</td>
                <td>
                    <button class="btn-danger" onclick="agentSystem.deleteRecord('${record.table}', '${record.id}')" style="padding: 3px 6px; font-size: 11px;">Delete</button>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    updateLogsUI() {
        const container = document.getElementById('logs-container');
        container.innerHTML = '';

        this.logs.slice(-20).forEach(log => {
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = `
                <span class="log-timestamp">[${log.timestamp.toLocaleTimeString()}]</span>
                <span class="log-level-${log.level}">[${log.level.toUpperCase()}]</span>
                <span>${log.message}</span>
            `;
            container.appendChild(logEntry);
        });

        // Auto-scroll to bottom
        container.scrollTop = container.scrollHeight;
    }

    async deleteAgent(agentId) {
        if (confirm('Are you sure you want to delete this agent?')) {
            this.agents.delete(agentId);
            await this.db.delete(this.db.tables.agents, agentId);
            this.log(`Deleted agent: ${agentId}`, 'warning');
            this.updateUI();
        }
    }

    async deleteTask(taskId) {
        if (confirm('Are you sure you want to delete this task?')) {
            this.tasks = this.tasks.filter(t => t.id !== taskId);
            await this.db.delete(this.db.tables.tasks, taskId);
            this.log(`Deleted task: ${taskId}`, 'warning');
            this.updateUI();
        }
    }

    async retryTask(taskId) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            task.status = 'queued';
            task.retries = 0;
            task.error = null;
            await this.db.update(this.db.tables.tasks, taskId, { 
                status: 'queued', 
                error: null 
            });
            this.log(`Retrying task: ${taskId}`, 'info');
            this.updateUI();
            setTimeout(() => this.processNextTask(), 100);
        }
    }

    async deleteRecord(table, id) {
        if (confirm('Are you sure you want to delete this record?')) {
            await this.db.delete(table, id);
            this.log(`Deleted record from ${table}: ${id}`, 'warning');
            this.updateUI();
        }
    }
}

// Global system instance
let agentSystem;

// UI Event Handlers - FIXED: Prevent form submission redirect
document.addEventListener('DOMContentLoaded', function() {
    // Initialize the system
    agentSystem = new EnhancedAgentSystem();

    // Task form submission
    document.getElementById('task-form').addEventListener('submit', function(e) {
        e.preventDefault(); // FIXED: This prevents the page redirect
        
        const taskData = {
            type: document.getElementById('task-type').value,
            description: document.getElementById('task-description').value,
            priority: document.getElementById('task-priority').value,
            assignedAgent: document.getElementById('task-agent').value || null,
            parameters: {}
        };

        if (taskData.description.trim()) {
            agentSystem.createTask(taskData);
            
            // Reset form
            document.getElementById('task-form').reset();
        } else {
            alert('Please enter a task description');
          // Global utility functions
function createAgent() {
    const name = prompt('Enter agent name:');
    if (name) {
        const role = prompt('Enter agent role (worker/coordinator/observer):', 'worker');
        const capabilities = prompt('Enter capabilities (comma-separated):', 'general').split(',').map(s => s.trim());
        
        agentSystem.createAgent({
            name: name,
            role: role || 'worker',
            capabilities: capabilities
        });
    }
}

function initializeDatabase() {
    agentSystem.db.clearAll();
    agentSystem.log('Database initialized', 'success');
    agentSystem.updateUI();
}

function exportData() {
    const data = {
        tasks: agentSystem.tasks,
        agents: Array.from(agentSystem.agents.values()),
        logs: agentSystem.logs,
        timestamp: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `agent_system_export_${Date.now()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    agentSystem.log('Data exported successfully', 'success');
}

function clearDatabase() {
    if (confirm('This will delete all data. Are you sure?')) {
        agentSystem.db.clearAll();
        agentSystem.tasks = [];
        agentSystem.agents.clear();
        agentSystem.logs = [];
        agentSystem.log('Database cleared', 'warning');
        agentSystem.updateUI();
    }
}

function showQueryInterface() {
    document.getElementById('query-modal').style.display = 'block';
}

function closeModal() {
    document.getElementById('query-modal').style.display = 'none';
}

function executeQuery() {
    const query = document.getElementById('query-input').value.trim();
    const resultsDiv = document.getElementById('query-results');
    
    if (!query) {
        resultsDiv.innerHTML = '<p style="color: red;">Please enter a query</p>';
        return;
    }
    
    // Simple query parser (basic SELECT functionality)
    try {
        let results = [];
        const lowerQuery = query.toLowerCase();
        
        if (lowerQuery.includes('from tasks')) {
            results = agentSystem.tasks;
        } else if (lowerQuery.includes('from agents')) {
            results = Array.from(agentSystem.agents.values());
        } else if (lowerQuery.includes('from logs')) {
            results = agentSystem.logs;
        } else {
            throw new Error('Unsupported query. Use: SELECT * FROM tasks/agents/logs');
        }
        
        // Basic WHERE filtering
        if (lowerQuery.includes('where')) {
            const whereMatch = query.match(/where\s+(\w+)\s*=\s*'([^']+)'/i);
            if (whereMatch) {
                const [, field, value] = whereMatch;
                results = results.filter(item => item[field] === value);
            }
        }
        
        // Display results
        if (results.length === 0) {
            resultsDiv.innerHTML = '<p>No results found</p>';
        } else {
            const table = document.createElement('table');
            table.className = 'data-table';
            table.style.marginTop = '15px';
            
            // Headers
            const headers = Object.keys(results[0]);
            const headerRow = table.insertRow();
            headers.forEach(header => {
                const th = document.createElement('th');
                th.textContent = header;
                headerRow.appendChild(th);
            });
            
            // Data rows
            results.slice(0, 20).forEach(item => {
                const row = table.insertRow();
                headers.forEach(header => {
                    const cell = row.insertCell();
                    let value = item[header];
                    if (typeof value === 'object' && value !== null) {
                        value = JSON.stringify(value);
                    }
                    cell.textContent = value || 'N/A';
                });
            });
            
            resultsDiv.innerHTML = '';
            resultsDiv.appendChild(table);
        }
        
        agentSystem.log(`Query executed: ${query}`, 'info');
        
    } catch (error) {
        resultsDiv.innerHTML = `<p style="color: red;">Query Error: ${error.message}</p>`;
        agentSystem.log(`Query failed: ${error.message}`, 'error');
    }
}

function clearLogs() {
    agentSystem.logs = [];
    agentSystem.db.clear(agentSystem.db.tables.logs);
    agentSystem.updateLogsUI();
    agentSystem.log('Logs cleared', 'info');
}
        }
    });
});
    </script>