profile-inspect 0.1.3

Analyze V8 CPU and heap profiles from Node.js/Chrome DevTools
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
use std::io::Write;

use crate::analysis::{
    AllocationStats, CpuAnalysis, HeapAnalysis, HotFunctionDetail, HotPath, Priority,
    Recommendation, RecommendationEngine,
};
use crate::ir::{FrameCategory, FrameKind, ProfileIR};

use super::{Formatter, OutputError, format_time_ms, format_time_us};

/// Markdown output formatter (default, LLM-optimized)
pub struct MarkdownFormatter;

impl Formatter for MarkdownFormatter {
    #[expect(clippy::cast_precision_loss)]
    #[expect(clippy::too_many_lines)]
    fn write_cpu_analysis(
        &self,
        profile: &ProfileIR,
        analysis: &CpuAnalysis,
        writer: &mut dyn Write,
    ) -> Result<(), OutputError> {
        // ==================== HEADER ====================
        if let Some(ref pkg) = analysis.metadata.focus_package {
            writeln!(writer, "# Profile Inspect Report — CPU (Package: `{pkg}`)")?;
        } else {
            writeln!(writer, "# Profile Inspect Report — CPU")?;
        }
        writeln!(writer)?;

        // Profile metadata
        if let Some(ref source) = analysis.metadata.source_file {
            if analysis.metadata.profiles_merged > 1 {
                writeln!(
                    writer,
                    "**Profile:** `{source}` ({} profiles merged)",
                    analysis.metadata.profiles_merged
                )?;
            } else {
                writeln!(writer, "**Profile:** `{source}`")?;
            }
        }

        let internals_str = if analysis.metadata.internals_filtered {
            "hidden"
        } else {
            "shown"
        };
        let sourcemaps_total =
            analysis.metadata.sourcemaps_loaded + analysis.metadata.sourcemaps_inline;
        let sourcemaps_str = if sourcemaps_total > 0 {
            if analysis.metadata.sourcemaps_inline > 0 && analysis.metadata.sourcemaps_loaded > 0 {
                format!(
                    "{} frames resolved ({} inline)",
                    sourcemaps_total, analysis.metadata.sourcemaps_inline
                )
            } else if analysis.metadata.sourcemaps_inline > 0 {
                format!("{} frames resolved (inline)", sourcemaps_total)
            } else {
                format!("{} frames resolved", sourcemaps_total)
            }
        } else {
            "OFF".to_string()
        };

        let cpu_time_str = format_time_ms(analysis.metadata.duration_ms);

        // Show wall time and CPU utilization if available
        if let Some(wall_ms) = analysis.metadata.wall_time_ms {
            let wall_str = format_time_ms(wall_ms);
            let util = analysis.metadata.cpu_utilization().unwrap_or(0.0);
            let util_pct = util * 100.0;

            // Add caveat for merged profiles where CPU utilization can be misleading
            let util_note = if analysis.metadata.profiles_merged > 1 {
                " (aggregated)"
            } else {
                ""
            };

            writeln!(
                writer,
                "**Wall time:** {} | **CPU time:** {} | **CPU utilization:** ~{:.0}%{}",
                wall_str, cpu_time_str, util_pct, util_note
            )?;
            writeln!(
                writer,
                "**Samples:** {} | **Interval:** ~{:.2} ms",
                analysis.metadata.sample_count, analysis.metadata.sample_interval_ms
            )?;

            // Workload classification based on CPU utilization
            let workload_class =
                Self::classify_workload(util_pct, analysis.metadata.profiles_merged);
            writeln!(writer, "**Workload:** {}", workload_class)?;

            // Quick "where CPU goes" summary
            let breakdown = &analysis.category_breakdown;
            let total = breakdown.total();
            if total > 0 {
                let top_category = Self::top_category_summary(breakdown, total);
                writeln!(writer, "**Top category (self time):** {}", top_category)?;
            }

            // Add insight about CPU utilization for edge cases
            if analysis.metadata.profiles_merged > 1 && util_pct > 100.0 {
                writeln!(writer)?;
                writeln!(
                    writer,
                    "> ℹ️ CPU utilization exceeds 100% because {} profiles were merged (multiple processes running in parallel).",
                    analysis.metadata.profiles_merged
                )?;
            }
        } else {
            writeln!(
                writer,
                "**Duration:** {} | **Samples:** {} | **Interval:** ~{:.2} ms",
                cpu_time_str, analysis.metadata.sample_count, analysis.metadata.sample_interval_ms
            )?;
        }

        if let Some(ref pkg) = analysis.metadata.focus_package {
            writeln!(writer, "**Package filter:** `{pkg}`")?;
        } else {
            writeln!(
                writer,
                "**Node/V8 internals:** {internals_str} | **Sourcemaps:** {sourcemaps_str}"
            )?;
        }

        if let Some(scope_line) = Self::scope_line(&analysis.metadata) {
            writeln!(writer, "{scope_line}")?;
        }

        let quality_notes = Self::profile_quality_notes(&analysis.metadata);
        if !quality_notes.is_empty() {
            for note in quality_notes {
                writeln!(writer, "> ℹ️ {note}")?;
            }
        }

        // Explain merged profiles
        if analysis.metadata.profiles_merged > 1 {
            writeln!(writer)?;
            writeln!(
                writer,
                "> **Note:** {} profiles were merged. This happens when Node.js spawns multiple processes",
                analysis.metadata.profiles_merged
            )?;
            writeln!(
                writer,
                "> (e.g., `npx` launching your script, worker threads, or child processes)."
            )?;
            writeln!(
                writer,
                "> Each process generates its own `.cpuprofile` file."
            )?;
        }

        writeln!(writer)?;
        writeln!(writer, "---")?;
        writeln!(writer)?;

        // ==================== TL;DR ====================
        Self::write_tldr(writer, profile, analysis)?;

        // ==================== EXECUTIVE SUMMARY ====================
        if Self::has_filters(&analysis.metadata) {
            writeln!(writer, "## Executive Summary (Full Profile)")?;
            writeln!(writer)?;
            writeln!(
                writer,
                "> **Scope note:** Function tables, hot paths, and recommendations honor filters. Category totals below reflect the full profile."
            )?;
            writeln!(writer)?;
        } else {
            writeln!(writer, "## Executive Summary")?;
            writeln!(writer)?;
        }
        writeln!(writer, "| Category | Self | % | Stack | % | Assessment |")?;
        writeln!(
            writer,
            "|----------|-----------|---|-----------|---|------------|"
        )?;

        let breakdown = &analysis.category_breakdown;
        let inclusive = &analysis.category_breakdown_inclusive;
        let total = breakdown.total();

        Self::write_summary_row_with_inclusive(
            writer,
            "App code",
            breakdown.app,
            inclusive.app,
            total,
        )?;
        Self::write_summary_row_with_inclusive(
            writer,
            "Dependencies",
            breakdown.deps,
            inclusive.deps,
            total,
        )?;
        Self::write_summary_row_with_inclusive(
            writer,
            "Node.js internals",
            breakdown.node_internal,
            inclusive.node_internal,
            total,
        )?;
        Self::write_summary_row_with_inclusive(
            writer,
            "V8/Native",
            breakdown.v8_internal + breakdown.native,
            inclusive.v8_internal + inclusive.native,
            total,
        )?;
        writeln!(writer)?;

        // Explain the columns
        writeln!(
            writer,
            "> **Self:** CPU time spent directly executing this category's code (exclusive, sums to 100%)."
        )?;
        writeln!(
            writer,
            "> **Stack:** CPU time when this category appears anywhere in the call stack (inclusive)."
        )?;
        writeln!(
            writer,
            "> Stack percentages can exceed 100% because categories overlap (e.g., App calls Deps)."
        )?;
        writeln!(writer)?;

        // Key takeaways
        writeln!(writer, "**Key takeaways:**")?;
        Self::write_key_takeaways(writer, analysis)?;
        writeln!(writer)?;
        writeln!(writer, "---")?;
        writeln!(writer)?;

        // ==================== PHASE ANALYSIS ====================
        if let Some(ref phases) = analysis.phase_analysis {
            Self::write_phase_analysis(writer, phases)?;
        }

        // ==================== TOP HOTSPOTS BY SELF TIME ====================
        writeln!(writer, "## Top Hotspots by Self Time")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "> Self time = CPU time spent directly in this function."
        )?;
        writeln!(writer)?;
        writeln!(
            writer,
            "| # | Self | % | Samples | Total | Function | Location | Category |"
        )?;
        writeln!(
            writer,
            "|---|------|---|---------|-------|----------|----------|----------|"
        )?;

        for (i, func) in analysis.functions.iter().take(25).enumerate() {
            let self_time = format_time_us(func.self_time);
            let self_pct = func.self_percent(analysis.total_time);
            let total_time = format_time_us(func.total_time);
            let category_badge = Self::category_badge(func.category);

            writeln!(
                writer,
                "| {} | {} | {} | {} | {} | `{}` | `{}` | {} |",
                i + 1,
                self_time,
                Self::format_percent(self_pct),
                func.self_samples,
                total_time,
                Self::escape_markdown(&func.name),
                Self::format_location(&func.location),
                category_badge
            )?;
        }
        writeln!(writer)?;

        // ==================== TOP HOTSPOTS BY TOTAL TIME ====================
        writeln!(writer, "## Top Hotspots by Total Time")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "> Total time = CPU time when this function is on the stack (including callees)."
        )?;
        writeln!(writer)?;
        writeln!(
            writer,
            "| # | Total | % | Self | Function | Location | Category |"
        )?;
        writeln!(
            writer,
            "|---|-------|---|------|----------|----------|----------|"
        )?;

        for (i, func) in analysis.functions_by_total.iter().take(15).enumerate() {
            let self_time = format_time_us(func.self_time);
            let total_time = format_time_us(func.total_time);
            let total_pct = func.total_percent(analysis.total_time);
            let category_badge = Self::category_badge(func.category);

            writeln!(
                writer,
                "| {} | {} | {} | {} | `{}` | `{}` | {} |",
                i + 1,
                total_time,
                Self::format_percent(total_pct),
                self_time,
                Self::escape_markdown(&func.name),
                Self::format_location(&func.location),
                category_badge
            )?;
        }
        writeln!(writer)?;

        // ==================== HOT PATHS ====================
        if !analysis.hot_paths.is_empty() {
            writeln!(writer, "## Hot Paths")?;
            writeln!(writer)?;
            writeln!(writer, "> Sorted by CPU time descending.")?;
            writeln!(writer)?;
            let mut significant_paths: Vec<&HotPath> = analysis
                .hot_paths
                .iter()
                .filter(|path| {
                    path.percent >= 0.2 || path.time >= 10_000 || path.sample_count >= 10
                })
                .collect();

            if significant_paths.is_empty() {
                significant_paths = analysis.hot_paths.iter().take(1).collect();
            }

            for (i, path) in significant_paths.iter().take(5).enumerate() {
                let cpu_time_str = format_time_us(path.time);
                let path_pct = Self::format_percent(path.percent);
                let low_signal = path.percent < 0.1 || path.sample_count < 10;
                let signal_note = if low_signal { " — low signal" } else { "" };

                writeln!(
                    writer,
                    "### Path #{}{} ({}, {} samples){}",
                    i + 1,
                    path_pct,
                    cpu_time_str,
                    path.sample_count,
                    signal_note
                )?;
                writeln!(writer)?;
                writeln!(writer, "```")?;
                Self::write_hot_path_visualization(writer, profile, path)?;
                writeln!(writer, "```")?;
                writeln!(writer)?;

                // Why this path is hot
                Self::write_path_explanation(writer, profile, path, analysis)?;
                writeln!(writer)?;
            }
        }

        // ==================== CALLER/CALLEE ATTRIBUTION ====================
        if !analysis.hot_function_details.is_empty() {
            writeln!(writer, "## Caller & Callee Attribution")?;
            writeln!(writer)?;

            for detail in &analysis.hot_function_details {
                Self::write_hot_function_detail(writer, detail, analysis)?;
            }
        }

        // ==================== RECURSIVE FUNCTIONS ====================
        if !analysis.recursive_functions.is_empty() {
            Self::write_recursive_functions(writer, analysis)?;
        }

        // ==================== BY SOURCE FILE ====================
        if !analysis.file_stats.is_empty() {
            if analysis.metadata.focus_package.is_some() {
                writeln!(writer, "## By Source File")?;
                writeln!(writer)?;
                writeln!(
                    writer,
                    "> Omitted under package filter — file stats are computed from the full profile."
                )?;
                writeln!(writer)?;
            } else {
                let file_stats: Vec<_> = analysis
                    .file_stats
                    .iter()
                    .filter(|fs| Self::category_allowed(&analysis.metadata, fs.category))
                    .collect();

                if !file_stats.is_empty() {
                    writeln!(writer, "## By Source File")?;
                    writeln!(writer)?;
                    writeln!(writer, "| File | Self | Total | Samples | Category |")?;
                    writeln!(writer, "|------|------|-------|---------|----------|")?;

                    for fs in file_stats.iter().take(15) {
                        let self_time = format_time_us(fs.self_time);
                        let total_time = format_time_us(fs.total_time);
                        let category_badge = Self::category_badge(fs.category);

                        writeln!(
                            writer,
                            "| `{}` | {} | {} | {} | {} |",
                            Self::format_location(&fs.file),
                            self_time,
                            total_time,
                            fs.call_count,
                            category_badge
                        )?;
                    }
                    writeln!(writer)?;
                }
            }
        }

        // ==================== BY DEPENDENCY PACKAGE ====================
        let show_package_stats = analysis.metadata.focus_package.is_none()
            && (analysis.metadata.filter_categories.is_empty()
                || analysis
                    .metadata
                    .filter_categories
                    .contains(&FrameCategory::Deps));

        if !analysis.package_stats.is_empty() && show_package_stats {
            writeln!(writer, "## By Dependency Package")?;
            writeln!(writer)?;
            writeln!(writer, "| Package | Time | % of Deps | Top Function |")?;
            writeln!(writer, "|---------|------|-----------|--------------|")?;

            for pkg in &analysis.package_stats {
                let time_str = format_time_us(pkg.time);
                writeln!(
                    writer,
                    "| `{}` | {} | {:.1}% | `{}` |",
                    pkg.package,
                    time_str,
                    pkg.percent_of_deps,
                    Self::escape_markdown(&pkg.top_function)
                )?;
            }
            writeln!(writer)?;
        }

        // ==================== NATIVE/RUNTIME TIME ====================
        if analysis.native_time > 0 {
            writeln!(writer, "## Native/Runtime Frames (Leaf)")?;
            writeln!(writer)?;
            writeln!(
                writer,
                "> Time in frames explicitly marked `Native` (leaf frames only)."
            )?;
            writeln!(
                writer,
                "> V8/Node JS internals still appear in the category breakdown above."
            )?;
            writeln!(writer)?;

            let native_time = format_time_us(analysis.native_time);
            let native_pct = if analysis.total_time > 0 {
                (analysis.native_time as f64 / analysis.total_time as f64) * 100.0
            } else {
                0.0
            };

            writeln!(writer, "**Total:** {} ({:.1}%)", native_time, native_pct)?;
            writeln!(writer)?;

            // List visible native frames if any
            let native_entries: Vec<_> = analysis
                .functions
                .iter()
                .filter(|f| {
                    profile
                        .get_frame(f.frame_id)
                        .is_some_and(|frame| frame.kind == FrameKind::Native)
                })
                .take(5)
                .collect();

            if !native_entries.is_empty() {
                writeln!(writer, "**Visible native frames:**")?;
                for func in native_entries {
                    let time_str = format_time_us(func.self_time);
                    writeln!(writer, "- `{}` — {}", func.name, time_str)?;
                }
                writeln!(writer)?;
            }

            writeln!(writer, "**What this means:**")?;
            writeln!(
                writer,
                "- This time is spent in compiled code (V8/Node native internals, syscalls, or addons)"
            )?;
            writeln!(
                writer,
                "- To attribute to specific libraries, capture a native profile (Instruments/perf)"
            )?;
            writeln!(
                writer,
                "- Focus optimization on reducing how often your JS code triggers native operations"
            )?;
            writeln!(writer)?;
        }

        // ==================== GC & ALLOCATION SIGNALS ====================
        if let Some(ref gc) = analysis.gc_analysis {
            Self::write_gc_analysis(
                writer,
                gc,
                analysis.total_time,
                analysis.phase_analysis.as_ref(),
            )?;
        } else if analysis.gc_time > 0 {
            // Fallback for basic GC time (shouldn't happen with new code)
            writeln!(writer, "## GC & Allocation Signals")?;
            writeln!(writer)?;
            let gc_time = format_time_us(analysis.gc_time);
            let gc_pct = (analysis.gc_time as f64 / analysis.total_time as f64) * 100.0;
            writeln!(writer, "**GC time:** {} ({:.1}%)", gc_time, gc_pct)?;
            writeln!(writer)?;
        }

        // ==================== ACTION ITEMS ====================
        Self::write_recommendations(writer, profile, analysis)?;

        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_heap_analysis(
        &self,
        profile: &ProfileIR,
        analysis: &HeapAnalysis,
        writer: &mut dyn Write,
    ) -> Result<(), OutputError> {
        // Header
        writeln!(writer, "# Profile Inspect Report — Heap")?;
        writeln!(writer)?;

        if let Some(ref source) = profile.source_file {
            writeln!(writer, "**Profile:** `{source}`")?;
        }

        writeln!(
            writer,
            "**Total allocated:** {} | **Allocations:** {}",
            AllocationStats::format_size(analysis.total_size),
            analysis.total_allocations
        )?;
        writeln!(writer)?;
        writeln!(writer, "---")?;
        writeln!(writer)?;

        // Category breakdown
        writeln!(writer, "## Allocation by Category")?;
        writeln!(writer)?;
        writeln!(writer, "| Category | Size | % |")?;
        writeln!(writer, "|----------|------|---|")?;

        let breakdown = &analysis.category_breakdown;
        let total = breakdown.total();

        Self::write_heap_category_row(writer, "App code", breakdown.app, total)?;
        Self::write_heap_category_row(writer, "Dependencies", breakdown.deps, total)?;
        Self::write_heap_category_row(writer, "Node.js internals", breakdown.node_internal, total)?;
        Self::write_heap_category_row(
            writer,
            "V8/Native",
            breakdown.v8_internal + breakdown.native,
            total,
        )?;
        writeln!(writer)?;

        // Top allocations
        writeln!(writer, "## Top Allocations by Size")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "| # | Self | % | Allocs | Total | Function | Location | Category |"
        )?;
        writeln!(
            writer,
            "|---|------|---|--------|-----------|----------|----------|----------|"
        )?;

        for (i, func) in analysis.functions.iter().enumerate() {
            let self_pct = func.self_percent(analysis.total_size);
            let self_str = AllocationStats::format_size(func.self_size);
            let total_str = AllocationStats::format_size(func.total_size);
            let category = Self::category_badge(func.category);

            writeln!(
                writer,
                "| {} | {} | {:.1}% | {} | {} | `{}` | `{}` | {} |",
                i + 1,
                self_str,
                self_pct,
                func.allocation_count,
                total_str,
                Self::escape_markdown(&func.name),
                Self::escape_markdown(&func.location),
                category
            )?;
        }
        writeln!(writer)?;

        // Recommendations
        writeln!(writer, "## Recommendations")?;
        writeln!(writer)?;

        let large_allocators: Vec<_> = analysis
            .functions
            .iter()
            .filter(|f| f.self_percent(analysis.total_size) >= 10.0)
            .collect();

        if !large_allocators.is_empty() {
            writeln!(writer, "**Large allocators (>=10% of total):**")?;
            writeln!(writer)?;
            for func in &large_allocators {
                let pct = func.self_percent(analysis.total_size);
                writeln!(
                    writer,
                    "- `{}` — {:.1}% ({})",
                    func.name,
                    pct,
                    AllocationStats::format_size(func.self_size)
                )?;
            }
        } else {
            writeln!(writer, "No single function dominates allocations.")?;
            writeln!(writer)?;
            writeln!(writer, "Memory is well-distributed across the codebase.")?;
        }

        Ok(())
    }
}

impl MarkdownFormatter {
    /// Write TL;DR section - quick assessment for humans and agents
    #[expect(clippy::cast_precision_loss)]
    fn write_tldr(
        writer: &mut dyn Write,
        _profile: &ProfileIR,
        analysis: &CpuAnalysis,
    ) -> Result<(), OutputError> {
        writeln!(writer, "## Quick Assessment")?;
        writeln!(writer)?;

        let filters = &analysis.metadata.filter_categories;
        let has_filter = !filters.is_empty();

        // Show filter notice if active
        if has_filter {
            let filter_names = Self::format_category_list(filters);
            writeln!(
                writer,
                "> **Filter active:** Function lists, hot paths, and recommendations show only {} categories",
                filter_names
            )?;
            writeln!(writer)?;
        }

        let breakdown = &analysis.category_breakdown;
        let total = breakdown.total();

        // Calculate percentages (relative to full profile)
        let app_pct = if total > 0 {
            (breakdown.app as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        let deps_pct = if total > 0 {
            (breakdown.deps as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        let internal_pct = if total > 0 {
            ((breakdown.v8_internal + breakdown.native + breakdown.node_internal) as f64
                / total as f64)
                * 100.0
        } else {
            0.0
        };

        let visible_total = Self::visible_total_time(analysis);
        let show_filtered_pct = has_filter
            || analysis.metadata.internals_filtered
            || analysis.metadata.focus_package.is_some();

        // Generate verdict (uses filtered functions for top bottleneck)
        let verdict = Self::generate_verdict(app_pct, deps_pct, internal_pct, analysis);
        writeln!(writer, "**{}**", verdict)?;
        writeln!(writer)?;

        // Quick breakdown table - show only filtered categories if filter is active
        writeln!(writer, "| Category | Time | Status |")?;
        writeln!(writer, "|----------|------|--------|")?;

        let show_app = !has_filter || filters.contains(&FrameCategory::App);
        let show_deps = !has_filter || filters.contains(&FrameCategory::Deps);
        let show_internal = !has_filter
            || filters.contains(&FrameCategory::NodeInternal)
            || filters.contains(&FrameCategory::V8Internal)
            || filters.contains(&FrameCategory::Native);

        let format_pct_label = |value: u64| -> String {
            let pct_total = if total > 0 {
                (value as f64 / total as f64) * 100.0
            } else {
                0.0
            };
            if show_filtered_pct {
                if let Some(filtered_total) = visible_total {
                    if filtered_total > 0 && filtered_total != total {
                        let pct_filtered = (value as f64 / filtered_total as f64) * 100.0;
                        return format!("{:.0}% total; {:.0}% filtered", pct_total, pct_filtered);
                    }
                }
            }
            format!("{:.0}%", pct_total)
        };

        if show_app {
            let app_status = if app_pct > 50.0 {
                "⚠️ Focus here"
            } else if app_pct > 20.0 {
                "👀 Worth checking"
            } else {
                "✅ Healthy"
            };
            writeln!(
                writer,
                "| App code | {} ({}) | {} |",
                format_time_us(breakdown.app),
                format_pct_label(breakdown.app),
                app_status
            )?;
        }

        if show_deps {
            let deps_status = if deps_pct > 40.0 {
                "⚠️ Heavy deps"
            } else if deps_pct > 20.0 {
                "👀 Review usage"
            } else {
                "✅ Normal"
            };
            writeln!(
                writer,
                "| Dependencies | {} ({}) | {} |",
                format_time_us(breakdown.deps),
                format_pct_label(breakdown.deps),
                deps_status
            )?;
        }

        if show_internal {
            let internal_status = if internal_pct > 70.0 {
                "ℹ️ Startup overhead"
            } else {
                "✅ Normal"
            };
            writeln!(
                writer,
                "| V8/Node internals | {} ({}) | {} |",
                format_time_us(breakdown.v8_internal + breakdown.native + breakdown.node_internal),
                format_pct_label(
                    breakdown.v8_internal + breakdown.native + breakdown.node_internal
                ),
                internal_status
            )?;
        }
        writeln!(writer)?;

        // Top function with impact assessment
        if let Some(top) = analysis.functions.first() {
            let top_pct = top.self_percent(analysis.total_time);

            // Only call it a "bottleneck" if it's significant (>= 2%)
            if top_pct >= 2.0 {
                let potential_savings = top.self_time / 2; // Assume 50% optimization
                let potential_pct = if analysis.total_time > 0 {
                    (potential_savings as f64 / analysis.total_time as f64) * 100.0
                } else {
                    0.0
                };

                writeln!(writer, "**Top hotspot:** `{}` at {:.1}%", top.name, top_pct)?;

                if top_pct >= 5.0 {
                    writeln!(
                        writer,
                        "**If optimized 50%:** Save {} ({:.1}% faster)",
                        format_time_us(potential_savings),
                        potential_pct
                    )?;
                }

                // Add context about the hotspot
                match top.category {
                    FrameCategory::Deps => {
                        // Try to extract package name from location
                        let pkg_hint = Self::extract_package_name(&top.location);
                        writeln!(
                            writer,
                            "**Note:** This is dependency code{}. Check if it's necessary or can be optimized.",
                            pkg_hint.map_or(String::new(), |p| format!(" ({})", p))
                        )?;
                    }
                    FrameCategory::App => {
                        writeln!(
                            writer,
                            "**Location:** `{}`",
                            Self::format_location(&top.location)
                        )?;
                    }
                    FrameCategory::NodeInternal
                    | FrameCategory::V8Internal
                    | FrameCategory::Native => {
                        writeln!(
                            writer,
                            "**Note:** This is runtime/engine code. Focus on what triggers it from your code."
                        )?;
                    }
                }
            } else {
                // Low impact - don't call it a bottleneck
                writeln!(
                    writer,
                    "**Top function:** `{}` at {:.1}% (low impact — no dominant CPU hotspot)",
                    top.name, top_pct
                )?;
            }
        }

        // Hotspot concentration (top N share)
        if !analysis.functions.is_empty() && analysis.total_time > 0 {
            let top_n = 5usize.min(analysis.functions.len());
            let top_sum: u64 = analysis
                .functions
                .iter()
                .take(top_n)
                .map(|f| f.self_time)
                .sum();
            let total_pct = (top_sum as f64 / analysis.total_time as f64) * 100.0;
            let (scope_pct, scope_label) = if let Some(filtered_total) = visible_total {
                if filtered_total > 0 && filtered_total != total {
                    let filtered_pct = (top_sum as f64 / filtered_total as f64) * 100.0;
                    (filtered_pct, "filtered")
                } else {
                    (total_pct, "total")
                }
            } else {
                (total_pct, "total")
            };
            let concentration = if scope_pct < 10.0 {
                "very flat"
            } else if scope_pct < 25.0 {
                "moderately flat"
            } else {
                "concentrated"
            };

            if scope_label == "filtered" {
                writeln!(
                    writer,
                    "**Hotspot concentration:** Top {top_n} functions = {:.1}% of filtered ({total_pct:.1}% of total) — {concentration}",
                    scope_pct
                )?;
            } else {
                writeln!(
                    writer,
                    "**Hotspot concentration:** Top {top_n} functions = {:.1}% of total — {concentration}",
                    scope_pct
                )?;
            }
        }

        writeln!(writer)?;
        writeln!(writer, "---")?;
        writeln!(writer)?;

        Ok(())
    }

    /// Generate a verdict based on category breakdown
    fn generate_verdict(
        app_pct: f64,
        deps_pct: f64,
        internal_pct: f64,
        analysis: &CpuAnalysis,
    ) -> String {
        // Check GC pressure first
        if let Some(gc) = &analysis.gc_analysis {
            let gc_pct = if analysis.total_time > 0 {
                (gc.total_time as f64 / analysis.total_time as f64) * 100.0
            } else {
                0.0
            };
            if gc_pct > 10.0 {
                return format!(
                    "🔴 High GC pressure ({:.0}%) — reduce allocations to improve performance",
                    gc_pct
                );
            }
        }

        // Check for dominant app code
        if app_pct > 50.0 {
            if let Some(top) = analysis.functions.first() {
                if top.self_percent(analysis.total_time) > 20.0 {
                    return format!(
                        "🔴 Single function dominates — `{}` uses {:.0}% of CPU",
                        top.name,
                        top.self_percent(analysis.total_time)
                    );
                }
            }
            return "🟡 App code dominates — optimization opportunities exist".to_string();
        }

        // Check for heavy dependencies
        if deps_pct > 40.0 {
            return "🟡 Heavy dependency usage — review if all are necessary".to_string();
        }

        // Check for startup-heavy profile
        if internal_pct > 70.0 {
            return "ℹ️ Profile is startup-heavy (V8/Node internals dominate). Profile under sustained load for better signal.".to_string();
        }

        // Check top function impact
        if let Some(top) = analysis.functions.first() {
            let top_pct = top.self_percent(analysis.total_time);
            if top_pct < 5.0 {
                return "✅ No clear bottleneck — CPU time is well-distributed".to_string();
            }
        }

        "✅ Profile looks healthy — no critical issues detected".to_string()
    }

    fn has_filters(metadata: &crate::analysis::ProfileMetadata) -> bool {
        metadata.internals_filtered
            || metadata.focus_package.is_some()
            || !metadata.filter_categories.is_empty()
    }

    fn scope_line(metadata: &crate::analysis::ProfileMetadata) -> Option<String> {
        let mut parts = Vec::new();

        if !metadata.filter_categories.is_empty() {
            parts.push(format!(
                "Categories: {}",
                Self::format_category_list(&metadata.filter_categories)
            ));
        }

        if metadata.internals_filtered {
            parts.push("Internals hidden".to_string());
        }

        if let Some(pkg) = &metadata.focus_package {
            parts.push(format!("Package: `{pkg}`"));
        }

        if parts.is_empty() {
            None
        } else {
            Some(format!("**Scope:** Filtered view ({})", parts.join("; ")))
        }
    }

    fn profile_quality_notes(metadata: &crate::analysis::ProfileMetadata) -> Vec<String> {
        let mut notes = Vec::new();

        if metadata.duration_ms < 1_000.0 || metadata.sample_count < 1_000 {
            notes.push("Short profile (<1s or <1000 samples). Results may be noisy.".to_string());
        }

        if metadata.sample_interval_ms > 5.0 {
            notes.push(
                "Coarse sampling interval (>5ms). Fine-grained hotspots may be missed.".to_string(),
            );
        }

        notes
    }

    fn format_category_list(categories: &[FrameCategory]) -> String {
        categories
            .iter()
            .map(|c| format!("`{}`", Self::category_label(*c)))
            .collect::<Vec<_>>()
            .join(", ")
    }

    fn category_label(category: FrameCategory) -> &'static str {
        match category {
            FrameCategory::App => "App",
            FrameCategory::Deps => "Dependencies",
            FrameCategory::NodeInternal => "Node internals",
            FrameCategory::V8Internal => "V8 internals",
            FrameCategory::Native => "Native",
        }
    }

    fn visible_total_time(analysis: &CpuAnalysis) -> Option<u64> {
        if analysis.metadata.focus_package.is_some() {
            return None;
        }

        let mut categories = if analysis.metadata.filter_categories.is_empty() {
            vec![
                FrameCategory::App,
                FrameCategory::Deps,
                FrameCategory::NodeInternal,
                FrameCategory::V8Internal,
                FrameCategory::Native,
            ]
        } else {
            analysis.metadata.filter_categories.clone()
        };

        if analysis.metadata.internals_filtered {
            categories.retain(|c| !c.is_internal());
        }

        let breakdown = &analysis.category_breakdown;
        let mut total = 0;
        for category in categories {
            total += match category {
                FrameCategory::App => breakdown.app,
                FrameCategory::Deps => breakdown.deps,
                FrameCategory::NodeInternal => breakdown.node_internal,
                FrameCategory::V8Internal => breakdown.v8_internal,
                FrameCategory::Native => breakdown.native,
            };
        }

        Some(total)
    }

    fn category_allowed(
        metadata: &crate::analysis::ProfileMetadata,
        category: FrameCategory,
    ) -> bool {
        if metadata.internals_filtered && category.is_internal() {
            return false;
        }

        if !metadata.filter_categories.is_empty() && !metadata.filter_categories.contains(&category)
        {
            return false;
        }

        true
    }

    /// Extract package name from a file location
    fn extract_package_name(location: &str) -> Option<String> {
        let path = location.strip_prefix("file://").unwrap_or(location);

        if let Some(nm_idx) = path.rfind("node_modules/") {
            let after_nm = &path[nm_idx + 13..];

            // Handle scoped packages
            if after_nm.starts_with('@') {
                let parts: Vec<&str> = after_nm.splitn(3, '/').collect();
                if parts.len() >= 2 {
                    return Some(format!("{}/{}", parts[0], parts[1]));
                }
            } else {
                let parts: Vec<&str> = after_nm.splitn(2, '/').collect();
                if !parts.is_empty() {
                    return Some(parts[0].to_string());
                }
            }
        }

        None
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_summary_row_with_inclusive(
        writer: &mut dyn Write,
        name: &str,
        self_time: u64,
        inclusive_time: u64,
        total: u64,
    ) -> Result<(), OutputError> {
        let self_str = format_time_us(self_time);
        let inclusive_str = format_time_us(inclusive_time);
        let self_pct = if total > 0 {
            (self_time as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        let inclusive_pct = if total > 0 {
            (inclusive_time as f64 / total as f64) * 100.0
        } else {
            0.0
        };

        let assessment = if self_pct < 20.0 {
            "normal"
        } else if self_pct < 50.0 {
            "notable"
        } else {
            "dominant"
        };

        writeln!(
            writer,
            "| {name} | {self_str} | {self_pct:.1}% | {inclusive_str} | {inclusive_pct:.1}% | {assessment} |"
        )?;
        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_heap_category_row(
        writer: &mut dyn Write,
        name: &str,
        size: u64,
        total: u64,
    ) -> Result<(), OutputError> {
        let size_str = AllocationStats::format_size(size);
        let pct = if total > 0 {
            (size as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        writeln!(writer, "| {name} | {size_str} | {pct:.1}% |")?;
        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_gc_analysis(
        writer: &mut dyn Write,
        gc: &crate::analysis::GcAnalysis,
        total_time: u64,
        phase_analysis: Option<&crate::analysis::PhaseAnalysis>,
    ) -> Result<(), OutputError> {
        writeln!(writer, "## GC & Allocation Signals")?;
        writeln!(writer)?;

        // Summary stats
        let gc_time_str = format_time_us(gc.total_time);
        let gc_pct = if total_time > 0 {
            (gc.total_time as f64 / total_time as f64) * 100.0
        } else {
            0.0
        };
        let avg_pause_str = format_time_us(gc.avg_pause_us);

        // Assessment
        let (severity, assessment) = if gc_pct > 10.0 {
            ("🔴", "High GC pressure — likely allocation hotspot")
        } else if gc_pct > 5.0 {
            ("🟡", "Moderate GC — worth investigating")
        } else if gc_pct > 2.0 {
            ("🟢", "Normal GC overhead")
        } else {
            ("", "Minimal GC activity")
        };

        writeln!(
            writer,
            "**{} GC overhead:** {} ({:.1}%) across {} samples — {}",
            severity, gc_time_str, gc_pct, gc.sample_count, assessment
        )?;
        writeln!(writer)?;

        // Calculate improvement potential
        let target_gc_pct = 2.0; // "Normal" GC overhead target
        let potential_savings_us = if gc_pct > target_gc_pct {
            let excess_pct = gc_pct - target_gc_pct;
            (excess_pct / 100.0 * total_time as f64) as u64
        } else {
            0
        };
        let potential_speedup_pct = if total_time > 0 {
            (potential_savings_us as f64 / total_time as f64) * 100.0
        } else {
            0.0
        };

        writeln!(writer, "| Metric | Value |")?;
        writeln!(writer, "|--------|-------|")?;
        writeln!(
            writer,
            "| Total GC time | {} ({:.1}%) |",
            gc_time_str, gc_pct
        )?;
        writeln!(writer, "| GC samples | {} |", gc.sample_count)?;
        writeln!(writer, "| Avg pause | {} |", avg_pause_str)?;

        // Show startup vs steady state GC if we have phase data
        if phase_analysis.is_some() && gc.startup_gc_time > 0 {
            let startup_pct = (gc.startup_gc_time as f64 / gc.total_time as f64) * 100.0;
            let steady_pct = (gc.steady_gc_time as f64 / gc.total_time as f64) * 100.0;
            writeln!(
                writer,
                "| Startup GC | {} ({:.0}%) |",
                format_time_us(gc.startup_gc_time),
                startup_pct
            )?;
            writeln!(
                writer,
                "| Steady-state GC | {} ({:.0}%) |",
                format_time_us(gc.steady_gc_time),
                steady_pct
            )?;
        }
        writeln!(writer)?;

        // Improvement potential section (only if GC is significantly above normal)
        // Don't show precise estimates for small differences - they're not defensible
        if gc_pct > 3.0 && potential_savings_us > 0 && potential_speedup_pct > 0.5 {
            writeln!(writer, "### 📈 Improvement Potential")?;
            writeln!(writer)?;
            writeln!(
                writer,
                "Reducing GC from {:.0}% to ~{:.0}% could save approximately **{}** (~{:.0}% faster)",
                gc_pct,
                target_gc_pct,
                format_time_us(potential_savings_us),
                potential_speedup_pct
            )?;
            writeln!(writer)?;

            // Per-hotspot impact estimation
            if !gc.allocation_hotspots.is_empty() {
                writeln!(writer, "| Optimize | Est. Savings | Impact |")?;
                writeln!(writer, "|----------|--------------|--------|")?;

                for hotspot in gc.allocation_hotspots.iter().take(5) {
                    // Estimate: if we eliminate this hotspot's GC contribution
                    // Savings = (correlation% / 100) * excess_gc_time
                    let hotspot_savings_us =
                        (hotspot.gc_correlation / 100.0 * potential_savings_us as f64) as u64;
                    let hotspot_impact_pct = if total_time > 0 {
                        (hotspot_savings_us as f64 / total_time as f64) * 100.0
                    } else {
                        0.0
                    };

                    if hotspot_savings_us > 0 {
                        writeln!(
                            writer,
                            "| `{}` | {} | {:.1}% faster |",
                            Self::escape_markdown(&hotspot.name),
                            format_time_us(hotspot_savings_us),
                            hotspot_impact_pct
                        )?;
                    }
                }
                writeln!(writer)?;

                writeln!(
                    writer,
                    "> **Note:** Estimates assume optimizing each function eliminates its GC contribution."
                )?;
                writeln!(
                    writer,
                    "> Actual savings depend on allocation patterns and may overlap between functions."
                )?;
                writeln!(writer)?;
            }
        }

        // Allocation hotspots
        if !gc.allocation_hotspots.is_empty() {
            writeln!(writer, "### Allocation Hotspots")?;
            writeln!(writer)?;
            writeln!(
                writer,
                "> Functions frequently on the call stack during GC — likely allocating heavily."
            )?;
            writeln!(writer)?;

            writeln!(
                writer,
                "| Function | GC Correlation | GC Samples | Category |"
            )?;
            writeln!(
                writer,
                "|----------|----------------|------------|----------|"
            )?;

            for hotspot in &gc.allocation_hotspots {
                writeln!(
                    writer,
                    "| `{}` | {:.0}% | {} | {} |",
                    Self::escape_markdown(&hotspot.name),
                    hotspot.gc_correlation,
                    hotspot.gc_samples,
                    Self::category_badge(hotspot.category)
                )?;
            }
            writeln!(writer)?;
        }

        // Actionable recommendations based on severity
        if gc_pct > 5.0 {
            writeln!(writer, "### Optimization Strategies")?;
            writeln!(writer)?;

            if !gc.allocation_hotspots.is_empty() {
                let top = &gc.allocation_hotspots[0];
                let top_savings = (top.gc_correlation / 100.0 * potential_savings_us as f64) as u64;
                writeln!(
                    writer,
                    "**Priority target: `{}`** ({:.0}% of GC events, ~{} potential savings)",
                    top.name,
                    top.gc_correlation,
                    format_time_us(top_savings)
                )?;
                writeln!(writer)?;
            }

            writeln!(writer, "**Common fixes:**")?;
            writeln!(
                writer,
                "- **Object reuse**: Pool frequently created objects instead of allocating new ones"
            )?;
            writeln!(
                writer,
                "- **Avoid closures in loops**: Each closure allocates; move them outside hot paths"
            )?;
            writeln!(
                writer,
                "- **Use typed arrays**: `Float64Array` instead of `[]` for numeric data"
            )?;
            writeln!(
                writer,
                "- **Batch operations**: Reduce intermediate array/object creation"
            )?;
            writeln!(
                writer,
                "- **String concatenation**: Use array join or template literals instead of `+` in loops"
            )?;

            if gc_pct > 10.0 {
                writeln!(writer)?;
                writeln!(writer, "**For severe GC pressure (>10%):**")?;
                writeln!(
                    writer,
                    "- Increase heap with `node --max-old-space-size=4096` (if memory allows)"
                )?;
                writeln!(
                    writer,
                    "- Profile heap with `profile-inspect heap` to find large allocators"
                )?;
            }
            writeln!(writer)?;
        }

        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_phase_analysis(
        writer: &mut dyn Write,
        phases: &crate::analysis::PhaseAnalysis,
    ) -> Result<(), OutputError> {
        writeln!(writer, "## Timing Phase Analysis")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "> Separates startup overhead from steady-state performance."
        )?;
        writeln!(writer)?;

        // Startup phase
        let startup = &phases.startup;
        let startup_duration = format_time_us(startup.end_us - startup.start_us);
        let startup_pct = if phases.total_duration_us > 0 {
            ((startup.end_us - startup.start_us) as f64 / phases.total_duration_us as f64) * 100.0
        } else {
            0.0
        };

        writeln!(
            writer,
            "### Startup Phase ({}, {:.1}% of profile)",
            startup_duration, startup_pct
        )?;
        writeln!(writer)?;

        if !startup.top_functions.is_empty() {
            writeln!(writer, "| Function | Self Time | % | Category |")?;
            writeln!(writer, "|----------|-----------|---|----------|")?;
            for func in &startup.top_functions {
                writeln!(
                    writer,
                    "| `{}` | {} | {:.1}% | {} |",
                    Self::escape_markdown(&func.name),
                    format_time_us(func.self_time),
                    func.percent,
                    Self::category_badge(func.category)
                )?;
            }
            writeln!(writer)?;
        }

        // Category breakdown for startup
        let total_startup = startup.category_breakdown.total();
        if total_startup > 0 {
            let v8_native =
                startup.category_breakdown.v8_internal + startup.category_breakdown.native;
            let v8_pct = (v8_native as f64 / total_startup as f64) * 100.0;
            if v8_pct > 50.0 {
                writeln!(
                    writer,
                    "**Startup insight:** {:.0}% V8/Native — typical for module loading/compilation",
                    v8_pct
                )?;
                writeln!(writer)?;
            }
        }

        // Steady state phase
        let steady = &phases.steady_state;
        let steady_duration = format_time_us(steady.end_us - steady.start_us);

        writeln!(writer, "### Steady State ({})", steady_duration)?;
        writeln!(writer)?;

        if !steady.top_functions.is_empty() {
            writeln!(writer, "| Function | Self Time | % | Category |")?;
            writeln!(writer, "|----------|-----------|---|----------|")?;
            for func in &steady.top_functions {
                writeln!(
                    writer,
                    "| `{}` | {} | {:.1}% | {} |",
                    Self::escape_markdown(&func.name),
                    format_time_us(func.self_time),
                    func.percent,
                    Self::category_badge(func.category)
                )?;
            }
            writeln!(writer)?;
        }

        // Category breakdown comparison
        let total_steady = steady.category_breakdown.total();
        if total_startup > 0 && total_steady > 0 {
            let startup_app_pct =
                (startup.category_breakdown.app as f64 / total_startup as f64) * 100.0;
            let steady_app_pct =
                (steady.category_breakdown.app as f64 / total_steady as f64) * 100.0;

            if steady_app_pct > startup_app_pct * 2.0 {
                writeln!(
                    writer,
                    "**Steady state insight:** App code increases from {:.0}% to {:.0}% — good, your code dominates runtime",
                    startup_app_pct, steady_app_pct
                )?;
                writeln!(writer)?;
            }
        }

        writeln!(writer, "---")?;
        writeln!(writer)?;

        Ok(())
    }

    fn write_recursive_functions(
        writer: &mut dyn Write,
        analysis: &CpuAnalysis,
    ) -> Result<(), OutputError> {
        writeln!(writer, "## Recursive Functions")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "> Functions that call themselves. Deep recursion can cause stack overflow and performance issues."
        )?;
        writeln!(writer)?;

        writeln!(
            writer,
            "| Function | Max Depth | Stacks with Recursion | Location |"
        )?;
        writeln!(
            writer,
            "|----------|-----------|----------------------|----------|"
        )?;

        for func in &analysis.recursive_functions {
            // Calculate percentage of stacks containing this function that show recursion
            // This should always be 0-100%
            let rec_pct = if func.total_samples > 0 {
                ((func.recursive_samples as f64 / func.total_samples as f64) * 100.0).min(100.0)
            } else {
                0.0
            };

            writeln!(
                writer,
                "| `{}` | {} | {} ({:.0}% of appearances) | `{}` |",
                Self::escape_markdown(&func.name),
                func.max_depth,
                func.recursive_samples,
                rec_pct,
                Self::escape_markdown(&func.location)
            )?;
        }

        writeln!(writer)?;
        writeln!(writer, "**Optimization tips for recursive functions:**")?;
        writeln!(
            writer,
            "- Consider iterative alternatives using explicit stack"
        )?;
        writeln!(
            writer,
            "- Add memoization if computing same values repeatedly"
        )?;
        writeln!(writer, "- Check for accidental infinite recursion patterns")?;
        writeln!(writer)?;
        writeln!(writer, "---")?;
        writeln!(writer)?;

        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_key_takeaways(
        writer: &mut dyn Write,
        analysis: &CpuAnalysis,
    ) -> Result<(), OutputError> {
        let breakdown = &analysis.category_breakdown;
        let inclusive = &analysis.category_breakdown_inclusive;
        let flow = &analysis.category_call_flow;
        let total = breakdown.total();

        if total == 0 {
            return Ok(());
        }

        let app_pct = (breakdown.app as f64 / total as f64) * 100.0;
        let deps_pct = (breakdown.deps as f64 / total as f64) * 100.0;
        let native_pct = ((breakdown.v8_internal + breakdown.native) as f64 / total as f64) * 100.0;

        // Calculate what each category triggers (calls to other categories)
        let app_triggers: u64 = flow
            .callees_for(FrameCategory::App)
            .iter()
            .map(|(_, t)| *t)
            .sum();
        let node_triggers: u64 = flow
            .callees_for(FrameCategory::NodeInternal)
            .iter()
            .map(|(_, t)| *t)
            .sum();

        // Key takeaways based on call flow analysis
        if app_pct > 50.0 {
            writeln!(
                writer,
                "- App code dominates ({:.0}% self) — focus optimization on your code",
                app_pct
            )?;
        } else if deps_pct > 20.0 {
            // Dependencies are significant by self time
            let inclusive_pct = (inclusive.deps as f64 / total as f64) * 100.0;
            writeln!(
                writer,
                "- Dependencies: {:.0}% self, {:.0}% stack presence — review which packages are expensive",
                deps_pct,
                inclusive_pct.min(100.0)
            )?;
        } else if native_pct > 70.0 {
            // V8/Native dominates - usually script compilation or native addon work
            // Check what's triggering this
            let node_to_native: u64 = flow
                .callees_for(FrameCategory::NodeInternal)
                .iter()
                .filter(|(cat, _)| {
                    *cat == FrameCategory::Native || *cat == FrameCategory::V8Internal
                })
                .map(|(_, t)| *t)
                .sum();
            let app_to_native: u64 = flow
                .callees_for(FrameCategory::App)
                .iter()
                .filter(|(cat, _)| {
                    *cat == FrameCategory::Native || *cat == FrameCategory::V8Internal
                })
                .map(|(_, t)| *t)
                .sum();

            if node_to_native > app_to_native {
                writeln!(
                    writer,
                    "- V8/Native dominates ({:.0}%) via Node.js internals — likely module loading/compilation",
                    native_pct
                )?;
            } else {
                writeln!(
                    writer,
                    "- V8/Native dominates ({:.0}%) — check for native addon work or heavy compilation",
                    native_pct
                )?;
            }
        } else if app_triggers > breakdown.app * 5 {
            // App code triggers much more than its self time
            writeln!(
                writer,
                "- App code ({:.0}% self) triggers {} in other categories — optimize hot call sites",
                app_pct,
                format_time_us(app_triggers)
            )?;
        } else if node_triggers > total / 3 {
            // Node internals are triggering a lot of work
            writeln!(
                writer,
                "- Node.js internals trigger {} — likely I/O or module loading",
                format_time_us(node_triggers)
            )?;
        }

        // Top hotspot (only if significant)
        if let Some(top) = analysis.functions.first() {
            let pct = top.self_percent(analysis.total_time);
            if pct > 5.0 {
                writeln!(
                    writer,
                    "- Top hotspot: `{}` at {:.1}% self time",
                    top.name, pct
                )?;
            }
        }

        // GC signal (use enhanced gc_analysis if available)
        if let Some(ref gc) = analysis.gc_analysis {
            let gc_pct = (gc.total_time as f64 / analysis.total_time as f64) * 100.0;
            if gc_pct > 5.0 {
                if let Some(top) = gc.allocation_hotspots.first() {
                    writeln!(
                        writer,
                        "- GC overhead at {:.1}% — `{}` may be allocating heavily ({:.0}% correlation)",
                        gc_pct, top.name, top.gc_correlation
                    )?;
                } else {
                    writeln!(
                        writer,
                        "- GC overhead at {:.1}% — investigate allocation patterns",
                        gc_pct
                    )?;
                }
            }
        } else if analysis.gc_time > 0 {
            let gc_pct = (analysis.gc_time as f64 / analysis.total_time as f64) * 100.0;
            if gc_pct > 5.0 {
                writeln!(
                    writer,
                    "- GC overhead at {:.1}% — may indicate allocation pressure",
                    gc_pct
                )?;
            }
        }

        Ok(())
    }

    fn category_badge(category: FrameCategory) -> &'static str {
        match category {
            FrameCategory::App => "App",
            FrameCategory::Deps => "Deps",
            FrameCategory::NodeInternal => "Node",
            FrameCategory::V8Internal => "V8",
            FrameCategory::Native => "Native",
        }
    }

    /// Classify workload based on CPU utilization
    fn classify_workload(cpu_util_pct: f64, profiles_merged: usize) -> String {
        let merged_note = if profiles_merged > 1 {
            ", aggregated across processes"
        } else {
            ""
        };

        if cpu_util_pct >= 80.0 {
            format!(
                "CPU-bound (~{:.0}% utilization{})",
                cpu_util_pct, merged_note
            )
        } else if cpu_util_pct <= 50.0 {
            format!(
                "I/O or wait-bound (~{:.0}% CPU utilization{}). CPU profiling may miss the full picture.",
                cpu_util_pct, merged_note
            )
        } else {
            format!(
                "Mixed (~{:.0}% CPU utilization{})",
                cpu_util_pct, merged_note
            )
        }
    }

    /// Summarize which category dominates self time
    #[expect(clippy::cast_precision_loss)]
    fn top_category_summary(breakdown: &crate::analysis::CategoryBreakdown, total: u64) -> String {
        let v8_native = breakdown.v8_internal + breakdown.native;
        let categories = [
            ("V8/Native", v8_native),
            ("App", breakdown.app),
            ("Dependencies", breakdown.deps),
            ("Node internals", breakdown.node_internal),
        ];

        let (top_name, top_time) = categories
            .iter()
            .max_by_key(|(_, t)| *t)
            .unwrap_or(&("Unknown", 0));

        let top_pct = (*top_time as f64 / total as f64) * 100.0;

        let insight = match *top_name {
            "V8/Native" if top_pct > 70.0 => {
                " — engine/runtime frames dominate (often startup/GC/JIT)"
            }
            "V8/Native" => " — engine/runtime frames (not necessarily native code)",
            "Dependencies" if top_pct > 40.0 => " — heavy library usage",
            "Dependencies" => "",
            "App" if top_pct > 50.0 => " — your code dominates, good optimization target",
            "App" => " — your code",
            "Node internals" => " — module loading/runtime setup",
            _ => "",
        };

        format!(
            "{} at {:.0}% self (exclusive){}",
            top_name, top_pct, insight
        )
    }

    fn escape_markdown(s: &str) -> String {
        s.replace('|', "\\|").replace('`', "\\`")
    }

    /// Format a percentage with appropriate precision.
    /// - >= 1%: show 1 decimal place (e.g., "4.5%")
    /// - 0.1% - 1%: show 2 decimal places (e.g., "0.34%")
    /// - < 0.1%: show as "<0.1%" to avoid noise
    fn format_percent(pct: f64) -> String {
        if pct >= 1.0 {
            format!("{:.1}%", pct)
        } else if pct >= 0.1 {
            format!("{:.2}%", pct)
        } else if pct > 0.0 {
            "<0.1%".to_string()
        } else {
            "0%".to_string()
        }
    }

    /// Format a location string for display, shortening long paths.
    ///
    /// Transforms:
    /// - `file:///Users/.../node_modules/.pnpm/pkg@1.0.0/node_modules/pkg/dist/file.js:10:5`
    ///   → `pkg » file.js:10`
    /// - `/Users/qing/project/src/utils/helper.ts:42:10`
    ///   → `src/utils/helper.ts:42`
    fn format_location(location: &str) -> String {
        // Strip file:// prefix
        let path = location.strip_prefix("file://").unwrap_or(location);

        // Handle node_modules paths - extract package name and file
        if let Some(nm_idx) = path.rfind("node_modules/") {
            let after_nm = &path[nm_idx + 13..]; // Skip "node_modules/"

            // Handle scoped packages (@org/pkg)
            let (pkg_name, rest) = if after_nm.starts_with('@') {
                // @scope/package/...
                let parts: Vec<&str> = after_nm.splitn(3, '/').collect();
                if parts.len() >= 3 {
                    (format!("{}/{}", parts[0], parts[1]), parts[2].to_string())
                } else {
                    (after_nm.to_string(), String::new())
                }
            } else {
                // Regular package/...
                let parts: Vec<&str> = after_nm.splitn(2, '/').collect();
                if parts.len() >= 2 {
                    (parts[0].to_string(), parts[1].to_string())
                } else {
                    (after_nm.to_string(), String::new())
                }
            };

            // Extract just the filename and line from rest
            let file_part = Self::extract_file_and_line(&rest);
            if file_part.is_empty() {
                return pkg_name;
            }
            return format!("{pkg_name} » {file_part}");
        }

        // Handle node: built-in modules
        if path.starts_with("node:") {
            return path.to_string();
        }

        // For regular paths, try to show relative from common roots
        // Look for common project directories
        for marker in &[
            "/src/",
            "/lib/",
            "/dist/",
            "/build/",
            "/apps/",
            "/packages/",
        ] {
            if let Some(idx) = path.find(marker) {
                return Self::extract_file_and_line(&path[idx + 1..]);
            }
        }

        // Fallback: just show the filename and line
        Self::extract_file_and_line(path)
    }

    /// Extract filename and line number from a path.
    /// Input: "dist/utils/helper.js:42:10" → "helper.js:42"
    fn extract_file_and_line(path: &str) -> String {
        // Split off line:col suffix
        let (path_part, line_col) = Self::split_line_col(path);

        // Get just the filename
        let filename = path_part.rsplit('/').next().unwrap_or(path_part);

        // For very long paths, show parent/file
        let display_path = if path_part.contains('/') {
            let parts: Vec<&str> = path_part.rsplitn(3, '/').collect();
            if parts.len() >= 2 && parts[1].len() < 20 {
                format!("{}/{}", parts[1], parts[0])
            } else {
                filename.to_string()
            }
        } else {
            filename.to_string()
        };

        if let Some(line) = line_col {
            format!("{display_path}:{line}")
        } else {
            display_path
        }
    }

    /// Split a path into (path, line_number) parts.
    /// "file.js:42:10" → ("file.js", Some(42))
    fn split_line_col(path: &str) -> (&str, Option<u32>) {
        // Find line:col pattern at end
        let mut parts = path.rsplitn(3, ':');
        let last = parts.next();
        let second = parts.next();
        let rest = parts.next();

        match (rest, second, last) {
            (Some(path), Some(line), Some(_col)) => {
                // path:line:col format
                (path, line.parse().ok())
            }
            (None, Some(path), Some(line_or_col)) => {
                // Could be path:line or just path with : in name
                if line_or_col.chars().all(|c| c.is_ascii_digit()) {
                    (path, line_or_col.parse().ok())
                } else {
                    // Not a line number, return original
                    (path.rsplit_once(':').map_or(path, |(p, _)| p), None)
                }
            }
            _ => (path, None),
        }
    }

    fn write_hot_path_visualization(
        writer: &mut dyn Write,
        profile: &ProfileIR,
        path: &HotPath,
    ) -> Result<(), OutputError> {
        // Find the most interesting span to display (avoid showing only internal frames)
        let frames: Vec<_> = path
            .frames
            .iter()
            .filter_map(|&fid| profile.get_frame(fid))
            .collect();

        // Find first non-internal frame
        let start_idx = frames
            .iter()
            .position(|f| !f.category.is_internal())
            .unwrap_or(0);

        // Show compressed path
        let display_frames: Vec<_> = frames.iter().skip(start_idx).take(8).collect();

        for (i, frame) in display_frames.iter().enumerate() {
            let indent = "  ".repeat(i);
            let arrow = if i > 0 { "└─ " } else { "" };
            let hotspot = if i == display_frames.len() - 1 {
                " ← HOTSPOT"
            } else {
                ""
            };
            let location = Self::format_location(&frame.location());
            writeln!(
                writer,
                "{indent}{arrow}{} ({location}){hotspot}",
                frame.display_name()
            )?;
        }

        if frames.len() > display_frames.len() + start_idx {
            writeln!(
                writer,
                "  ... ({} frames omitted)",
                frames.len() - display_frames.len() - start_idx
            )?;
        }

        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_path_explanation(
        writer: &mut dyn Write,
        profile: &ProfileIR,
        path: &HotPath,
        analysis: &CpuAnalysis,
    ) -> Result<(), OutputError> {
        let mut reasons = Vec::new();

        // Check if leaf has high self time
        if let Some(&leaf_id) = path.frames.last() {
            if let Some(func) = analysis.functions.iter().find(|f| f.frame_id == leaf_id) {
                let self_pct = func.self_percent(analysis.total_time);
                if self_pct > 1.0 {
                    reasons.push(format!(
                        "Leaf function `{}` has {:.1}% self time",
                        func.name, self_pct
                    ));
                }
            }
        }

        // Check if path is frequently sampled
        let total_samples = analysis.total_samples;
        if total_samples > 0 {
            let path_sample_pct = (path.sample_count as f64 / total_samples as f64) * 100.0;
            if path_sample_pct > 1.0 {
                reasons.push(format!("Appears in {:.1}% of samples", path_sample_pct));
            }
        }

        // Check for file system operations (be specific, not "I/O")
        let fs_keywords = [
            "fs:",
            "readFile",
            "writeFile",
            "stat",
            "readdir",
            "createReadStream",
            "createWriteStream",
            "readdirSync",
            "statSync",
            "readFileSync",
            "existsSync",
            "accessSync",
        ];
        let has_fs = path.frames.iter().any(|&fid| {
            profile.get_frame(fid).is_some_and(|f| {
                let name = f.display_name();
                let location = f.location();
                fs_keywords
                    .iter()
                    .any(|kw| name.contains(kw) || location.contains(kw))
            })
        });

        // Check for network operations separately (be strict to avoid false positives like "fetchModule")
        let has_net = path.frames.iter().any(|&fid| {
            profile.get_frame(fid).is_some_and(|f| {
                let location = f.location();
                // Only check location, not function name (to avoid "fetchModule" false positives)
                location.contains("node:net")
                    || location.contains("node:dns")
                    || location.contains("node:http")
                    || location.contains("node:https")
                    || location.contains("node:tls")
                    || location.contains("node:dgram")
            })
        });

        // Only mention what's actually present
        if has_fs && has_net {
            reasons.push("File system and network activity on stack".to_string());
        } else if has_fs {
            reasons.push("File system activity on stack (stat/readdir/path ops)".to_string());
        } else if has_net {
            reasons.push("Network activity on stack".to_string());
        }

        // Check for native addon calls (strict: only N-API, .node modules)
        // vs general native runtime operations
        let mut has_native_addon = false;
        let mut has_native_runtime = false;

        for &fid in &path.frames {
            if let Some(f) = profile.get_frame(fid) {
                if f.kind == FrameKind::Native {
                    let name = f.display_name();
                    let location = f.location();

                    // True native addon: N-API, .node modules, binding files
                    if name.contains("napi_")
                        || location.ends_with(".node")
                        || location.contains("/binding.")
                    {
                        has_native_addon = true;
                    } else if f.category == FrameCategory::Native && !name.starts_with('(') {
                        // Native runtime operations (not anonymous internal frames)
                        has_native_runtime = true;
                    }
                }
            }
        }

        if has_native_addon {
            reasons.push("Calls native addon (C++/Rust via N-API)".to_string());
        } else if has_native_runtime {
            reasons.push("Includes Node/V8 native operations".to_string());
        }

        if reasons.is_empty() {
            reasons.push("This call sequence accumulates time across samples".to_string());
        }

        writeln!(writer, "**Why this path is hot:**")?;
        for reason in reasons {
            writeln!(writer, "- {reason}")?;
        }

        Ok(())
    }

    #[expect(clippy::cast_precision_loss)]
    fn write_hot_function_detail(
        writer: &mut dyn Write,
        detail: &HotFunctionDetail,
        analysis: &CpuAnalysis,
    ) -> Result<(), OutputError> {
        let profile_total_time = analysis.total_time;
        let self_time = format_time_us(detail.self_time);
        let self_pct = if profile_total_time > 0 {
            (detail.self_time as f64 / profile_total_time as f64) * 100.0
        } else {
            0.0
        };

        writeln!(
            writer,
            "### `{}` ({} self, {:.1}%)",
            detail.name, self_time, self_pct
        )?;
        writeln!(writer, "Location: `{}`", detail.location)?;
        writeln!(writer)?;

        // Callers
        if !detail.callers.is_empty() {
            writeln!(writer, "**Top callers:**")?;
            writeln!(writer, "| Caller | Time | Calls |")?;
            writeln!(writer, "|--------|------|-------|")?;

            for caller in detail.callers.iter().take(5) {
                writeln!(
                    writer,
                    "| `{}` | {} | {} |",
                    Self::escape_markdown(&caller.name),
                    format_time_us(caller.time),
                    caller.call_count
                )?;
            }
            writeln!(writer)?;
        }

        // Callees
        if !detail.callees.is_empty() {
            writeln!(writer, "**Top callees inside:**")?;
            writeln!(writer, "| Callee | Self | Total | Calls |")?;
            writeln!(writer, "|--------|------|-------|-------|")?;

            for callee in detail.callees.iter().take(5) {
                writeln!(
                    writer,
                    "| `{}` | {} | {} | {} |",
                    Self::escape_markdown(&callee.name),
                    format_time_us(callee.self_time),
                    format_time_us(callee.total_time),
                    callee.call_count
                )?;
            }
            writeln!(writer)?;
        }

        // Call pattern signal
        if detail.callers.len() == 1 && detail.self_time > profile_total_time / 100 {
            writeln!(
                writer,
                "**Call pattern signal:** Single caller — if result is deterministic, consider memoization."
            )?;
            writeln!(writer)?;
        } else if detail.callers.len() > 3 {
            writeln!(
                writer,
                "**Call pattern signal:** Called from {} different sites — hot utility function.",
                detail.callers.len()
            )?;
            writeln!(writer)?;
        }

        Ok(())
    }

    /// Write intelligent, actionable recommendations
    #[expect(clippy::cast_precision_loss)]
    fn write_recommendations(
        writer: &mut dyn Write,
        profile: &ProfileIR,
        analysis: &CpuAnalysis,
    ) -> Result<(), OutputError> {
        let report = RecommendationEngine::analyze(profile, analysis);

        writeln!(writer, "## Action Items")?;
        writeln!(writer)?;

        if report.recommendations.is_empty() {
            // Tailor message based on CPU utilization
            let cpu_util = analysis.metadata.cpu_utilization().unwrap_or(1.0) * 100.0;
            let is_cpu_bound = cpu_util >= 80.0;

            writeln!(writer, "**No dominant CPU hotspot detected in App code.**")?;
            writeln!(writer)?;

            if is_cpu_bound {
                // CPU-bound: don't suggest I/O latency, focus on diffuse CPU work
                writeln!(
                    writer,
                    "CPU usage is high ({:.0}%) but distributed across dependencies and runtime. To improve performance:",
                    cpu_util
                )?;
                writeln!(
                    writer,
                    "- **Reduce filesystem CPU cost:** cache config/path resolution, avoid repeated `stat`/`readdir`"
                )?;
                writeln!(
                    writer,
                    "- **Minimize parser/transform passes:** batch operations, reuse AST where possible"
                )?;
                writeln!(
                    writer,
                    "- **Review dependency usage:** check if heavy deps can be replaced or lazily loaded"
                )?;
                writeln!(
                    writer,
                    "- **Profile under sustained load:** startup overhead may dominate short runs"
                )?;
            } else {
                // I/O-bound or mixed: suggest investigating wait time
                writeln!(
                    writer,
                    "CPU utilization is low ({:.0}%), indicating the process spent time waiting. Consider:",
                    cpu_util
                )?;
                writeln!(
                    writer,
                    "- **I/O latency:** check file system, network, or database wait times"
                )?;
                writeln!(
                    writer,
                    "- **Async bottlenecks:** look for sequential awaits that could be parallelized"
                )?;
                writeln!(
                    writer,
                    "- **Tool orchestration:** time spent in `npx`, package managers, or build tools"
                )?;
                writeln!(
                    writer,
                    "- **Use tracing:** CPU profiles can't measure wait time; consider `--trace-event-categories`"
                )?;
            }
            writeln!(writer)?;
            return Ok(());
        }

        // Write insights summary
        if !report.insights.is_empty() {
            writeln!(writer, "### Key Insights")?;
            writeln!(writer)?;
            for insight in &report.insights {
                writeln!(writer, "- {insight}")?;
            }
            writeln!(writer)?;
        }

        // Write quick wins if any
        if !report.quick_wins.is_empty() {
            writeln!(writer, "### Quick Wins")?;
            writeln!(writer)?;
            writeln!(
                writer,
                "> High-impact improvements that are easy to implement"
            )?;
            writeln!(writer)?;
            for &idx in &report.quick_wins {
                if let Some(rec) = report.recommendations.get(idx) {
                    Self::write_recommendation_summary(writer, rec, analysis.total_time)?;
                }
            }
            writeln!(writer)?;
        }

        // Write all recommendations by priority (excluding quick wins already shown)
        let quick_win_set: std::collections::HashSet<_> = report.quick_wins.iter().collect();
        let critical: Vec<_> = report
            .recommendations
            .iter()
            .enumerate()
            .filter(|(i, r)| r.priority == Priority::Critical && !quick_win_set.contains(i))
            .map(|(_, r)| r)
            .collect();
        let high: Vec<_> = report
            .recommendations
            .iter()
            .enumerate()
            .filter(|(i, r)| r.priority == Priority::High && !quick_win_set.contains(i))
            .map(|(_, r)| r)
            .collect();
        let medium: Vec<_> = report
            .recommendations
            .iter()
            .enumerate()
            .filter(|(i, r)| r.priority == Priority::Medium && !quick_win_set.contains(i))
            .map(|(_, r)| r)
            .collect();

        if !critical.is_empty() {
            writeln!(writer, "### Critical Priority")?;
            writeln!(writer)?;
            for rec in critical {
                Self::write_recommendation_detail(writer, rec, analysis.total_time)?;
            }
        }

        if !high.is_empty() {
            writeln!(writer, "### High Priority")?;
            writeln!(writer)?;
            for rec in high {
                Self::write_recommendation_detail(writer, rec, analysis.total_time)?;
            }
        }

        if !medium.is_empty() {
            writeln!(writer, "### Medium Priority")?;
            writeln!(writer)?;
            for rec in &medium[..medium.len().min(5)] {
                Self::write_recommendation_summary(writer, rec, analysis.total_time)?;
            }
            if medium.len() > 5 {
                writeln!(
                    writer,
                    "*...and {} more medium-priority items*",
                    medium.len() - 5
                )?;
            }
            writeln!(writer)?;
        }

        // Write investigation items if any
        if !report.investigations.is_empty() {
            writeln!(writer, "### Needs Investigation")?;
            writeln!(writer)?;
            for item in &report.investigations {
                writeln!(writer, "- {item}")?;
            }
            writeln!(writer)?;
        }

        Ok(())
    }

    /// Write a brief recommendation summary
    #[expect(clippy::cast_precision_loss)]
    fn write_recommendation_summary(
        writer: &mut dyn Write,
        rec: &Recommendation,
        total_time: u64,
    ) -> Result<(), OutputError> {
        let savings_str = format_time_us(rec.estimated_savings_us);
        let savings_pct = rec.savings_percent(total_time);

        writeln!(
            writer,
            "- **{}** — *{} potential savings ({:.1}% faster)*",
            rec.title, savings_str, savings_pct
        )?;
        writeln!(writer, "  - {}", rec.root_cause)?;
        writeln!(writer, "  - Effort: {}", rec.effort)?;
        writeln!(writer)?;

        Ok(())
    }

    /// Write detailed recommendation with actions
    #[expect(clippy::cast_precision_loss)]
    fn write_recommendation_detail(
        writer: &mut dyn Write,
        rec: &Recommendation,
        total_time: u64,
    ) -> Result<(), OutputError> {
        let savings_str = format_time_us(rec.estimated_savings_us);
        let savings_pct = rec.savings_percent(total_time);
        let current_str = format_time_us(rec.current_time_us);

        // Header with impact
        writeln!(
            writer,
            "#### {} `{}`",
            Self::priority_icon(rec.priority),
            rec.title
        )?;
        writeln!(writer)?;

        // Impact summary
        writeln!(writer, "| Metric | Value |")?;
        writeln!(writer, "|--------|-------|")?;
        writeln!(writer, "| Current time | {} |", current_str)?;
        writeln!(
            writer,
            "| Potential savings | {} ({:.1}% faster) |",
            savings_str, savings_pct
        )?;
        writeln!(writer, "| Effort | {} |", rec.effort)?;
        writeln!(writer, "| Type | {} |", rec.issue_type)?;
        writeln!(writer)?;

        // Location
        writeln!(
            writer,
            "**Location:** `{}`",
            Self::format_location(&rec.location)
        )?;
        writeln!(writer)?;

        // Root cause
        writeln!(writer, "**Why:** {}", rec.root_cause)?;
        writeln!(writer)?;

        // Actions
        writeln!(writer, "**Actions:**")?;
        for action in &rec.actions {
            writeln!(writer, "- {action}")?;
        }
        writeln!(writer)?;

        // Code patterns to look for
        if !rec.code_patterns.is_empty() {
            writeln!(writer, "**Look for:**")?;
            for pattern in &rec.code_patterns {
                writeln!(writer, "- `{pattern}`")?;
            }
            writeln!(writer)?;
        }

        // Evidence
        if !rec.evidence.is_empty() {
            writeln!(writer, "<details>")?;
            writeln!(writer, "<summary>Evidence from profile</summary>")?;
            writeln!(writer)?;
            for evidence in &rec.evidence {
                writeln!(writer, "- {evidence}")?;
            }
            writeln!(writer)?;
            writeln!(writer, "</details>")?;
            writeln!(writer)?;
        }

        Ok(())
    }

    fn priority_icon(priority: Priority) -> &'static str {
        match priority {
            Priority::Critical => "🔴",
            Priority::High => "🟠",
            Priority::Medium => "🟡",
            Priority::Low => "🟢",
        }
    }
}