memscope-rs 0.2.0

A memory tracking library for Rust applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
//! Dashboard renderer using Handlebars templates

use crate::analysis::memory_passport_tracker::MemoryPassportTracker;
use crate::tracker::Tracker;
use handlebars::Handlebars;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Risk score penalty per high-risk operation.
/// Each high-risk operation reduces the health score by this amount.
const HIGH_RISK_PENALTY: f64 = 10.0;

/// Dashboard context for template rendering
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardContext {
    /// Page title
    pub title: String,
    /// Export timestamp
    pub export_timestamp: String,
    /// Total memory allocated (formatted)
    pub total_memory: String,
    /// Total number of allocations
    pub total_allocations: usize,
    /// Number of active allocations
    pub active_allocations: usize,
    /// Peak memory usage (formatted)
    pub peak_memory: String,
    /// Number of threads
    pub thread_count: usize,
    /// Number of memory passports
    pub passport_count: usize,
    /// Number of memory leaks detected
    pub leak_count: usize,
    /// Number of unsafe operations
    pub unsafe_count: usize,
    /// Number of FFI operations
    pub ffi_count: usize,
    /// Allocation information
    pub allocations: Vec<AllocationInfo>,
    /// Variable relationships
    pub relationships: Vec<RelationshipInfo>,
    /// Unsafe/FFI reports
    pub unsafe_reports: Vec<UnsafeReport>,
    /// Detailed passport information
    pub passport_details: Vec<PassportDetail>,
    /// Count helper for template
    pub allocations_count: usize,
    /// Count helper for template
    pub relationships_count: usize,
    /// Count helper for template
    pub unsafe_reports_count: usize,
    /// JSON data string for injection (performance optimization)
    pub json_data: String,
    /// OS name
    pub os_name: String,
    /// Architecture
    pub architecture: String,
    /// CPU cores
    pub cpu_cores: usize,
    /// System resources
    pub system_resources: SystemResources,
    /// Thread analysis data
    pub threads: Vec<ThreadInfo>,
    /// Async task analysis data
    pub async_tasks: Vec<AsyncTaskInfo>,
    /// Async summary
    pub async_summary: AsyncSummary,
    /// Health score (0-100)
    pub health_score: u32,
    /// Health status text
    pub health_status: String,
    /// Safe operations count
    pub safe_ops_count: usize,
    /// High risk issues count
    pub high_risk_count: usize,
    /// Clean passports count
    pub clean_passport_count: usize,
    /// Active passports count
    pub active_passport_count: usize,
    /// Leaked passports count
    pub leaked_passport_count: usize,
    /// FFI tracked passports count
    pub ffi_tracked_count: usize,
    /// Safe code percentage
    pub safe_code_percent: u32,
    /// Ownership graph information
    pub ownership_graph: OwnershipGraphInfo,
}

/// Ownership graph information for dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnershipGraphInfo {
    /// Total number of nodes
    pub total_nodes: usize,
    /// Total number of edges
    pub total_edges: usize,
    /// Number of detected cycles
    pub total_cycles: usize,
    /// Rc clone count
    pub rc_clone_count: usize,
    /// Arc clone count
    pub arc_clone_count: usize,
    /// Whether there are issues
    pub has_issues: bool,
    /// Detected issues
    pub issues: Vec<OwnershipIssue>,
    /// Root cause if any
    pub root_cause: Option<RootCauseInfo>,
}

/// Ownership issue for dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnershipIssue {
    /// Issue type
    pub issue_type: String,
    /// Severity (error, warning)
    pub severity: String,
    /// Description
    pub description: String,
}

/// Root cause information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RootCauseInfo {
    /// Cause type
    pub cause: String,
    /// Description
    pub description: String,
    /// Impact
    pub impact: String,
}

/// Async task information for dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsyncTaskInfo {
    /// Task ID
    pub task_id: u64,
    /// Task name
    pub task_name: String,
    /// Task type
    pub task_type: String,
    /// Total bytes allocated
    pub total_bytes: u64,
    /// Current memory usage
    pub current_memory: u64,
    /// Peak memory usage
    pub peak_memory: u64,
    /// Number of allocations
    pub total_allocations: u64,
    /// Duration in milliseconds
    pub duration_ms: f64,
    /// Efficiency score (0.0 - 1.0)
    pub efficiency_score: f64,
    /// Whether task is completed
    pub is_completed: bool,
    /// Whether task has potential leak
    pub has_potential_leak: bool,
}

/// Async summary for dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsyncSummary {
    /// Total number of async tasks
    pub total_tasks: usize,
    /// Number of active tasks
    pub active_tasks: usize,
    /// Total allocations across all tasks
    pub total_allocations: usize,
    /// Total memory bytes
    pub total_memory_bytes: usize,
    /// Peak memory bytes
    pub peak_memory_bytes: usize,
}

/// Allocation information for dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AllocationInfo {
    /// Memory address
    pub address: String,
    /// Type name
    pub type_name: String,
    /// Allocation size in bytes
    pub size: usize,
    /// Variable name
    pub var_name: String,
    /// Timestamp
    pub timestamp: String,
    /// Thread ID
    pub thread_id: String,
    /// Borrow information
    pub immutable_borrows: usize,
    pub mutable_borrows: usize,
    /// Clone information
    pub is_clone: bool,
    pub clone_count: usize,
    /// Allocation timestamp (nanoseconds)
    pub timestamp_alloc: u64,
    /// Deallocation timestamp (nanoseconds, 0 if not freed)
    pub timestamp_dealloc: u64,
    /// Lifetime in milliseconds
    pub lifetime_ms: f64,
    /// Whether memory is leaked
    pub is_leaked: bool,
    /// Allocation type (stack, heap, etc.)
    pub allocation_type: String,
    /// Whether this is a smart pointer
    pub is_smart_pointer: bool,
    /// Smart pointer type (Arc, Rc, Box, etc.)
    pub smart_pointer_type: String,
    /// Source file where allocation occurred
    pub source_file: Option<String>,
    /// Source line where allocation occurred
    pub source_line: Option<u32>,
}

/// Thread statistics for multithread dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ThreadStats {
    /// Thread ID
    id: u64,
    /// Number of allocations
    allocations: usize,
    /// Total memory used
    memory: usize,
    /// Peak memory usage
    peak: usize,
    /// Thread status
    status: String,
}

/// Timeline allocation for multithread dashboard
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TimelineAllocation {
    /// Timestamp
    timestamp: u64,
    /// Thread ID
    thread_id: u64,
    /// Allocation size
    size: usize,
    /// Variable name
    var_name: Option<String>,
}

/// Thread conflict information
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ThreadConflict {
    /// Description of the conflict
    description: String,
    /// Threads involved
    threads: String,
    /// Conflict type
    #[serde(rename = "type")]
    conflict_type: String,
}

/// Variable relationship information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelationshipInfo {
    /// Source pointer
    pub source_ptr: String,
    /// Source variable name
    pub source_var_name: String,
    /// Target pointer
    pub target_ptr: String,
    /// Target variable name
    pub target_var_name: String,
    /// Relationship type (reference, borrow, clone, copy, move, ownership_transfer)
    pub relationship_type: String,
    /// Relationship strength (0.0 to 1.0)
    pub strength: f64,
    /// Type name
    pub type_name: String,
    /// Color for visualization
    pub color: String,
    /// Whether this relationship is part of a detected cycle (true) or not (false)
    pub is_part_of_cycle: bool,
}

/// Unsafe/FFI report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnsafeReport {
    /// Passport ID
    pub passport_id: String,
    /// Allocation pointer
    pub allocation_ptr: String,
    /// Variable name
    pub var_name: String,
    /// Type name
    pub type_name: String,
    /// Size in bytes
    pub size_bytes: usize,
    /// Created at timestamp
    pub created_at: u64,
    /// Last update timestamp
    pub updated_at: u64,
    /// Status at shutdown
    pub status: String,
    /// Lifecycle events
    pub lifecycle_events: Vec<LifecycleEventInfo>,
    /// Cross-boundary events
    pub cross_boundary_events: Vec<BoundaryEventInfo>,
    /// Whether this is a memory leak
    pub is_leaked: bool,
    /// Risk level (low, medium, high)
    pub risk_level: String,
    /// Risk factors
    pub risk_factors: Vec<String>,
}

/// Lifecycle event information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LifecycleEventInfo {
    /// Event type
    pub event_type: String,
    /// Timestamp
    pub timestamp: u64,
    /// Context
    pub context: String,
    /// Event icon
    pub icon: String,
    /// Event color
    pub color: String,
}

/// Boundary event information (FFI/Rust crossings)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundaryEventInfo {
    /// Event type (RustToFfi, FfiToRust, etc.)
    pub event_type: String,
    /// Source context
    pub from_context: String,
    /// Target context
    pub to_context: String,
    /// Timestamp
    pub timestamp: u64,
    /// Direction icon
    pub icon: String,
    /// Direction color
    pub color: String,
}

/// Detailed passport information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PassportDetail {
    /// Passport ID
    pub passport_id: String,
    /// Allocation pointer
    pub allocation_ptr: String,
    /// Variable name
    pub var_name: String,
    /// Type name
    pub type_name: String,
    /// Size in bytes
    pub size_bytes: usize,
    /// Status at shutdown
    pub status: String,
    /// Created at
    pub created_at: u64,
    /// Updated at
    pub updated_at: u64,
    /// Whether leaked
    pub is_leaked: bool,
    /// Whether FFI tracked
    pub ffi_tracked: bool,
    /// Lifecycle events
    pub lifecycle_events: Vec<LifecycleEventInfo>,
    /// Cross-boundary events
    pub cross_boundary_events: Vec<BoundaryEventInfo>,
    /// Risk level
    pub risk_level: String,
    /// Risk confidence
    pub risk_confidence: f64,
}

/// System resources information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemResources {
    /// OS name
    pub os_name: String,
    /// OS version
    pub os_version: String,
    /// CPU architecture
    pub architecture: String,
    /// Number of CPU cores
    pub cpu_cores: u32,
    /// Total physical memory (formatted)
    pub total_physical: String,
    /// Available physical memory (formatted)
    pub available_physical: String,
    /// Used physical memory (formatted)
    pub used_physical: String,
    /// Page size
    pub page_size: u64,
}

/// Thread information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadInfo {
    /// Thread ID (formatted as "Thread-N" instead of "ThreadId(N)")
    pub thread_id: String,
    /// Thread summary (e.g., "5 allocs, 1.2KB")
    pub thread_summary: String,
    /// Number of allocations
    pub allocation_count: usize,
    /// Current memory usage
    pub current_memory: String,
    /// Peak memory usage
    pub peak_memory: String,
    /// Total allocated
    pub total_allocated: String,
    /// Raw current memory in bytes for sorting
    pub current_memory_bytes: usize,
    /// Raw peak memory in bytes for sorting
    pub peak_memory_bytes: usize,
    /// Raw total allocated in bytes for sorting
    pub total_allocated_bytes: usize,
}

struct ThreadAggregator {
    allocation_count: usize,
    current_memory: usize,
    peak_memory: usize,
    total_allocated: usize,
}

/// Dashboard renderer
pub struct DashboardRenderer {
    handlebars: Handlebars<'static>,
}

impl DashboardRenderer {
    /// Create a new dashboard renderer
    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let mut handlebars = Handlebars::new();

        let template_path = format!(
            "{}/src/render_engine/dashboard/templates/dashboard_unified.html",
            env!("CARGO_MANIFEST_DIR")
        );
        handlebars.register_template_file("dashboard_unified", &template_path)?;

        let final_path = format!(
            "{}/src/render_engine/dashboard/templates/dashboard_final.html",
            env!("CARGO_MANIFEST_DIR")
        );
        handlebars.register_template_file("dashboard_final", &final_path)?;

        handlebars.register_helper("format_bytes", Box::new(format_bytes_helper));
        handlebars.register_helper("gt", Box::new(greater_than_helper));
        handlebars.register_helper("contains", Box::new(contains_helper));
        handlebars.register_helper("json", Box::new(json_helper));

        Ok(Self { handlebars })
    }

    /// Extract user source file from stack trace (filter out Rust internals)
    fn extract_user_source_file(stack_trace: &Option<Vec<String>>) -> Option<String> {
        if let Some(ref frames) = stack_trace {
            for frame in frames {
                let frame_lower = frame.to_lowercase();
                if !frame_lower.contains("/rustc/")
                    && !frame_lower.contains("/library/")
                    && !frame_lower.contains("memscope")
                    && !frame_lower.contains(".cargo/registry")
                    && !frame_lower.contains("/src/core/")
                    && !frame_lower.contains("/src/capture/")
                    && !frame_lower.contains("/src/unified/")
                    && !frame_lower.contains("/src/tracker")
                {
                    if let Some(file_part) = frame.split(':').next() {
                        let file_name = file_part.split('/').next_back().unwrap_or(file_part);
                        if !file_name.starts_with('<') && file_name.contains(".rs") {
                            return Some(file_part.to_string());
                        }
                    }
                }
            }
        }
        None
    }

    /// Extract user source line from stack trace (filter out Rust internals)
    fn extract_user_source_line(stack_trace: &Option<Vec<String>>) -> Option<u32> {
        if let Some(ref frames) = stack_trace {
            for frame in frames {
                let frame_lower = frame.to_lowercase();
                if !frame_lower.contains("/rustc/")
                    && !frame_lower.contains("/library/")
                    && !frame_lower.contains("memscope")
                    && !frame_lower.contains(".cargo/registry")
                    && !frame_lower.contains("/src/core/")
                    && !frame_lower.contains("/src/capture/")
                    && !frame_lower.contains("/src/unified/")
                    && !frame_lower.contains("/src/tracker")
                {
                    if let Some(line_part) = frame.rsplit(':').next() {
                        if let Ok(line) = line_part.parse::<u32>() {
                            return Some(line);
                        }
                    }
                }
            }
        }
        None
    }

    /// Build relationships using the relation inference system
    fn build_relationships_from_inference(
        allocations: &[crate::capture::backends::core_types::AllocationInfo],
        alloc_info: &[AllocationInfo],
    ) -> Vec<RelationshipInfo> {
        use crate::analysis::relation_inference::{Relation, RelationGraphBuilder};
        use crate::snapshot::types::ActiveAllocation;

        // Convert AllocationInfo to ActiveAllocation
        let active_allocations: Vec<ActiveAllocation> = allocations
            .iter()
            .map(|a| ActiveAllocation {
                ptr: a.ptr,
                size: a.size,
                allocated_at: a.allocated_at_ns,
                var_name: a.var_name.clone(),
                type_name: a.type_name.clone(),
                thread_id: a.thread_id,
                call_stack_hash: None,
            })
            .collect();

        let graph = RelationGraphBuilder::build(&active_allocations, None);

        let mut relationships = Vec::new();

        for edge in &graph.edges {
            let from_alloc = alloc_info.get(edge.from);
            let to_alloc = alloc_info.get(edge.to);

            let (rel_type, color, strength) = match edge.relation {
                Relation::Owner => ("ownership_transfer", "#dc2626", 1.0),
                Relation::Slice => ("immutable_borrow", "#3b82f6", 0.8),
                Relation::Clone => ("clone", "#10b981", 0.9),
                Relation::Shared => ("Arc", "#8b5cf6", 0.7),
            };

            let source_addr = from_alloc
                .and_then(|a| {
                    if a.address.starts_with("0x") {
                        usize::from_str_radix(&a.address[2..], 16).ok()
                    } else {
                        None
                    }
                })
                .unwrap_or(edge.from);

            let target_addr = to_alloc
                .and_then(|a| {
                    if a.address.starts_with("0x") {
                        usize::from_str_radix(&a.address[2..], 16).ok()
                    } else {
                        None
                    }
                })
                .unwrap_or(edge.to);

            relationships.push(RelationshipInfo {
                source_ptr: format!("0x{:x}", source_addr),
                source_var_name: from_alloc
                    .map(|a| a.var_name.clone())
                    .unwrap_or_else(|| format!("alloc_{}", edge.from)),
                target_ptr: format!("0x{:x}", target_addr),
                target_var_name: to_alloc
                    .map(|a| a.var_name.clone())
                    .unwrap_or_else(|| format!("alloc_{}", edge.to)),
                relationship_type: rel_type.to_string(),
                strength,
                type_name: from_alloc
                    .map(|a| a.type_name.clone())
                    .unwrap_or_else(|| "unknown".to_string()),
                color: color.to_string(),
                is_part_of_cycle: false,
            });
        }

        // Limit relationships to avoid performance issues
        if relationships.len() > 500 {
            relationships.truncate(500);
        }

        relationships
    }

    /// Infer type from size-based heuristics when type_name is unknown
    fn infer_type_from_size(size: usize) -> String {
        match size {
            8 => "*mut c_void (30%)".to_string(),
            16 => "&[T] (25%)".to_string(),
            24 => "Vec<_>/String (15%)".to_string(),
            32 | 48 | 64 => "CStruct (10%)".to_string(),
            n if n.is_power_of_two() && n >= 64 => {
                format!("Vec<_>/[u8] ({}%)", 10 + n.trailing_zeros() as u8)
            }
            n if (32..=256).contains(&n) => "[u8] (10%)".to_string(),
            _ => "unknown".to_string(),
        }
    }

    /// Get inferred type name with confidence
    fn get_inferred_type_name(type_name: &str, size: usize) -> String {
        if type_name != "unknown" && type_name != "-" && !type_name.is_empty() {
            return type_name.to_string();
        }
        Self::infer_type_from_size(size)
    }

    /// Build dashboard context from tracker data
    pub fn build_context_from_tracker(
        &self,
        tracker: &Tracker,
        passport_tracker: &Arc<MemoryPassportTracker>,
    ) -> Result<DashboardContext, Box<dyn std::error::Error>> {
        self.build_context_from_tracker_with_async(tracker, passport_tracker, None)
    }

    /// Build dashboard context from tracker data with async support
    pub fn build_context_from_tracker_with_async(
        &self,
        tracker: &Tracker,
        passport_tracker: &Arc<MemoryPassportTracker>,
        async_tracker: Option<&Arc<crate::capture::backends::async_tracker::AsyncTracker>>,
    ) -> Result<DashboardContext, Box<dyn std::error::Error>> {
        let allocations = tracker.inner().get_active_allocations().unwrap_or_default();
        let passports = passport_tracker.get_all_passports();
        let analysis = tracker.analyze();

        let total_memory: usize = allocations.iter().map(|a| a.size).sum();

        // Build allocation info
        let alloc_info: Vec<AllocationInfo> = allocations
            .iter()
            .map(|a| {
                let original_type_name =
                    a.type_name.clone().unwrap_or_else(|| "unknown".to_string());
                let type_name = Self::get_inferred_type_name(&original_type_name, a.size);
                let timestamp_alloc = a.allocated_at_ns;
                let timestamp_dealloc = 0u64;
                let lifetime_ms = 0.0;

                // Determine if smart pointer
                let is_smart_pointer = type_name.contains("Arc")
                    || type_name.contains("Rc")
                    || type_name.contains("Box");
                let smart_pointer_type = if type_name.contains("Arc") {
                    "Arc".to_string()
                } else if type_name.contains("Rc") {
                    "Rc".to_string()
                } else if type_name.contains("Box") {
                    "Box".to_string()
                } else {
                    String::new()
                };

                AllocationInfo {
                    address: format!("0x{:x}", a.ptr),
                    type_name: type_name.clone(),
                    size: a.size,
                    var_name: a.var_name.clone().unwrap_or_else(|| "unknown".to_string()),
                    timestamp: format!("{:?}", a.allocated_at_ns),
                    thread_id: format!("{}", a.thread_id),
                    immutable_borrows: 0,
                    mutable_borrows: 0,
                    is_clone: false,
                    clone_count: 0,
                    timestamp_alloc,
                    timestamp_dealloc,
                    lifetime_ms,
                    is_leaked: true,
                    allocation_type: "heap".to_string(),
                    is_smart_pointer,
                    smart_pointer_type,
                    source_file: Self::extract_user_source_file(&a.stack_trace),
                    source_line: Self::extract_user_source_line(&a.stack_trace),
                }
            })
            .collect();

        // Build variable relationships using RelationGraphBuilder
        let mut relationships = Self::build_relationships_from_inference(&allocations, &alloc_info);

        // Detect cycles in relationships and mark cycle edges
        let cycle_edges: std::collections::HashSet<(String, String)> = {
            let rel_tuples: Vec<(String, String, String)> = relationships
                .iter()
                .map(|r| {
                    (
                        r.source_ptr.clone(),
                        r.target_ptr.clone(),
                        r.type_name.clone(),
                    )
                })
                .collect();
            let result = crate::analysis::detect_cycles_in_relationships(&rel_tuples);
            result.cycle_edges
        };

        for rel in &mut relationships {
            if cycle_edges.contains(&(rel.source_ptr.clone(), rel.target_ptr.clone())) {
                rel.is_part_of_cycle = true;
                rel.color = "#ef4444".to_string();
            }
        }

        // Build unsafe reports from passports
        let unsafe_reports: Vec<UnsafeReport> = passports.values()
            .filter(|p| !p.lifecycle_events.is_empty())
            .map(|p| {
                // Build lifecycle events
                let lifecycle_events: Vec<LifecycleEventInfo> = p.lifecycle_events.iter()
                    .map(|event| {
                        let (icon, color, context) = match &event.event_type {
                            crate::analysis::memory_passport_tracker::PassportEventType::AllocatedInRust => {
                                ("🟢".to_string(), "#10b981".to_string(), "Rust Allocation".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::HandoverToFfi => {
                                ("⬇️".to_string(), "#f59e0b".to_string(), "Handover to FFI".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::FreedByForeign => {
                                ("🔵".to_string(), "#3b82f6".to_string(), "Freed by Foreign".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::ReclaimedByRust => {
                                ("⬆️".to_string(), "#10b981".to_string(), "Reclaimed by Rust".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::BoundaryAccess => {
                                ("🔄".to_string(), "#8b5cf6".to_string(), "Boundary Access".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::OwnershipTransfer => {
                                ("↔️".to_string(), "#dc2626".to_string(), "Ownership Transfer".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::ValidationCheck => {
                                ("".to_string(), "#10b981".to_string(), "Validation Check".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::CorruptionDetected => {
                                ("🚨".to_string(), "#dc2626".to_string(), "Corruption Detected".to_string())
                            }
                        };

                        LifecycleEventInfo {
                            event_type: format!("{:?}", event.event_type),
                            timestamp: event.timestamp,
                            context,
                            icon,
                            color,
                        }
                    })
                    .collect();

                // Build cross-boundary events
                let cross_boundary_events: Vec<BoundaryEventInfo> = lifecycle_events.iter()
                    .filter(|e| e.event_type.contains("Handover") || e.event_type.contains("Reclaimed"))
                    .map(|e| {
                        let (event_type, from, to, icon, color) = if e.event_type.contains("HandoverToFfi") {
                            ("RustToFfi".to_string(), "Rust".to_string(), "FFI".to_string(), "⬇️".to_string(), "#f59e0b".to_string())
                        } else if e.event_type.contains("ReclaimedByRust") {
                            ("FfiToRust".to_string(), "FFI".to_string(), "Rust".to_string(), "⬆️".to_string(), "#10b981".to_string())
                        } else {
                            (e.event_type.clone(), "Unknown".to_string(), "Unknown".to_string(), "".to_string(), "#6b7280".to_string())
                        };

                        BoundaryEventInfo {
                            event_type,
                            from_context: from,
                            to_context: to,
                            timestamp: e.timestamp,
                            icon,
                            color,
                        }
                    })
                    .collect();

                // Determine risk level
                let is_leaked = p.status_at_shutdown == crate::analysis::memory_passport_tracker::PassportStatus::InForeignCustody ||
                               p.status_at_shutdown == crate::analysis::memory_passport_tracker::PassportStatus::HandoverToFfi;
                let risk_level = if is_leaked {
                    "high".to_string()
                } else if !cross_boundary_events.is_empty() {
                    "medium".to_string()
                } else {
                    "low".to_string()
                };

                // Use passport's stored type and variable name, fallback to allocations if needed
                let var_name = if p.var_name != "-" {
                    p.var_name.clone()
                } else {
                    allocations.iter()
                        .find(|a| a.ptr == p.allocation_ptr)
                        .and_then(|a| a.var_name.clone())
                        .unwrap_or_else(|| "-".to_string())
                };

                let type_name = if p.type_name != "-" {
                    p.type_name.clone()
                } else {
                    let from_alloc = allocations.iter()
                        .find(|a| a.ptr == p.allocation_ptr)
                        .and_then(|a| a.type_name.clone())
                        .unwrap_or_else(|| "-".to_string());

                    if from_alloc != "-" {
                        from_alloc
                    } else {
                        Self::infer_type_from_size(p.size_bytes)
                    }
                };

                // Risk factors
                let mut risk_factors = Vec::new();
                if is_leaked {
                    risk_factors.push("Memory leaked at shutdown".to_string());
                }
                if !cross_boundary_events.is_empty() {
                    risk_factors.push(format!("Crosses FFI boundary {} times", cross_boundary_events.len()));
                }
                if cross_boundary_events.len() > 3 {
                    risk_factors.push("Frequent boundary crossings".to_string());
                }

                UnsafeReport {
                    passport_id: p.passport_id.clone(),
                    allocation_ptr: format!("0x{:x}", p.allocation_ptr),
                    var_name,
                    type_name,
                    size_bytes: p.size_bytes,
                    created_at: p.created_at,
                    updated_at: p.updated_at,
                    status: format!("{:?}", p.status_at_shutdown),
                    lifecycle_events,
                    cross_boundary_events,
                    is_leaked,
                    risk_level,
                    risk_factors,
                }
            })
            .collect();

        // Build passport details
        let passport_details: Vec<PassportDetail> = passports.values()
            .map(|p| {
                // Build lifecycle events
                let lifecycle_events: Vec<LifecycleEventInfo> = p.lifecycle_events.iter()
                    .map(|event| {
                        let (icon, color, context) = match &event.event_type {
                            crate::analysis::memory_passport_tracker::PassportEventType::AllocatedInRust => {
                                ("🟢".to_string(), "#10b981".to_string(), "Rust Allocation".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::HandoverToFfi => {
                                ("⬇️".to_string(), "#f59e0b".to_string(), "Handover to FFI".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::FreedByForeign => {
                                ("🔵".to_string(), "#3b82f6".to_string(), "Freed by Foreign".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::ReclaimedByRust => {
                                ("⬆️".to_string(), "#10b981".to_string(), "Reclaimed by Rust".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::BoundaryAccess => {
                                ("🔄".to_string(), "#8b5cf6".to_string(), "Boundary Access".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::OwnershipTransfer => {
                                ("↔️".to_string(), "#dc2626".to_string(), "Ownership Transfer".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::ValidationCheck => {
                                ("".to_string(), "#10b981".to_string(), "Validation Check".to_string())
                            }
                            crate::analysis::memory_passport_tracker::PassportEventType::CorruptionDetected => {
                                ("🚨".to_string(), "#dc2626".to_string(), "Corruption Detected".to_string())
                            }
                        };

                        LifecycleEventInfo {
                            event_type: format!("{:?}", event.event_type),
                            timestamp: event.timestamp,
                            context,
                            icon: icon.to_string(),
                            color,
                        }
                    })
                    .collect();

                // Build cross-boundary events
                let cross_boundary_events: Vec<BoundaryEventInfo> = lifecycle_events.iter()
                    .filter(|e| e.event_type.contains("Handover") || e.event_type.contains("Reclaimed"))
                    .map(|e| {
                        let (event_type, from, to, icon, color) = if e.event_type.contains("HandoverToFfi") {
                            ("RustToFfi".to_string(), "Rust".to_string(), "FFI".to_string(), "⬇️".to_string(), "#f59e0b".to_string())
                        } else if e.event_type.contains("ReclaimedByRust") {
                            ("FfiToRust".to_string(), "FFI".to_string(), "Rust".to_string(), "⬆️".to_string(), "#10b981".to_string())
                        } else {
                            (e.event_type.clone(), "Unknown".to_string(), "Unknown".to_string(), "".to_string(), "#6b7280".to_string())
                        };

                        BoundaryEventInfo {
                            event_type,
                            from_context: from,
                            to_context: to,
                            timestamp: e.timestamp,
                            icon,
                            color,
                        }
                    })
                    .collect();

                // Use passport's stored type and variable name, fallback to allocations if needed
                let var_name = if p.var_name != "-" {
                    p.var_name.clone()
                } else {
                    allocations.iter()
                        .find(|a| a.ptr == p.allocation_ptr)
                        .and_then(|a| a.var_name.clone())
                        .unwrap_or_else(|| "-".to_string())
                };

                let type_name = if p.type_name != "-" {
                    p.type_name.clone()
                } else {
                    let from_alloc = allocations.iter()
                        .find(|a| a.ptr == p.allocation_ptr)
                        .and_then(|a| a.type_name.clone())
                        .unwrap_or_else(|| "-".to_string());

                    if from_alloc != "-" {
                        from_alloc
                    } else {
                        Self::infer_type_from_size(p.size_bytes)
                    }
                };

                // Determine risk level
                let is_leaked = p.status_at_shutdown == crate::analysis::memory_passport_tracker::PassportStatus::InForeignCustody ||
                               p.status_at_shutdown == crate::analysis::memory_passport_tracker::PassportStatus::HandoverToFfi;
                let risk_level = if is_leaked {
                    "high".to_string()
                } else if !cross_boundary_events.is_empty() {
                    "medium".to_string()
                } else {
                    "low".to_string()
                };

                PassportDetail {
                    passport_id: p.passport_id.clone(),
                    allocation_ptr: format!("0x{:x}", p.allocation_ptr),
                    var_name,
                    type_name,
                    size_bytes: p.size_bytes,
                    status: format!("{:?}", p.status_at_shutdown),
                    created_at: p.created_at,
                    updated_at: p.updated_at,
                    is_leaked,
                    ffi_tracked: !cross_boundary_events.is_empty(),
                    lifecycle_events,
                    cross_boundary_events,
                    risk_level,
                    risk_confidence: 0.85, // Default confidence
                }
            })
            .collect();

        // Perform leak detection
        let leak_result = passport_tracker.detect_leaks_at_shutdown();
        let leak_count = leak_result.leaked_passports.len();

        // Build thread data from allocations
        let thread_data = Self::aggregate_thread_data(&alloc_info);

        // Prepare JSON data for direct injection (performance optimization)

        #[derive(serde::Serialize)]
        struct DashboardData<'a> {
            allocations: &'a [AllocationInfo],
            relationships: &'a [RelationshipInfo],
            unsafe_reports: &'a [UnsafeReport],
            threads: &'a [ThreadInfo],
            passport_details: &'a [PassportDetail],
            active_allocations: usize,
            total_allocations: usize,
            leak_count: usize,
            async_tasks: &'a [AsyncTaskInfo],
            async_summary: &'a AsyncSummary,
            ownership_graph: &'a OwnershipGraphInfo,
        }

        let async_tasks = Self::build_async_tasks(async_tracker);
        let async_summary = Self::build_async_summary(async_tracker);
        let ownership_graph = Self::build_ownership_graph_info(&allocations);
        let data = DashboardData {
            allocations: &alloc_info,
            relationships: &relationships,
            unsafe_reports: &unsafe_reports,
            threads: &thread_data,
            passport_details: &passport_details,
            active_allocations: analysis.active_allocations,
            total_allocations: analysis.total_allocations,
            leak_count,
            async_tasks: &async_tasks,
            async_summary: &async_summary,
            ownership_graph: &ownership_graph,
        };

        let json_data: String = serde_json::to_string(&data)
            .map_err(|e| format!("Failed to serialize dashboard data: {}", e))?;

        // Get system information directly using platform-specific functions
        let (
            os_name,
            os_version,
            architecture,
            cpu_cores,
            page_size,
            total_physical,
            available_physical,
            used_physical,
        ) = {
            #[cfg(target_os = "macos")]
            {
                // Get OS version
                let os_version = unsafe {
                    let mut size: libc::size_t = 256;
                    let mut buf = [0u8; 256];
                    if libc::sysctlbyname(
                        c"kern.osrelease".as_ptr(),
                        buf.as_mut_ptr() as *mut libc::c_void,
                        &mut size,
                        std::ptr::null_mut(),
                        0,
                    ) == 0
                    {
                        String::from_utf8_lossy(&buf[..size - 1]).to_string()
                    } else {
                        "Unknown".to_string()
                    }
                };

                // Get architecture
                let architecture = unsafe {
                    let mut size: libc::size_t = 256;
                    let mut buf = [0u8; 256];
                    if libc::sysctlbyname(
                        c"hw.machine".as_ptr(),
                        buf.as_mut_ptr() as *mut libc::c_void,
                        &mut size,
                        std::ptr::null_mut(),
                        0,
                    ) == 0
                    {
                        let arch_str = String::from_utf8_lossy(&buf[..size - 1]).to_string();
                        if arch_str.contains("arm64") || arch_str.contains("arm") {
                            "arm64".to_string()
                        } else {
                            arch_str
                        }
                    } else {
                        "unknown".to_string()
                    }
                };

                // Get CPU cores
                let mut size = std::mem::size_of::<u32>();
                let mut cpu_cores: u32 = 1;
                unsafe {
                    let mut mib: [libc::c_int; 2] = [libc::CTL_HW, libc::HW_NCPU];
                    if libc::sysctl(
                        mib.as_mut_ptr(),
                        mib.len() as libc::c_uint,
                        &mut cpu_cores as *mut u32 as *mut libc::c_void,
                        &mut size,
                        std::ptr::null_mut(),
                        0,
                    ) == 0
                    {
                        // Successfully got CPU cores
                    }
                }

                // Get page size
                let mut page_size: u64 = 4096;
                unsafe {
                    size = std::mem::size_of::<u64>();
                    if libc::sysctlbyname(
                        c"hw.pagesize".as_ptr(),
                        &mut page_size as *mut u64 as *mut libc::c_void,
                        &mut size,
                        std::ptr::null_mut(),
                        0,
                    ) != 0
                    {
                        page_size = 4096;
                    }
                }

                // Get total physical memory
                let mut total: u64 = 0;
                let mut size = std::mem::size_of::<u64>();
                unsafe {
                    let mut mib: [libc::c_int; 2] = [libc::CTL_HW, libc::HW_MEMSIZE];
                    if libc::sysctl(
                        mib.as_mut_ptr(),
                        mib.len() as libc::c_uint,
                        &mut total as *mut u64 as *mut libc::c_void,
                        &mut size,
                        std::ptr::null_mut(),
                        0,
                    ) != 0
                    {
                        total = 16 * 1024 * 1024 * 1024; // 16GB default
                    }
                }

                // Get available memory
                let mut vm_stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
                let mut count = libc::HOST_VM_INFO64_COUNT;
                let (available_physical, used_physical) = unsafe {
                    if libc::host_statistics64(
                        mach2::mach_init::mach_host_self(),
                        libc::HOST_VM_INFO64,
                        &mut vm_stats as *mut _ as libc::host_info64_t,
                        &mut count,
                    ) != 0
                    {
                        // Fall back to simple calculation
                        (total / 2, total / 2)
                    } else {
                        let free = vm_stats.free_count as u64 * page_size;
                        let active = vm_stats.active_count as u64 * page_size;
                        let inactive = vm_stats.inactive_count as u64 * page_size;
                        let wired = vm_stats.wire_count as u64 * page_size;
                        let used = active + wired;
                        let available = free + inactive;

                        (available, used)
                    }
                };

                (
                    "macOS".to_string(),
                    os_version,
                    architecture,
                    cpu_cores,
                    page_size,
                    total,
                    available_physical,
                    used_physical,
                )
            }

            #[cfg(not(target_os = "macos"))]
            {
                (
                    "Unknown".to_string(),
                    "Unknown".to_string(),
                    "unknown".to_string(),
                    1,
                    4096,
                    16_u64 * 1024 * 1024 * 1024,
                    8_u64 * 1024 * 1024 * 1024,
                    8_u64 * 1024 * 1024 * 1024,
                )
            }
        };

        let high_risk_count = unsafe_reports
            .iter()
            .filter(|r| r.risk_level == "high")
            .count();
        let clean_passport_count = passport_details.iter().filter(|p| !p.is_leaked).count();
        let active_passport_count = passport_details
            .iter()
            .filter(|p| p.status == "active")
            .count();
        let leaked_passport_count = passport_details.iter().filter(|p| p.is_leaked).count();
        let ffi_tracked_count = passport_details.iter().filter(|p| p.ffi_tracked).count();
        let total_allocs = alloc_info.len().max(1);
        let unsafe_count = unsafe_reports.len();
        let leak_score = (100.0 - (leak_count as f64 / total_allocs as f64) * 100.0).max(0.0);
        let unsafe_score = (100.0 - (unsafe_count as f64 / total_allocs as f64) * 50.0).max(0.0);
        let risk_score = (100.0 - high_risk_count as f64 * HIGH_RISK_PENALTY).max(0.0);
        let health_score = ((leak_score + unsafe_score + risk_score) / 3.0).round() as u32;
        let health_status = if health_score >= 80 {
            "✅ Excellent"
        } else if health_score >= 60 {
            "⚠️ Good"
        } else {
            "🚨 Needs Attention"
        };
        let safe_ops_count = total_allocs.saturating_sub(unsafe_count);
        let safe_code_percent =
            ((safe_ops_count as f64 / total_allocs as f64) * 100.0).round() as u32;

        let context = DashboardContext {
            title: "MemScope Dashboard".to_string(),
            export_timestamp: chrono::Utc::now()
                .format("%Y-%m-%d %H:%M:%S UTC")
                .to_string(),
            total_memory: format_bytes(total_memory),
            total_allocations: analysis.total_allocations,
            active_allocations: analysis.active_allocations,
            peak_memory: format_bytes(analysis.peak_memory_bytes as usize),
            thread_count: 1,
            passport_count: passports.len(),
            leak_count,
            unsafe_count: unsafe_reports.len(),
            ffi_count: unsafe_reports.len(),
            allocations: alloc_info.clone(),
            relationships: relationships.clone(),
            unsafe_reports: unsafe_reports.clone(),
            passport_details: passport_details.clone(),
            allocations_count: alloc_info.len(),
            relationships_count: relationships.len(),
            unsafe_reports_count: unsafe_reports.len(),
            json_data,
            os_name: os_name.clone(),
            architecture: architecture.clone(),
            cpu_cores: cpu_cores as usize,
            system_resources: SystemResources {
                os_name: os_name.clone(),
                os_version: os_version.clone(),
                architecture: architecture.clone(),
                cpu_cores,
                total_physical: format_bytes(total_physical as usize),
                available_physical: format_bytes(available_physical as usize),
                used_physical: format_bytes(used_physical as usize),
                page_size,
            },
            threads: Self::aggregate_thread_data(&alloc_info),
            async_tasks: Self::build_async_tasks(async_tracker),
            async_summary: Self::build_async_summary(async_tracker),
            health_score,
            health_status: health_status.to_string(),
            safe_ops_count,
            high_risk_count,
            clean_passport_count,
            active_passport_count,
            leaked_passport_count,
            ffi_tracked_count,
            safe_code_percent,
            ownership_graph: Self::build_ownership_graph_info(&allocations),
        };

        Ok(context)
    }

    /// Build ownership graph info from allocations
    fn build_ownership_graph_info(
        allocations: &[crate::capture::backends::core_types::AllocationInfo],
    ) -> OwnershipGraphInfo {
        use crate::analysis::ownership_graph::{
            DiagnosticIssue, ObjectId, OwnershipGraph, OwnershipOp,
        };

        // Convert allocations to passport format for graph building
        let passports: Vec<(
            ObjectId,
            String,
            usize,
            Vec<crate::analysis::ownership_graph::OwnershipEvent>,
        )> = allocations
            .iter()
            .map(|alloc| {
                let id = ObjectId::from_ptr(alloc.ptr);
                let type_name = alloc
                    .type_name
                    .clone()
                    .unwrap_or_else(|| "unknown".to_string());
                let size = alloc.size;

                // Generate ownership events from allocation info
                let events = vec![crate::analysis::ownership_graph::OwnershipEvent::new(
                    alloc.allocated_at_ns,
                    OwnershipOp::Create,
                    id,
                    None,
                )];

                (id, type_name, size, events)
            })
            .collect();

        let graph = OwnershipGraph::build(&passports);
        let diagnostics = graph.diagnostics(50);

        // Build issues list
        let issues = diagnostics
            .issues
            .iter()
            .map(|issue| match issue {
                DiagnosticIssue::RcCycle { cycle_type, .. } => OwnershipIssue {
                    issue_type: "RcCycle".to_string(),
                    severity: "error".to_string(),
                    description: format!("{:?} retain cycle detected", cycle_type),
                },
                DiagnosticIssue::ArcCloneStorm {
                    clone_count,
                    threshold,
                } => OwnershipIssue {
                    issue_type: "ArcCloneStorm".to_string(),
                    severity: "warning".to_string(),
                    description: format!(
                        "Arc clone storm: {} clones (threshold: {})",
                        clone_count, threshold
                    ),
                },
            })
            .collect();

        // Build root cause
        let root_cause = graph.find_root_cause().map(|rc| RootCauseInfo {
            cause: format!("{:?}", rc.root_cause),
            description: rc.description,
            impact: rc.impact,
        });

        OwnershipGraphInfo {
            total_nodes: graph.nodes.len(),
            total_edges: graph.edges.len(),
            total_cycles: graph.cycles.len(),
            rc_clone_count: diagnostics.rc_clone_count,
            arc_clone_count: diagnostics.arc_clone_count,
            has_issues: diagnostics.has_issues(),
            issues,
            root_cause,
        }
    }

    fn build_async_tasks(
        async_tracker: Option<&Arc<crate::capture::backends::async_tracker::AsyncTracker>>,
    ) -> Vec<AsyncTaskInfo> {
        if let Some(tracker) = async_tracker {
            let profiles = tracker.get_all_profiles();
            profiles
                .into_iter()
                .map(|p| {
                    let is_completed = p.is_completed();
                    let has_potential_leak = p.has_potential_leak();
                    let task_type_str = format!("{:?}", p.task_type);
                    AsyncTaskInfo {
                        task_id: p.task_id,
                        task_name: p.task_name,
                        task_type: task_type_str,
                        total_bytes: p.total_bytes,
                        current_memory: p.current_memory,
                        peak_memory: p.peak_memory,
                        total_allocations: p.total_allocations,
                        duration_ms: p.duration_ns as f64 / 1_000_000.0,
                        efficiency_score: p.efficiency_score,
                        is_completed,
                        has_potential_leak,
                    }
                })
                .collect()
        } else {
            Vec::new()
        }
    }

    fn build_async_summary(
        async_tracker: Option<&Arc<crate::capture::backends::async_tracker::AsyncTracker>>,
    ) -> AsyncSummary {
        if let Some(tracker) = async_tracker {
            let stats = tracker.get_stats();
            AsyncSummary {
                total_tasks: stats.total_tasks,
                active_tasks: stats.active_tasks,
                total_allocations: stats.total_allocations,
                total_memory_bytes: stats.total_memory,
                peak_memory_bytes: stats.peak_memory,
            }
        } else {
            AsyncSummary {
                total_tasks: 0,
                active_tasks: 0,
                total_allocations: 0,
                total_memory_bytes: 0,
                peak_memory_bytes: 0,
            }
        }
    }

    fn aggregate_thread_data(allocations: &[AllocationInfo]) -> Vec<ThreadInfo> {
        use std::collections::HashMap;
        let mut thread_map: HashMap<String, ThreadAggregator> = HashMap::new();

        for alloc in allocations {
            let entry = thread_map
                .entry(alloc.thread_id.clone())
                .or_insert_with(|| ThreadAggregator {
                    allocation_count: 0,
                    current_memory: 0,
                    peak_memory: 0,
                    total_allocated: 0,
                });
            entry.allocation_count += 1;
            entry.current_memory += alloc.size;
            entry.total_allocated += alloc.size;
            if alloc.size > entry.peak_memory {
                entry.peak_memory = alloc.size;
            }
        }

        thread_map
            .into_iter()
            .map(|(raw_tid, agg)| {
                let summary = format!(
                    "{} allocs, {}",
                    agg.allocation_count,
                    format_bytes(agg.current_memory)
                );
                let thread_id = format_thread_id(&raw_tid);
                ThreadInfo {
                    thread_id,
                    thread_summary: summary,
                    allocation_count: agg.allocation_count,
                    current_memory: format_bytes(agg.current_memory),
                    peak_memory: format_bytes(agg.peak_memory),
                    total_allocated: format_bytes(agg.total_allocated),
                    current_memory_bytes: agg.current_memory,
                    peak_memory_bytes: agg.peak_memory,
                    total_allocated_bytes: agg.total_allocated,
                }
            })
            .collect()
    }

    /// Render dashboard from tracker data (for standalone template)
    pub fn render_from_tracker(
        &self,
        tracker: &Tracker,
        passport_tracker: &Arc<MemoryPassportTracker>,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let context = self.build_context_from_tracker(tracker, passport_tracker)?;
        self.render_dashboard(&context)
    }

    /// Render dashboard from context
    pub fn render_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        self.render_unified_dashboard(context)
    }

    /// Render standalone dashboard (no external dependencies, works with file:// protocol)
    pub fn render_standalone_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        self.render_unified_dashboard(context)
    }

    /// Render unified dashboard (multi-mode in single HTML)
    pub fn render_unified_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert(
            "title".to_string(),
            serde_json::Value::String(context.title.clone()),
        );
        template_data.insert(
            "export_timestamp".to_string(),
            serde_json::Value::String(context.export_timestamp.clone()),
        );
        template_data.insert(
            "total_memory".to_string(),
            serde_json::Value::String(context.total_memory.clone()),
        );
        template_data.insert(
            "total_allocations".to_string(),
            serde_json::Value::Number(context.total_allocations.into()),
        );
        template_data.insert(
            "active_allocations".to_string(),
            serde_json::Value::Number(context.active_allocations.into()),
        );
        template_data.insert(
            "peak_memory".to_string(),
            serde_json::Value::String(context.peak_memory.clone()),
        );
        template_data.insert(
            "thread_count".to_string(),
            serde_json::Value::Number(context.thread_count.into()),
        );
        template_data.insert(
            "passport_count".to_string(),
            serde_json::Value::Number(context.passport_count.into()),
        );
        template_data.insert(
            "leak_count".to_string(),
            serde_json::Value::Number(context.leak_count.into()),
        );
        template_data.insert(
            "unsafe_count".to_string(),
            serde_json::Value::Number(context.unsafe_count.into()),
        );
        template_data.insert(
            "ffi_count".to_string(),
            serde_json::Value::Number(context.ffi_count.into()),
        );
        template_data.insert(
            "allocations_count".to_string(),
            serde_json::Value::Number(context.allocations_count.into()),
        );
        template_data.insert(
            "relationships_count".to_string(),
            serde_json::Value::Number(context.relationships_count.into()),
        );
        template_data.insert(
            "unsafe_reports_count".to_string(),
            serde_json::Value::Number(context.unsafe_reports_count.into()),
        );
        template_data.insert(
            "os_name".to_string(),
            serde_json::Value::String(context.os_name.clone()),
        );
        template_data.insert(
            "architecture".to_string(),
            serde_json::Value::String(context.architecture.clone()),
        );
        template_data.insert(
            "cpu_cores".to_string(),
            serde_json::Value::Number(context.cpu_cores.into()),
        );
        template_data.insert(
            "json_data".to_string(),
            serde_json::Value::String(context.json_data.clone()),
        );
        template_data.insert(
            "health_score".to_string(),
            serde_json::Value::Number(context.health_score.into()),
        );
        template_data.insert(
            "health_status".to_string(),
            serde_json::Value::String(context.health_status.clone()),
        );
        template_data.insert(
            "safe_ops_count".to_string(),
            serde_json::Value::Number(context.safe_ops_count.into()),
        );
        template_data.insert(
            "high_risk_count".to_string(),
            serde_json::Value::Number(context.high_risk_count.into()),
        );
        template_data.insert(
            "clean_passport_count".to_string(),
            serde_json::Value::Number(context.clean_passport_count.into()),
        );
        template_data.insert(
            "active_passport_count".to_string(),
            serde_json::Value::Number(context.active_passport_count.into()),
        );
        template_data.insert(
            "leaked_passport_count".to_string(),
            serde_json::Value::Number(context.leaked_passport_count.into()),
        );
        template_data.insert(
            "ffi_tracked_count".to_string(),
            serde_json::Value::Number(context.ffi_tracked_count.into()),
        );
        template_data.insert(
            "safe_code_percent".to_string(),
            serde_json::Value::Number(context.safe_code_percent.into()),
        );

        template_data.insert(
            "allocations".to_string(),
            serde_json::to_value(&context.allocations)?,
        );
        template_data.insert(
            "passport_details".to_string(),
            serde_json::to_value(&context.passport_details)?,
        );
        template_data.insert(
            "relationships".to_string(),
            serde_json::to_value(&context.relationships)?,
        );
        template_data.insert(
            "unsafe_reports".to_string(),
            serde_json::to_value(&context.unsafe_reports)?,
        );
        template_data.insert(
            "threads".to_string(),
            serde_json::to_value(&context.threads)?,
        );
        template_data.insert(
            "ownership_graph".to_string(),
            serde_json::to_value(&context.ownership_graph)?,
        );

        self.handlebars
            .render("dashboard_unified", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Render final dashboard (new investigation console template)
    pub fn render_final_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert(
            "title".to_string(),
            serde_json::Value::String(context.title.clone()),
        );
        template_data.insert(
            "export_timestamp".to_string(),
            serde_json::Value::String(context.export_timestamp.clone()),
        );
        template_data.insert(
            "total_memory".to_string(),
            serde_json::Value::String(context.total_memory.clone()),
        );
        template_data.insert(
            "total_allocations".to_string(),
            serde_json::Value::Number(context.total_allocations.into()),
        );
        template_data.insert(
            "active_allocations".to_string(),
            serde_json::Value::Number(context.active_allocations.into()),
        );
        template_data.insert(
            "peak_memory".to_string(),
            serde_json::Value::String(context.peak_memory.clone()),
        );
        template_data.insert(
            "thread_count".to_string(),
            serde_json::Value::Number(context.thread_count.into()),
        );
        template_data.insert(
            "passport_count".to_string(),
            serde_json::Value::Number(context.passport_count.into()),
        );
        template_data.insert(
            "leak_count".to_string(),
            serde_json::Value::Number(context.leak_count.into()),
        );
        template_data.insert(
            "unsafe_count".to_string(),
            serde_json::Value::Number(context.unsafe_count.into()),
        );
        template_data.insert(
            "ffi_count".to_string(),
            serde_json::Value::Number(context.ffi_count.into()),
        );
        template_data.insert(
            "health_score".to_string(),
            serde_json::Value::Number(context.health_score.into()),
        );
        template_data.insert(
            "health_status".to_string(),
            serde_json::Value::String(context.health_status.clone()),
        );
        template_data.insert(
            "safe_ops_count".to_string(),
            serde_json::Value::Number(context.safe_ops_count.into()),
        );
        template_data.insert(
            "high_risk_count".to_string(),
            serde_json::Value::Number(context.high_risk_count.into()),
        );
        template_data.insert(
            "clean_passport_count".to_string(),
            serde_json::Value::Number(context.clean_passport_count.into()),
        );
        template_data.insert(
            "active_passport_count".to_string(),
            serde_json::Value::Number(context.active_passport_count.into()),
        );
        template_data.insert(
            "leaked_passport_count".to_string(),
            serde_json::Value::Number(context.leaked_passport_count.into()),
        );
        template_data.insert(
            "ffi_tracked_count".to_string(),
            serde_json::Value::Number(context.ffi_tracked_count.into()),
        );
        template_data.insert(
            "safe_code_percent".to_string(),
            serde_json::Value::Number(context.safe_code_percent.into()),
        );
        template_data.insert(
            "os_name".to_string(),
            serde_json::Value::String(context.os_name.clone()),
        );
        template_data.insert(
            "architecture".to_string(),
            serde_json::Value::String(context.architecture.clone()),
        );
        template_data.insert(
            "cpu_cores".to_string(),
            serde_json::Value::Number(context.cpu_cores.into()),
        );
        template_data.insert(
            "json_data".to_string(),
            serde_json::Value::String(context.json_data.clone()),
        );
        template_data.insert(
            "allocations".to_string(),
            serde_json::to_value(&context.allocations)?,
        );
        template_data.insert(
            "passport_details".to_string(),
            serde_json::to_value(&context.passport_details)?,
        );
        template_data.insert(
            "relationships".to_string(),
            serde_json::to_value(&context.relationships)?,
        );
        template_data.insert(
            "unsafe_reports".to_string(),
            serde_json::to_value(&context.unsafe_reports)?,
        );
        template_data.insert(
            "threads".to_string(),
            serde_json::to_value(&context.threads)?,
        );
        template_data.insert(
            "async_tasks".to_string(),
            serde_json::to_value(&context.async_tasks)?,
        );
        template_data.insert(
            "ownership_graph".to_string(),
            serde_json::to_value(&context.ownership_graph)?,
        );

        self.handlebars
            .render("dashboard_final", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Render binary dashboard (legacy template)
    pub fn render_binary_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let legacy_data = self.to_legacy_binary_data(context);
        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert("BINARY_DATA".to_string(), legacy_data);
        template_data.insert(
            "PROJECT_NAME".to_string(),
            serde_json::Value::String("MemScope Memory Analysis".to_string()),
        );

        self.handlebars
            .render("binary_dashboard", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Render clean dashboard (legacy template)
    pub fn render_clean_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let legacy_data = self.to_legacy_binary_data(context);
        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert("BINARY_DATA".to_string(), legacy_data.clone());
        template_data.insert("json_data".to_string(), legacy_data);
        template_data.insert(
            "PROJECT_NAME".to_string(),
            serde_json::Value::String("MemScope Memory Analysis".to_string()),
        );

        self.handlebars
            .render("clean_dashboard", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Render hybrid dashboard (legacy template)
    pub fn render_hybrid_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let variables_data = serde_json::Value::Array(
            context
                .allocations
                .iter()
                .map(|a| {
                    let mut map = serde_json::Map::new();
                    map.insert(
                        "var_name".to_string(),
                        serde_json::Value::String(a.var_name.clone()),
                    );
                    map.insert(
                        "type_name".to_string(),
                        serde_json::Value::String(a.type_name.clone()),
                    );
                    map.insert("size".to_string(), serde_json::Value::Number(a.size.into()));
                    map.insert(
                        "address".to_string(),
                        serde_json::Value::String(a.address.clone()),
                    );
                    map.insert(
                        "is_leaked".to_string(),
                        serde_json::Value::Bool(a.is_leaked),
                    );
                    map.insert(
                        "timestamp_alloc".to_string(),
                        serde_json::Value::Number(a.timestamp_alloc.into()),
                    );
                    map.insert(
                        "timestamp_dealloc".to_string(),
                        serde_json::Value::Number(a.timestamp_dealloc.into()),
                    );
                    map.insert(
                        "thread_id".to_string(),
                        serde_json::Value::String(a.thread_id.clone()),
                    );
                    serde_json::Value::Object(map)
                })
                .collect(),
        );

        let threads_data = serde_json::Value::Array(
            context
                .threads
                .iter()
                .map(|t| {
                    let mut map = serde_json::Map::new();
                    map.insert(
                        "thread_id".to_string(),
                        serde_json::Value::String(t.thread_id.clone()),
                    );
                    map.insert(
                        "allocation_count".to_string(),
                        serde_json::Value::String(t.allocation_count.to_string()),
                    );
                    map.insert(
                        "current_memory".to_string(),
                        serde_json::Value::String(t.current_memory.clone()),
                    );
                    map.insert(
                        "peak_memory".to_string(),
                        serde_json::Value::String(t.peak_memory.clone()),
                    );
                    map.insert(
                        "total_allocated".to_string(),
                        serde_json::Value::String(t.total_allocated.clone()),
                    );
                    serde_json::Value::Object(map)
                })
                .collect(),
        );

        let tasks_data = serde_json::Value::Array(Vec::new());

        let total_memory: usize = context.allocations.iter().map(|a| a.size).sum();
        let efficiency = if context.total_allocations > 0 {
            (context.active_allocations as f64 / context.total_allocations as f64 * 100.0) as usize
        } else {
            100
        };

        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert("VARIABLES_DATA".to_string(), variables_data);
        template_data.insert("THREADS_DATA".to_string(), threads_data);
        template_data.insert("TASKS_DATA".to_string(), tasks_data);
        template_data.insert(
            "PROJECT_NAME".to_string(),
            serde_json::Value::String("MemScope Memory Analysis".to_string()),
        );
        template_data.insert(
            "TOTAL_MEMORY".to_string(),
            serde_json::Value::String(format_bytes(total_memory)),
        );
        template_data.insert(
            "TOTAL_VARIABLES".to_string(),
            serde_json::Value::Number(context.allocations.len().into()),
        );
        template_data.insert(
            "THREAD_COUNT".to_string(),
            serde_json::Value::Number(context.thread_count.into()),
        );
        template_data.insert(
            "EFFICIENCY".to_string(),
            serde_json::Value::String(format!("{}%", efficiency)),
        );

        self.handlebars
            .render("hybrid_dashboard", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Render performance dashboard (legacy template)
    pub fn render_performance_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        // Prepare performance data in expected format
        let performance_data = serde_json::json!({
            "allocations": context.allocations.iter().map(|a| {
                serde_json::json!({
                    "timestamp": a.timestamp_alloc,
                    "memory": a.size,
                    "var_name": a.var_name,
                    "type_name": a.type_name
                })
            }).collect::<Vec<_>>(),
            "total_memory": context.total_memory,
            "peak_memory": context.peak_memory,
            "allocations_count": context.total_allocations,
            "thread_count": context.thread_count
        });

        // Prepare efficiency data
        // Calculate fragmentation: ratio of active allocations to total allocations
        // Higher ratio = less fragmentation (more allocations still in use)
        let fragmentation = if context.total_allocations > 0 {
            let deallocated = context
                .total_allocations
                .saturating_sub(context.active_allocations);
            deallocated as f64 / context.total_allocations as f64 * 100.0
        } else {
            0.0
        };

        // Calculate reclamation rate: percentage of memory that was deallocated
        // This estimates how well the program is cleaning up memory
        let reclamation_rate = if context.total_allocations > 0 {
            let active_ratio = context.active_allocations as f64 / context.total_allocations as f64;
            (1.0 - active_ratio) * 100.0
        } else {
            100.0
        };

        let efficiency_data = serde_json::json!({
            "memory_efficiency": if context.total_allocations > 0 {
                context.active_allocations as f64 / context.total_allocations as f64 * 100.0
            } else { 100.0 },
            "fragmentation": format!("{:.1}", fragmentation),
            "reclamation_rate": format!("{:.1}", reclamation_rate),
            "average_size": if context.allocations.is_empty() {
                0
            } else {
                context.allocations.iter().map(|a| a.size).sum::<usize>() / context.allocations.len()
            }
        });

        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert(
            "PERFORMANCE_DATA",
            serde_json::to_string(&performance_data)?,
        );
        template_data.insert("EFFICIENCY_DATA", serde_json::to_string(&efficiency_data)?);
        template_data.insert("PROJECT_NAME", "MemScope Memory Analysis".to_string());

        self.handlebars
            .render("performance_dashboard", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Render multithread dashboard (new template for thread analysis)
    pub fn render_multithread_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let threads_data = self.prepare_thread_data(context)?;
        let allocation_data = self.prepare_allocation_timeline_data(context)?;
        let conflict_data = self.prepare_conflict_data(context)?;

        let conflict_count = conflict_data.as_array().map(|a| a.len()).unwrap_or(0);
        let mut template_data = std::collections::BTreeMap::new();
        template_data.insert("THREADS_DATA".to_string(), threads_data);
        template_data.insert("ALLOCATION_DATA".to_string(), allocation_data);
        template_data.insert("CONFLICT_DATA".to_string(), conflict_data);
        template_data.insert(
            "PROJECT_NAME".to_string(),
            serde_json::Value::String("MemScope Memory Analysis".to_string()),
        );
        template_data.insert(
            "THREAD_COUNT".to_string(),
            serde_json::Value::Number(context.thread_count.into()),
        );
        template_data.insert(
            "TOTAL_MEMORY".to_string(),
            serde_json::Value::String(context.total_memory.clone()),
        );
        template_data.insert(
            "TOTAL_ALLOCATIONS".to_string(),
            serde_json::Value::Number(context.total_allocations.into()),
        );
        template_data.insert(
            "CONFLICT_COUNT".to_string(),
            serde_json::Value::Number(conflict_count.into()),
        );

        self.handlebars
            .render("multithread_template", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Prepare thread data for multithread dashboard
    fn prepare_thread_data(
        &self,
        context: &DashboardContext,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut thread_map: std::collections::HashMap<String, ThreadStats> =
            std::collections::HashMap::new();

        for allocation in &context.allocations {
            let thread_id = allocation.thread_id.clone();
            let stats = thread_map
                .entry(thread_id.clone())
                .or_insert_with(|| ThreadStats {
                    id: thread_id.parse::<u64>().unwrap_or(0),
                    allocations: 0,
                    memory: 0,
                    peak: 0,
                    status: "active".to_string(),
                });

            stats.allocations += 1;
            stats.memory += allocation.size;
            if allocation.size > stats.peak {
                stats.peak = allocation.size;
            }
        }

        let threads: Vec<ThreadStats> = thread_map.into_values().collect();
        serde_json::to_value(&threads).map_err(|e| e.into())
    }

    /// Prepare allocation timeline data for multithread dashboard
    fn prepare_allocation_timeline_data(
        &self,
        context: &DashboardContext,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let timeline: Vec<TimelineAllocation> = context
            .allocations
            .iter()
            .map(|a| TimelineAllocation {
                timestamp: a.timestamp_alloc,
                thread_id: a.thread_id.parse::<u64>().unwrap_or(0),
                size: a.size,
                var_name: Some(a.var_name.clone()),
            })
            .collect();

        serde_json::to_value(&timeline).map_err(|e| e.into())
    }

    /// Prepare conflict data for multithread dashboard
    fn prepare_conflict_data(
        &self,
        context: &DashboardContext,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut conflicts: Vec<ThreadConflict> = Vec::new();

        let mut address_map: std::collections::HashMap<String, Vec<&AllocationInfo>> =
            std::collections::HashMap::new();

        for allocation in &context.allocations {
            address_map
                .entry(allocation.address.clone())
                .or_default()
                .push(allocation);
        }

        for (address, allocations) in &address_map {
            if allocations.len() > 1 {
                let thread_ids: Vec<u64> = allocations
                    .iter()
                    .map(|a| a.thread_id.parse::<u64>().unwrap_or(0))
                    .collect();
                let unique_threads: std::collections::HashSet<u64> =
                    thread_ids.iter().cloned().collect();

                if unique_threads.len() > 1 {
                    conflicts.push(ThreadConflict {
                        description: format!(
                            "Address {} accessed by {} threads",
                            address,
                            unique_threads.len()
                        ),
                        threads: thread_ids
                            .iter()
                            .map(|t| t.to_string())
                            .collect::<Vec<_>>()
                            .join(", "),
                        conflict_type: "Data Race".to_string(),
                    });
                }
            }
        }

        serde_json::to_value(&conflicts).map_err(|e| e.into())
    }

    /// Build base async data map with common fields
    fn build_async_base_map(
        context: &DashboardContext,
        subtitle: &str,
    ) -> serde_json::Map<String, serde_json::Value> {
        let mut map = serde_json::Map::new();
        map.insert(
            "title".to_string(),
            serde_json::Value::String("Async Performance Dashboard".to_string()),
        );
        map.insert(
            "subtitle".to_string(),
            serde_json::Value::String(subtitle.to_string()),
        );
        map.insert(
            "total_tasks".to_string(),
            serde_json::Value::Number(context.allocations.len().into()),
        );
        map.insert(
            "active_tasks".to_string(),
            serde_json::Value::Number(context.active_allocations.into()),
        );
        map.insert(
            "completed_tasks".to_string(),
            serde_json::Value::Number(
                context
                    .allocations
                    .iter()
                    .filter(|a| a.timestamp_dealloc > 0)
                    .count()
                    .into(),
            ),
        );
        map.insert(
            "failed_tasks".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "cpu_usage_avg".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "cpu_usage_peak".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "cpu_cores".to_string(),
            serde_json::Value::Number(context.cpu_cores.into()),
        );
        map.insert(
            "context_switches".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "total_memory_mb".to_string(),
            serde_json::Value::Number(
                serde_json::Number::from_f64(Self::parse_bytes_to_mb(&context.total_memory))
                    .unwrap(),
            ),
        );
        map.insert(
            "peak_memory_mb".to_string(),
            serde_json::Value::Number(
                serde_json::Number::from_f64(Self::parse_bytes_to_mb(&context.peak_memory))
                    .unwrap(),
            ),
        );
        map.insert(
            "total_allocations".to_string(),
            serde_json::Value::Number(context.total_allocations.into()),
        );
        map.insert(
            "memory_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "io_throughput".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_read_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_write_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_io_ops".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "network_throughput".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_sent_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_received_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "avg_latency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "efficiency_score".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "resource_balance".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "bottleneck_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "optimization_potential".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "futures_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "total_polls".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "avg_poll_time".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "ready_rate".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "cpu_intensive_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "cpu_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "cpu_intensive_tasks".to_string(),
            serde_json::Value::Array(vec![]),
        );
        map.insert(
            "memory_intensive_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "memory_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "memory_intensive_tasks".to_string(),
            serde_json::Value::Array(vec![]),
        );
        map.insert(
            "io_intensive_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "io_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "io_intensive_tasks".to_string(),
            serde_json::Value::Array(vec![]),
        );
        map.insert(
            "network_intensive_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "network_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "network_intensive_tasks".to_string(),
            serde_json::Value::Array(vec![]),
        );
        map.insert(
            "executor_utilization".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "avg_queue_length".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "blocking_tasks_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "deadlock_risk".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "gc_pressure".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "avg_fragmentation".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "peak_alloc_rate".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "waker_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "immediate_ready_percent".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map
    }

    /// Parse bytes string to MB (helper function)
    fn parse_bytes_to_mb(bytes_str: &str) -> f64 {
        let num_str: String = bytes_str
            .chars()
            .filter(|c| c.is_ascii_digit() || *c == '.')
            .collect();
        let num: f64 = num_str.parse().unwrap_or(0.0);
        if bytes_str.contains("GB") {
            num * 1024.0
        } else if bytes_str.contains("MB") {
            num
        } else if bytes_str.contains("KB") {
            num / 1024.0
        } else {
            num / 1024.0 / 1024.0
        }
    }

    /// Render async template (legacy template)
    pub fn render_async_template(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let has_async_tasks = context.allocations.iter().any(|a| {
            a.type_name.contains("Future")
                || a.type_name.contains("Task")
                || a.type_name.contains("async")
                || a.type_name.contains("Waker")
        });

        let async_data = if has_async_tasks {
            self.prepare_async_data(context)?
        } else {
            serde_json::Value::Object(Self::build_async_base_map(
                context,
                "No async tasks detected",
            ))
        };

        let mut template_data = std::collections::BTreeMap::new();
        if let serde_json::Value::Object(map) = &async_data {
            for (key, value) in map {
                template_data.insert(key.clone(), value.clone());
            }
        }
        template_data.insert(
            "PROJECT_NAME".to_string(),
            serde_json::Value::String("MemScope Async Performance Analysis".to_string()),
        );

        self.handlebars
            .render("async_template", &template_data)
            .map_err(|e| format!("Template rendering error: {}", e).into())
    }

    /// Prepare async-specific data from context
    fn prepare_async_data(
        &self,
        context: &DashboardContext,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut cpu_intensive_tasks: Vec<serde_json::Value> = Vec::new();
        let mut memory_intensive_tasks: Vec<serde_json::Value> = Vec::new();
        let mut io_intensive_tasks: Vec<serde_json::Value> = Vec::new();
        let mut network_intensive_tasks: Vec<serde_json::Value> = Vec::new();

        for (idx, alloc) in context.allocations.iter().enumerate() {
            let task_type = if alloc.type_name.contains("Future") {
                "future"
            } else if alloc.type_name.contains("Task") {
                "task"
            } else if alloc.type_name.contains("Channel") {
                "channel"
            } else {
                "async_op"
            };

            let status = if alloc.is_leaked {
                "leaked"
            } else if alloc.timestamp_dealloc > 0 {
                "completed"
            } else {
                "active"
            };
            let mut task_map = serde_json::Map::new();
            task_map.insert("task_id".to_string(), serde_json::Value::Number(idx.into()));
            task_map.insert(
                "task_name".to_string(),
                serde_json::Value::String(if alloc.var_name.is_empty() {
                    format!("async_{}", idx)
                } else {
                    alloc.var_name.clone()
                }),
            );
            task_map.insert(
                "source_file".to_string(),
                serde_json::Value::String("unknown".to_string()),
            );
            task_map.insert(
                "source_line".to_string(),
                serde_json::Value::Number(0.into()),
            );
            task_map.insert(
                "task_type".to_string(),
                serde_json::Value::String(task_type.to_string()),
            );
            task_map.insert(
                "cpu_usage".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "cpu_cycles".to_string(),
                serde_json::Value::Number(0.into()),
            );
            task_map.insert(
                "instructions".to_string(),
                serde_json::Value::Number(0.into()),
            );
            task_map.insert(
                "cache_misses".to_string(),
                serde_json::Value::Number(0.into()),
            );
            task_map.insert(
                "allocated_mb".to_string(),
                serde_json::Value::Number(
                    serde_json::Number::from_f64(alloc.size as f64 / 1024.0 / 1024.0).unwrap(),
                ),
            );
            task_map.insert(
                "memory_usage_percent".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "peak_memory_mb".to_string(),
                serde_json::Value::Number(
                    serde_json::Number::from_f64(alloc.size as f64 / 1024.0 / 1024.0).unwrap(),
                ),
            );
            task_map.insert(
                "allocation_count".to_string(),
                serde_json::Value::Number(1.into()),
            );
            task_map.insert(
                "heap_fragmentation".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "bytes_read_mb".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "bytes_written_mb".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "avg_latency_us".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "queue_depth".to_string(),
                serde_json::Value::Number(0.into()),
            );
            task_map.insert(
                "bytes_sent_mb".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "bytes_received_mb".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "active_connections".to_string(),
                serde_json::Value::Number(0.into()),
            );
            task_map.insert(
                "avg_latency_ms".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
            );
            task_map.insert(
                "status".to_string(),
                serde_json::Value::String(status.to_string()),
            );
            task_map.insert(
                "duration_ms".to_string(),
                serde_json::Value::Number(serde_json::Number::from_f64(alloc.lifetime_ms).unwrap()),
            );
            let task_data = serde_json::Value::Object(task_map);

            if alloc.type_name.contains("Future") || alloc.type_name.contains("Stream") {
                cpu_intensive_tasks.push(task_data);
            } else if alloc.type_name.contains("Channel") || alloc.type_name.contains("Mutex") {
                memory_intensive_tasks.push(task_data);
            } else if alloc.type_name.contains("Tcp") || alloc.type_name.contains("Udp") {
                network_intensive_tasks.push(task_data);
            } else {
                io_intensive_tasks.push(task_data);
            }
        }

        let memory_efficiency = if context.total_allocations > 0 {
            context.active_allocations as f64 / context.total_allocations as f64 * 100.0
        } else {
            100.0
        };

        let mut map = serde_json::Map::new();
        map.insert(
            "title".to_string(),
            serde_json::Value::String("Async Performance Dashboard".to_string()),
        );
        map.insert(
            "subtitle".to_string(),
            serde_json::Value::String("Rust Async Runtime Analysis".to_string()),
        );
        map.insert(
            "total_tasks".to_string(),
            serde_json::Value::Number(context.allocations.len().into()),
        );
        map.insert(
            "active_tasks".to_string(),
            serde_json::Value::Number(context.active_allocations.into()),
        );
        map.insert(
            "completed_tasks".to_string(),
            serde_json::Value::Number(
                context
                    .allocations
                    .iter()
                    .filter(|a| a.timestamp_dealloc > 0)
                    .count()
                    .into(),
            ),
        );
        map.insert(
            "failed_tasks".to_string(),
            serde_json::Value::Number(context.leak_count.into()),
        );
        map.insert(
            "cpu_usage_avg".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "cpu_usage_peak".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "cpu_cores".to_string(),
            serde_json::Value::Number(context.cpu_cores.into()),
        );
        map.insert(
            "context_switches".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "total_memory_mb".to_string(),
            serde_json::Value::Number(
                serde_json::Number::from_f64(Self::parse_bytes_to_mb(&context.total_memory))
                    .unwrap(),
            ),
        );
        map.insert(
            "peak_memory_mb".to_string(),
            serde_json::Value::Number(
                serde_json::Number::from_f64(Self::parse_bytes_to_mb(&context.peak_memory))
                    .unwrap(),
            ),
        );
        map.insert(
            "total_allocations".to_string(),
            serde_json::Value::Number(context.total_allocations.into()),
        );
        map.insert(
            "memory_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(memory_efficiency).unwrap()),
        );
        map.insert(
            "io_throughput".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_read_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_write_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_io_ops".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "network_throughput".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_sent_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "total_received_mb".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "avg_latency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "efficiency_score".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "resource_balance".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "bottleneck_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "optimization_potential".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "futures_count".to_string(),
            serde_json::Value::Number(cpu_intensive_tasks.len().into()),
        );
        map.insert(
            "total_polls".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "avg_poll_time".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "ready_rate".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "cpu_intensive_count".to_string(),
            serde_json::Value::Number(cpu_intensive_tasks.len().into()),
        );
        map.insert(
            "cpu_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "cpu_intensive_tasks".to_string(),
            serde_json::Value::Array(cpu_intensive_tasks),
        );
        map.insert(
            "memory_intensive_count".to_string(),
            serde_json::Value::Number(memory_intensive_tasks.len().into()),
        );
        map.insert(
            "memory_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "memory_intensive_tasks".to_string(),
            serde_json::Value::Array(memory_intensive_tasks),
        );
        map.insert(
            "io_intensive_count".to_string(),
            serde_json::Value::Number(io_intensive_tasks.len().into()),
        );
        map.insert(
            "io_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "io_intensive_tasks".to_string(),
            serde_json::Value::Array(io_intensive_tasks),
        );
        map.insert(
            "network_intensive_count".to_string(),
            serde_json::Value::Number(network_intensive_tasks.len().into()),
        );
        map.insert(
            "network_avg_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "network_intensive_tasks".to_string(),
            serde_json::Value::Array(network_intensive_tasks),
        );
        map.insert(
            "executor_utilization".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "avg_queue_length".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "blocking_tasks_count".to_string(),
            serde_json::Value::Number(0.into()),
        );
        map.insert(
            "deadlock_risk".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "gc_pressure".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "avg_fragmentation".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "peak_alloc_rate".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.0).unwrap()),
        );
        map.insert(
            "waker_efficiency".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        map.insert(
            "immediate_ready_percent".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(100.0).unwrap()),
        );
        Ok(serde_json::Value::Object(map))
    }

    /// Convert new DashboardContext to legacy binary data format
    fn to_legacy_binary_data(&self, context: &DashboardContext) -> serde_json::Value {
        // Calculate type distribution
        let mut type_counts: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();
        let mut total_size: usize = 0;

        for alloc in &context.allocations {
            let type_name =
                if alloc.type_name.contains("Vec") || alloc.type_name.contains("vec::Vec") {
                    "dynamic_array"
                } else if alloc.type_name.contains("String") || alloc.type_name.contains("str") {
                    "string"
                } else if alloc.type_name.contains("Box")
                    || alloc.type_name.contains("Rc")
                    || alloc.type_name.contains("Arc")
                {
                    "smart_pointer"
                } else if alloc.type_name.contains("[") && alloc.type_name.contains("u8") {
                    "byte_array"
                } else if alloc.size > 1024 * 1024 {
                    "large_buffer"
                } else {
                    "custom"
                }
                .to_string();

            *type_counts.entry(type_name).or_insert(0) += 1;
            total_size += alloc.size;
        }

        // Calculate statistics
        let average_size = if context.allocations.is_empty() {
            0
        } else {
            total_size / context.allocations.len()
        };

        // Build lifetime events from allocations
        let lifetime_events: Vec<serde_json::Value> = context.allocations.iter().map(|a| {
            serde_json::json!({
                "address": a.address,
                "events": [{
                    "context": "initial_allocation",
                    "event_type": "Created",
                    "timestamp": a.timestamp_alloc
                }],
                "lifetime_ms": a.lifetime_ms,
                "size": a.size,
                "timestamp_alloc": a.timestamp_alloc,
                "timestamp_dealloc": if a.timestamp_dealloc > 0 { Some(a.timestamp_dealloc) } else { None },
                "type_name": a.type_name,
                "var_name": a.var_name
            })
        }).collect();

        serde_json::json!({
            "memory_analysis": {
                "allocations": context.allocations.iter().map(|a| {
                    serde_json::json!({
                        "var_name": a.var_name,
                        "type_name": a.type_name,
                        "size": a.size,
                        "address": a.address,
                        "timestamp": a.timestamp,
                        "timestamp_alloc": a.timestamp_alloc,
                        "timestamp_dealloc": if a.timestamp_dealloc > 0 { Some(a.timestamp_dealloc) } else { None },
                        "lifetime_ms": a.lifetime_ms,
                        "is_leaked": a.is_leaked,
                        "thread_id": a.thread_id,
                        "immutable_borrows": a.immutable_borrows,
                        "mutable_borrows": a.mutable_borrows,
                        "is_clone": a.is_clone,
                        "clone_count": a.clone_count,
                        "allocation_type": a.allocation_type,
                        "is_smart_pointer": a.is_smart_pointer,
                        "smart_pointer_type": a.smart_pointer_type,
                        "borrow_info": {
                            "immutable_borrows": a.immutable_borrows,
                            "max_concurrent_borrows": a.immutable_borrows + a.mutable_borrows,
                            "mutable_borrows": a.mutable_borrows
                        },
                        "clone_info": {
                            "clone_count": a.clone_count,
                            "is_clone": a.is_clone,
                            "original_ptr": null
                        },
                        "ownership_history_available": false,
                        "type": if a.type_name.contains("Vec") || a.type_name.contains("vec::Vec") {
                            "dynamic_array"
                        } else if a.type_name.contains("String") || a.type_name.contains("str") {
                            "string"
                        } else if a.type_name.contains("Box") || a.type_name.contains("Rc") || a.type_name.contains("Arc") {
                            "smart_pointer"
                        } else {
                            "custom"
                        }
                    })
                }).collect::<Vec<_>>(),
                "metadata": {
                    "export_timestamp": context.export_timestamp,
                    "export_version": "2.0",
                    "specification": "memscope-rs memory analysis",
                    "total_allocations": context.allocations.len(),
                    "total_size_bytes": total_size
                },
                "statistics": {
                    "average_size_bytes": average_size,
                    "total_allocations": context.allocations.len(),
                    "total_size_bytes": total_size
                },
                "type_distribution": type_counts
            },
            "lifetime": {
                "metadata": {
                    "export_timestamp": context.export_timestamp,
                    "export_version": "2.0",
                    "specification": "memscope-rs lifetime tracking",
                    "total_tracked_allocations": context.allocations.len()
                },
                "ownership_histories": lifetime_events
            },
            "complex_types": {
                "smart_pointers": context.allocations.iter().filter(|a| a.is_smart_pointer).count(),
                "collections": context.allocations.iter().filter(|a| {
                    a.type_name.contains("Vec") || a.type_name.contains("HashMap") || a.type_name.contains("BTreeMap")
                }).count()
            },
            "unsafe_ffi": {
                "passports": context.passport_details,
                "reports": context.unsafe_reports,
                "cross_boundary_events": context.unsafe_reports.iter()
                    .flat_map(|r| r.cross_boundary_events.iter())
                    .count()
            },
            "performance": {
                "total_memory": context.total_memory,
                "peak_memory": context.peak_memory,
                "total_allocations": context.total_allocations,
                "active_allocations": context.active_allocations,
                "thread_count": context.thread_count,
                "passport_count": context.passport_count,
                "leak_count": context.leak_count,
                "unsafe_count": context.unsafe_count,
                "ffi_count": context.ffi_count
            },
            "system_resources": {
                "os_name": context.os_name,
                "architecture": context.architecture,
                "cpu_cores": context.cpu_cores,
                "system_info": context.system_resources
            },
            "threads": context.threads
        })
    }
}

/// Format thread_id from "ThreadId(5)" to "Thread-5"
fn format_thread_id(raw: &str) -> String {
    if raw.starts_with("ThreadId(") && raw.ends_with(')') {
        let num = &raw[9..raw.len() - 1];
        format!("Thread-{}", num)
    } else {
        raw.to_string()
    }
}

/// Format bytes to human-readable string
fn format_bytes(bytes: usize) -> String {
    const KB: usize = 1024;
    const MB: usize = KB * 1024;
    const GB: usize = MB * 1024;
    const TB: usize = GB * 1024;
    const PB: usize = TB * 1024;

    if bytes >= PB {
        format!("{:.2} PB", bytes as f64 / PB as f64)
    } else if bytes >= TB {
        format!("{:.2} TB", bytes as f64 / TB as f64)
    } else if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} bytes", bytes)
    }
}

// Custom Handlebars helpers
fn format_bytes_helper(
    h: &handlebars::Helper,
    _: &handlebars::Handlebars,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    let param = h.param(0).unwrap().value();
    if let Some(bytes) = param.as_u64() {
        let formatted = format_bytes(bytes as usize);
        out.write(&formatted)?;
    }
    Ok(())
}

fn greater_than_helper(
    h: &handlebars::Helper,
    _: &handlebars::Handlebars,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    let param1 = h.param(0).unwrap().value();
    let param2 = h.param(1).unwrap().value();

    if let (Some(v1), Some(v2)) = (param1.as_u64(), param2.as_u64()) {
        if v1 > v2 {
            out.write("true")?;
        }
    }
    Ok(())
}

fn contains_helper(
    h: &handlebars::Helper,
    _: &handlebars::Handlebars,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    let haystack = h.param(0).unwrap().value();
    let needle = h.param(1).unwrap().value();

    if let (Some(h_str), Some(n_str)) = (haystack.as_str(), needle.as_str()) {
        if h_str.contains(n_str) {
            out.write("true")?;
        }
    }
    Ok(())
}

fn json_helper(
    h: &handlebars::Helper,
    _: &handlebars::Handlebars,
    _: &handlebars::Context,
    _: &mut handlebars::RenderContext,
    out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
    let param = h.param(0).unwrap().value();
    let json_string = serde_json::to_string(param).map_err(|e| {
        handlebars::RenderErrorReason::Other(format!("Failed to serialize to JSON: {}", e))
    })?;
    out.write(&json_string)?;
    Ok(())
}

impl Default for DashboardRenderer {
    fn default() -> Self {
        Self::new().expect("Failed to create dashboard renderer")
    }
}