startled 0.9.1

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

/// Define a type alias for the report structure
type ReportStructure = BTreeMap<String, Vec<String>>;

/// Convert snake_case to kebab-case for SEO-friendly URLs
fn snake_to_kebab(input: &str) -> String {
    input.replace('_', "-")
}

#[derive(Serialize)]
struct SeriesRenderData {
    name: String,
    values: Vec<f64>, // e.g., [avg, p99, p95, p50]
}

#[derive(Serialize)]
struct BarChartRenderData {
    title: String,                  // e.g., "Cold Start - Init Duration"
    unit: String,                   // e.g., "ms"
    y_axis_categories: Vec<String>, // e.g., ["AVG", "P99", "P95", "P50"]
    series: Vec<SeriesRenderData>,
    page_type: String,           // e.g., "cold_init", for context in JS if needed
    description: Option<String>, // AWS-documentation-based description of the metric
}

#[derive(Serialize)]
struct ScatterPoint {
    x: usize, // Original index or offsetted index
    y: f64,   // Duration
}

#[derive(Serialize)]
struct LineSeriesRenderData {
    name: String,
    points: Vec<ScatterPoint>,
    mean: Option<f64>,
}

#[derive(Serialize)]
struct LineChartRenderData {
    title: String,
    x_axis_label: String,
    y_axis_label: String,
    unit: String,
    series: Vec<LineSeriesRenderData>,
    total_x_points: usize,
    page_type: String,
    description: Option<String>, // AWS-documentation-based description of the metric
}

/// Data structure for memory scaling charts
#[derive(Debug, Serialize)]
struct MemoryScalingPoint {
    memory_mb: i32,
    value: f64,
}

#[derive(Debug, Serialize)]
struct MemoryScalingSeriesData {
    name: String, // Function name
    points: Vec<MemoryScalingPoint>,
}

#[derive(Debug, Serialize)]
struct MemoryScalingChartRenderData {
    title: String,
    subtitle: String,
    x_axis_label: String,
    y_axis_label: String,
    unit: String,
    series: Vec<MemoryScalingSeriesData>,
    page_type: String,
    description: Option<String>,
}

/// Data structure for individual metrics in the summary
#[derive(Debug, Serialize)]
struct SummaryMetricData {
    id: String,                   // e.g., "cold-total-duration"
    title: String,                // e.g., "Cold Start Total Duration"
    unit: String,                 // e.g., "ms"
    link: String,                 // e.g., "../cold-start-total-duration/"
    data: Vec<SummarySeriesData>, // Function performance data
}

#[derive(Debug, Serialize)]
struct SummarySeriesData {
    name: String, // Function name
    value: f64,   // Average value for this metric
}

/// Data structure for the complete summary page
#[derive(Debug, Serialize)]
struct SummaryChartRenderData {
    title: String,
    description: String,
    metrics: Vec<SummaryMetricData>,
    page_type: String,
}

/// Data structure for memory scaling summary with multiple charts
#[derive(Debug, Serialize)]
struct MemoryScalingSummaryData {
    title: String,
    description: String,
    charts: Vec<MemoryScalingChartRenderData>,
    page_type: String,
}

#[derive(Serialize)]
enum ChartRenderData {
    Combined {
        bar: Box<BarChartRenderData>,
        line: Box<LineChartRenderData>,
    },
    Summary(SummaryChartRenderData),
    MemoryScalingSummary(MemoryScalingSummaryData),
}

/// Generate a chart with the given options
#[allow(clippy::too_many_arguments)]
async fn generate_chart(
    html_dir: &Path,
    png_dir: Option<&Path>,
    name: &str,
    chart_render_data: &ChartRenderData,
    config: &BenchmarkConfig,
    suffix: &str,
    screenshot_theme: Option<&str>,
    pb: &ProgressBar,
    report_structure: &ReportStructure,
    current_group: &str,
    current_subgroup: &str,
    template_dir: Option<&String>,
    base_url: Option<&str>,
    local_browsing: bool,
) -> Result<()> {
    // Initialize Tera for HTML templates (chart.html, _sidebar.html)
    let mut tera_html = Tera::default();
    if let Some(custom_template_dir) = template_dir {
        let base_path = PathBuf::from(custom_template_dir);
        if !base_path.exists() {
            anyhow::bail!(
                "Custom template directory not found: {}",
                custom_template_dir
            );
        }
        let glob_pattern = base_path.join("*.html").to_string_lossy().into_owned();
        tera_html = Tera::new(&glob_pattern).with_context(|| {
            format!(
                "Failed to load HTML templates from custom directory: {}",
                glob_pattern
            )
        })?;
        if !tera_html.get_template_names().any(|n| n == "chart.html") {
            anyhow::bail!(
                "Essential HTML template 'chart.html' not found in custom directory: {}",
                custom_template_dir
            );
        }
        if !tera_html.get_template_names().any(|n| n == "_sidebar.html") {
            anyhow::bail!(
                "Essential HTML template '_sidebar.html' not found in custom directory: {}",
                custom_template_dir
            );
        }
    } else {
        tera_html.add_raw_template("chart.html", include_str!("templates/chart.html"))?;
        tera_html.add_raw_template("_sidebar.html", include_str!("templates/_sidebar.html"))?;
    }

    // Create kebab-case chart directory name
    let kebab_name = snake_to_kebab(name);

    // Create directory for this chart
    let chart_dir = html_dir.join(&kebab_name);
    fs::create_dir_all(&chart_dir)?;

    // Write ChartRenderData variant to *_data.js file in the chart directory
    let data_js_filename = "chart_data.js";
    let data_js_path = chart_dir.join(data_js_filename);
    let json_data_string = serde_json::to_string(chart_render_data)
        .context("Failed to serialize chart render data enum")?;
    fs::write(
        &data_js_path,
        // JS will need to check the structure or use page_type/chart_type
        format!("window.currentChartSpecificData = {};", json_data_string),
    )?;

    // Create context FOR HTML PAGE (chart.html)
    let mut ctx = TeraContext::new();
    // Extract title, page_type, and description from the enum variant
    let (title, page_type, description) = match chart_render_data {
        ChartRenderData::Combined { bar, line: _ } => {
            (bar.title.as_str(), bar.page_type.as_str(), &bar.description)
        }
        ChartRenderData::Summary(summary) => (
            summary.title.as_str(),
            summary.page_type.as_str(),
            &Some(summary.description.clone()),
        ),
        ChartRenderData::MemoryScalingSummary(memory_summary) => (
            memory_summary.title.as_str(),
            memory_summary.page_type.as_str(),
            &Some(memory_summary.description.clone()),
        ),
    };

    ctx.insert("title", title);
    ctx.insert("config", config);
    ctx.insert("chart_id", "chart");
    ctx.insert("page_type", page_type);
    ctx.insert("chart_data_js", data_js_filename);
    ctx.insert("description", description);

    // Add sidebar context
    ctx.insert("report_structure", report_structure);
    ctx.insert("current_group", current_group);
    ctx.insert("current_subgroup", current_subgroup);
    ctx.insert("base_path", &calculate_base_path(html_dir, base_url)?);

    // Use the kebab-case name for URL references
    ctx.insert("kebab_name", &kebab_name);

    // Add link_suffix for local browsing
    ctx.insert(
        "link_suffix",
        if local_browsing { "index.html" } else { "" },
    );

    // Render the index file inside the chart directory
    let html_path = chart_dir.join(format!("index.{}", suffix));
    pb.set_message(format!("Rendering {}...", html_path.display()));
    let html = tera_html.render("chart.html", &ctx)?;
    fs::write(&html_path, html)?;

    // Take screenshot if requested
    if let Some(png_dir_path) = png_dir {
        if let Some(theme_str) = screenshot_theme {
            let screenshot_path = png_dir_path.join(format!("{}.png", name));
            pb.set_message(format!("Generating {}...", screenshot_path.display()));
            take_chart_screenshot(&html_path, &screenshot_path, theme_str).await?;
        }
    }

    Ok(())
}

/// Calculate the relative base path for sidebar links (needed for templates)
/// If base_url is provided, it will be used instead of calculating relative paths
fn calculate_base_path(current_dir: &Path, base_url: Option<&str>) -> Result<String> {
    if let Some(base) = base_url {
        // If a base URL is provided, use it for all paths
        // Ensure it ends with a trailing slash for path concatenation
        let mut base = base.to_string();
        if !base.ends_with('/') {
            base.push('/');
        }
        return Ok(base);
    }

    // Otherwise calculate relative paths as before
    // Calculate depth by counting directory components
    // For node/128mb/chart-name/ that would be 3 levels deep, resulting in "../../../"
    let path_components = current_dir.components().count();

    // When calculating the base path, we'll be one level deeper in the chart-type directory
    // So we need to add 1 to the standard depth calculation
    let depth = match path_components {
        0 => 0,
        // Count actual directory levels + 1 for chart subdirectory (but at most 3 levels deep)
        _ => std::cmp::min(path_components + 1, 3),
    };

    Ok("../".repeat(depth))
}

/// Represents an item in the index page
#[derive(Debug, Serialize)]
struct IndexItem {
    title: String,
    subtitle: Option<String>,
    path: String,
    metadata: Vec<(String, String)>,
}

impl IndexItem {
    fn new(title: impl Into<String>, path: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            subtitle: None,
            path: path.into(),
            metadata: Vec::new(),
        }
    }

    fn with_subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }
}

/// Scans the input directory to build the report structure for the sidebar.
fn scan_report_structure(base_input_dir: &str) -> Result<ReportStructure> {
    let mut structure = BTreeMap::new();
    let base_path = Path::new(base_input_dir);

    for group_entry in fs::read_dir(base_path)? {
        let group_entry = group_entry?;
        let group_path = group_entry.path();
        if group_path.is_dir() {
            let group_name = group_entry.file_name().to_string_lossy().to_string();
            let mut subgroups = Vec::new();
            for subgroup_entry in fs::read_dir(&group_path)? {
                let subgroup_entry = subgroup_entry?;
                let subgroup_path = subgroup_entry.path();
                if subgroup_path.is_dir() {
                    // Use match and is_some_and for clarity
                    let has_json = fs::read_dir(&subgroup_path)?.any(|entry_result| {
                        match entry_result {
                            Ok(e) => e.path().extension().is_some_and(|ext| ext == "json"),
                            Err(_) => false, // Ignore errors reading specific entries
                        }
                    });
                    if has_json {
                        subgroups.push(subgroup_entry.file_name().to_string_lossy().to_string());
                    }
                }
            }
            // Sort subgroups numerically by name
            subgroups.sort_by_key(|name| {
                name.trim_end_matches("mb")
                    .parse::<u32>()
                    .unwrap_or(u32::MAX)
            });

            if !subgroups.is_empty() {
                structure.insert(group_name, subgroups);
            }
        }
    }

    Ok(structure)
}

/// Generates the main landing page for the reports.
#[allow(clippy::too_many_arguments)]
async fn generate_landing_page(
    output_directory: &str,
    report_structure: &ReportStructure,
    custom_title: Option<&str>,
    description: Option<&str>,
    suffix: &str,
    pb: &ProgressBar,
    template_dir: Option<&String>,
    readme_file: Option<&str>,
    base_url: Option<&str>,
    local_browsing: bool,
) -> Result<()> {
    let mut tera = Tera::default();
    if let Some(custom_template_dir) = template_dir {
        let base_path = PathBuf::from(custom_template_dir);
        if !base_path.exists() {
            anyhow::bail!(
                "Custom template directory not found: {}",
                custom_template_dir
            );
        }
        let glob_pattern = base_path.join("*.html").to_string_lossy().into_owned();
        tera = Tera::new(&glob_pattern).with_context(|| {
            format!(
                "Failed to load templates from custom directory: {}",
                glob_pattern
            )
        })?;

        if !tera.get_template_names().any(|n| n == "index.html") {
            anyhow::bail!(
                "Essential template 'index.html' not found in custom directory: {}",
                custom_template_dir
            );
        }
        if !tera.get_template_names().any(|n| n == "_sidebar.html") {
            anyhow::bail!(
                "Essential template '_sidebar.html' not found in custom directory: {}",
                custom_template_dir
            );
        }
    } else {
        // Fallback to embedded templates
        tera.add_raw_template("index.html", include_str!("templates/index.html"))?;
        tera.add_raw_template("_sidebar.html", include_str!("templates/_sidebar.html"))?;
    }

    let mut ctx = TeraContext::new();
    ctx.insert("title", custom_title.unwrap_or("Benchmark Reports"));
    if let Some(desc) = description {
        ctx.insert("description", desc);
    }
    // Landing page specific context
    ctx.insert("is_landing_page", &true);
    // Add link_suffix for local browsing
    ctx.insert(
        "link_suffix",
        if local_browsing { "index.html" } else { "" },
    );
    // Sidebar context
    ctx.insert("report_structure", report_structure);
    ctx.insert("current_group", "");
    ctx.insert("current_subgroup", "");

    // Handle base_url parameter
    let base_path = if let Some(base) = base_url {
        // Ensure it ends with a trailing slash for path concatenation
        let mut base = base.to_string();
        if !base.ends_with('/') {
            base.push('/');
        }
        base
    } else {
        // Default empty string for root path
        "".to_string()
    };
    ctx.insert("base_path", &base_path);

    // Parse markdown content if readme file provided
    if let Some(readme_path) = readme_file {
        pb.set_message(format!("Parsing markdown from {}...", readme_path));
        match fs::read_to_string(readme_path) {
            Ok(markdown_content) => {
                // Set up the parser with GitHub-flavored markdown options
                let mut options = Options::empty();
                options.insert(Options::ENABLE_TABLES);
                options.insert(Options::ENABLE_FOOTNOTES);
                options.insert(Options::ENABLE_STRIKETHROUGH);
                options.insert(Options::ENABLE_TASKLISTS);

                let parser = Parser::new_ext(&markdown_content, options);

                // Convert markdown to HTML
                let mut html_output = String::new();
                html::push_html(&mut html_output, parser);

                // Add the HTML content to the template context
                ctx.insert("readme_html", &html_output);
                ctx.insert("has_readme", &true);
            }
            Err(e) => {
                // Set progress bar message
                pb.set_message(format!("Warning: Failed to read markdown file: {}", e));

                // Print warning to stderr for better visibility
                eprintln!(
                    "\n⚠️  Warning: Failed to read readme file '{}': {}",
                    readme_path, e
                );
                eprintln!("    Report will be generated without readme content.\n");

                ctx.insert("has_readme", &false);
            }
        }
    } else {
        ctx.insert("has_readme", &false);
    }

    // Create items for the landing page grid
    let mut items = Vec::new();
    for (group_name, subgroups) in report_structure {
        // Link to the group's memory scaling summary page
        let link_path = format!("{}/all/summary/", group_name);
        items.push(
            IndexItem::new(group_name, link_path)
                .with_subtitle(format!("{} memory configurations", subgroups.len())),
        );
    }
    ctx.insert("items", &items);

    let index_path = Path::new(output_directory).join(format!("index.{}", suffix));
    pb.set_message(format!("Generating landing page: {}", index_path.display()));
    let html = tera.render("index.html", &ctx)?;
    fs::write(&index_path, html)?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn generate_reports(
    input_directory: &str,
    output_directory: &str,
    custom_title: Option<&str>,
    description: Option<&str>,
    suffix: &str,
    base_url: Option<&str>,
    screenshot_theme: Option<&str>,
    template_dir: Option<String>,
    readme_file: Option<String>,
    local_browsing: bool,
) -> Result<()> {
    // Create output directory if it doesn't exist
    fs::create_dir_all(output_directory)?;

    // --- Copy CSS and JS files first (before chart generation for screenshots) ---
    let css_dir = Path::new(output_directory).join("css");
    fs::create_dir_all(&css_dir).context("Failed to create css output directory")?;
    let css_path = css_dir.join("style.css");

    if let Some(custom_template_dir_str) = &template_dir {
        let css_src_path = PathBuf::from(custom_template_dir_str)
            .join("css")
            .join("style.css");
        if !css_src_path.exists() {
            anyhow::bail!(
                "style.css not found in custom template directory: {}",
                css_src_path.display()
            );
        }
        fs::copy(&css_src_path, &css_path).context(format!(
            "Failed to copy style.css from custom template directory: {}",
            css_src_path.display()
        ))?;
    } else {
        let css_content = include_str!("templates/css/style.css");
        fs::write(&css_path, css_content).context("Failed to write style.css")?;
    }

    let js_dir = Path::new(output_directory).join("js");
    fs::create_dir_all(&js_dir).context("Failed to create js output directory")?;
    let js_lib_dst = js_dir.join("lib.js");

    if let Some(custom_template_dir_str) = &template_dir {
        let js_lib_src_path = PathBuf::from(custom_template_dir_str)
            .join("js")
            .join("lib.js");

        if !js_lib_src_path.exists() {
            anyhow::bail!(
                "lib.js not found in custom template directory: {}",
                js_lib_src_path.display()
            );
        }

        fs::copy(&js_lib_src_path, &js_lib_dst).context(format!(
            "Failed to copy lib.js from custom template directory: {}",
            js_lib_src_path.display()
        ))?;
    } else {
        let js_lib_content = include_str!("templates/js/lib.js");
        fs::write(&js_lib_dst, js_lib_content).context("Failed to write default lib.js")?;
    }
    // -------------------------

    // Early check if readme file exists
    if let Some(readme_path) = &readme_file {
        if !Path::new(readme_path).exists() {
            eprintln!("\n⚠️  Warning: Readme file '{}' not found.", readme_path);
            eprintln!("    Report will be generated without readme content.\n");
        }
    }

    // Scan the structure first
    println!("Scanning report structure at {}", input_directory);
    let report_structure = scan_report_structure(input_directory)?;
    if report_structure.is_empty() {
        anyhow::bail!("No valid benchmark data found in the input directory structure.");
    }

    // Print the structure as an indented list instead of using Debug formatting
    println!("✓ Report structure scanned:");
    for (group_name, subgroups) in &report_structure {
        println!("{} ({} configurations)", group_name, subgroups.len());
        for subgroup in subgroups {
            println!("    - {}", subgroup);
        }
    }

    // Setup progress indicators
    let m = MultiProgress::new();
    let pb_style = ProgressStyle::default_spinner()
        .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
        .template("{prefix:.bold.dim} {spinner} {wide_msg}")?;
    let main_pb = m.add(ProgressBar::new_spinner());
    main_pb.set_style(pb_style.clone());
    main_pb.set_prefix("[1/2] Generating Charts");
    main_pb.enable_steady_tick(Duration::from_millis(100));

    // Iterate through the structure and generate chart pages
    let total_subgroups: usize = report_structure.values().map(|v| v.len()).sum();
    main_pb.set_length(total_subgroups as u64);
    main_pb.set_message("Processing subgroups...");

    for (group_name, subgroups) in &report_structure {
        for subgroup_name in subgroups {
            main_pb.set_message(format!("Processing {}/{}...", group_name, subgroup_name));
            let current_input_dir = Path::new(input_directory)
                .join(group_name)
                .join(subgroup_name);
            let current_output_dir = Path::new(output_directory)
                .join(group_name)
                .join(subgroup_name);

            fs::create_dir_all(&current_output_dir)?;

            // Generate the actual chart reports for this specific group/subgroup
            generate_reports_for_directory(
                current_input_dir.to_str().unwrap(),
                current_output_dir.to_str().unwrap(),
                custom_title,
                suffix,
                screenshot_theme,
                &main_pb,
                &report_structure, // Pass full structure for sidebar
                group_name,
                subgroup_name,
                template_dir.as_ref(),
                base_url,
                local_browsing,
            )
            .await
            .context(format!(
                "Failed generating reports for {}/{}",
                group_name, subgroup_name
            ))?;
            main_pb.inc(1);
        }

        // Generate group-level memory scaling summary
        main_pb.set_message(format!(
            "Generating memory scaling summary for {}...",
            group_name
        ));
        generate_group_memory_scaling_summary(
            group_name,
            subgroups,
            input_directory,
            output_directory,
            suffix,
            screenshot_theme,
            &main_pb,
            &report_structure,
            template_dir.as_ref(),
            base_url,
            local_browsing,
        )
        .await
        .context(format!(
            "Failed generating memory scaling summary for {}",
            group_name
        ))?;
    }
    main_pb.finish_with_message("✓ Charts generated.");

    // Generate the single landing page
    let landing_pb = m.add(ProgressBar::new_spinner());
    landing_pb.set_style(pb_style);
    landing_pb.set_prefix("[2/2] Finalizing");
    landing_pb.enable_steady_tick(Duration::from_millis(100));

    generate_landing_page(
        output_directory,
        &report_structure,
        custom_title,
        description,
        suffix,
        &landing_pb,
        template_dir.as_ref(),
        readme_file.as_deref(),
        base_url,
        local_browsing,
    )
    .await?;
    landing_pb.finish_with_message("✓ Landing page generated.");

    m.clear()?;

    // Print path to the main index.html
    let index_path = PathBuf::from(output_directory).join("index.html");
    if index_path.exists() {
        println!("✨ Report generated successfully!");
        println!("📊 View the report at: {}", index_path.display());
    }

    Ok(())
}

/// Generate group-level memory scaling summary showing how each function performs across memory sizes
#[allow(clippy::too_many_arguments)]
async fn generate_group_memory_scaling_summary(
    group_name: &str,
    subgroups: &[String],
    input_directory: &str,
    output_directory: &str,
    suffix: &str,
    screenshot_theme: Option<&str>,
    pb: &ProgressBar,
    report_structure: &ReportStructure,
    template_dir: Option<&String>,
    base_url: Option<&str>,
    local_browsing: bool,
) -> Result<()> {
    // Create group/all directory for memory scaling summary
    let all_dir = Path::new(output_directory).join(group_name).join("all");
    fs::create_dir_all(&all_dir)?;

    // Create output directory for PNG files if screenshots are enabled
    let png_dir = if screenshot_theme.is_some() {
        let dir = all_dir.join("png");
        fs::create_dir_all(&dir)?;
        Some(dir)
    } else {
        None
    };

    // Collect data across all memory sizes
    let mut function_memory_data: BTreeMap<String, BTreeMap<i32, BenchmarkReport>> =
        BTreeMap::new();

    for subgroup_name in subgroups {
        // Parse memory size from subgroup name (e.g., "128mb" -> 128)
        let memory_mb = subgroup_name
            .trim_end_matches("mb")
            .parse::<i32>()
            .unwrap_or(0);

        if memory_mb == 0 {
            continue; // Skip non-memory subgroups
        }

        let subgroup_dir = Path::new(input_directory)
            .join(group_name)
            .join(subgroup_name);

        // Read all JSON files in this subgroup
        for entry in fs::read_dir(&subgroup_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("json") {
                let content = fs::read_to_string(&path)?;
                let report: BenchmarkReport = serde_json::from_str(&content)?;
                let function_name = report.config.function_name.clone();

                function_memory_data
                    .entry(function_name)
                    .or_default()
                    .insert(memory_mb, report);
            }
        }
    }

    if function_memory_data.is_empty() {
        return Ok(()); // No data to process
    }

    // Prepare all metrics for the consolidated summary page
    type MetricExtractor = Box<dyn Fn(&BenchmarkReport) -> Option<f64>>;
    let metrics: Vec<(&str, &str, &str, MetricExtractor)> = vec![
        (
            "cold_start_total_duration",
            "Cold Start Total Duration",
            "ms",
            Box::new(|r: &BenchmarkReport| {
                calculate_avg_from_cold_starts(&r.cold_starts, |cs| cs.total_cold_start_duration)
            }),
        ),
        (
            "cold_start_init_duration",
            "Cold Start Init Duration",
            "ms",
            Box::new(|r: &BenchmarkReport| {
                calculate_avg_from_cold_starts(&r.cold_starts, |cs| Some(cs.init_duration))
            }),
        ),
        (
            "warm_start_billed_duration",
            "Warm Start Billed Duration",
            "ms",
            Box::new(|r: &BenchmarkReport| {
                calculate_avg_from_warm_starts(&r.warm_starts, |ws| Some(ws.billed_duration as f64))
            }),
        ),
        (
            "warm_start_extension_overhead",
            "Warm Start Extension Overhead",
            "ms",
            Box::new(|r: &BenchmarkReport| {
                calculate_avg_from_warm_starts(&r.warm_starts, |ws| Some(ws.extension_overhead))
            }),
        ),
        (
            "resource_consumption",
            "Cost per Million Invocations",
            "GB-seconds per Million",
            Box::new(|r: &BenchmarkReport| {
                calculate_gb_seconds_per_million(&r.warm_starts, r.config.memory_size)
            }),
        ),
    ];

    // Collect all chart data for the single summary page
    let mut all_charts = Vec::new();

    for (metric_id, title, unit, extractor) in metrics {
        let chart_data = prepare_memory_scaling_chart_data(
            &function_memory_data,
            title,
            unit,
            metric_id,
            extractor,
        );
        all_charts.push(chart_data);
    }

    // Generate the consolidated summary page
    let summary_data = MemoryScalingSummaryData {
        title: format!("{} Memory Scaling Analysis", group_name),
        description: "Performance metrics across different memory configurations".to_string(),
        charts: all_charts,
        page_type: "memory_scaling_summary".to_string(),
    };

    generate_chart(
        &all_dir,
        png_dir.as_deref(),
        "summary",
        &ChartRenderData::MemoryScalingSummary(summary_data),
        &function_memory_data
            .values()
            .next()
            .unwrap()
            .values()
            .next()
            .unwrap()
            .config,
        suffix,
        screenshot_theme,
        pb,
        report_structure,
        group_name,
        "all",
        template_dir,
        base_url,
        local_browsing,
    )
    .await?;

    Ok(())
}

// Helper functions for metric calculations
fn calculate_avg_from_cold_starts<F>(cold_starts: &[ColdStartMetrics], extractor: F) -> Option<f64>
where
    F: Fn(&ColdStartMetrics) -> Option<f64>,
{
    let values: Vec<f64> = cold_starts.iter().filter_map(extractor).collect();

    if values.is_empty() {
        None
    } else {
        Some(values.iter().sum::<f64>() / values.len() as f64)
    }
}

fn calculate_avg_from_warm_starts<F>(warm_starts: &[WarmStartMetrics], extractor: F) -> Option<f64>
where
    F: Fn(&WarmStartMetrics) -> Option<f64>,
{
    let values: Vec<f64> = warm_starts.iter().filter_map(extractor).collect();

    if values.is_empty() {
        None
    } else {
        Some(values.iter().sum::<f64>() / values.len() as f64)
    }
}

fn calculate_gb_seconds_per_million(
    warm_starts: &[WarmStartMetrics],
    memory_mb: i32,
) -> Option<f64> {
    let avg_billed =
        calculate_avg_from_warm_starts(warm_starts, |ws| Some(ws.billed_duration as f64))?;
    let gb = memory_mb as f64 / 1024.0;
    let seconds = avg_billed / 1000.0;
    Some(gb * seconds * 1_000_000.0)
}

fn prepare_memory_scaling_chart_data<F>(
    function_memory_data: &BTreeMap<String, BTreeMap<i32, BenchmarkReport>>,
    title: &str,
    unit: &str,
    page_type: &str,
    value_extractor: F,
) -> MemoryScalingChartRenderData
where
    F: Fn(&BenchmarkReport) -> Option<f64>,
{
    let mut series = Vec::new();

    for (function_name, memory_reports) in function_memory_data {
        let mut points = Vec::new();

        for (memory_mb, report) in memory_reports {
            if let Some(value) = value_extractor(report) {
                points.push(MemoryScalingPoint {
                    memory_mb: *memory_mb,
                    value,
                });
            }
        }

        // Sort points by memory size
        points.sort_by_key(|p| p.memory_mb);

        if !points.is_empty() {
            series.push(MemoryScalingSeriesData {
                name: function_name.clone(),
                points,
            });
        }
    }

    // Sort series by function name for consistency
    series.sort_by(|a, b| a.name.cmp(&b.name));

    MemoryScalingChartRenderData {
        title: title.to_string(),
        subtitle: "Performance across memory configurations".to_string(),
        x_axis_label: "Memory Configuration".to_string(),
        y_axis_label: format!("{} ({})", title, unit),
        unit: unit.to_string(),
        series,
        page_type: page_type.to_string(),
        description: Some(get_memory_scaling_description(page_type).to_string()),
    }
}

fn get_memory_scaling_description(page_type: &str) -> &'static str {
    match page_type {
        "cold_start_total_duration" => "Shows how cold start times scale with memory allocation. Lower values indicate better cold start performance. The curve shape reveals whether additional memory provides diminishing returns.",
        "cold_start_init_duration" => "Initialization time for the Lambda runtime and dependencies. This metric helps identify if your initialization is CPU-bound (improves with memory) or I/O-bound (plateaus early).",
        "warm_start_billed_duration" => "The duration AWS bills for warm invocations. This directly impacts cost and helps find the optimal memory configuration for your workload.",
        "warm_start_extension_overhead" => "Performance impact of Lambda Extensions (e.g., observability agents). Shows how extension overhead scales with available resources.",
        "resource_consumption" => "Cost efficiency measured in GB-seconds per million invocations. Lower values mean more cost-efficient execution. Helps balance performance vs. cost when choosing memory allocation.",
        _ => "Performance metric across different memory configurations.",
    }
}

#[allow(clippy::too_many_arguments)]
pub async fn generate_reports_for_directory(
    input_directory: &str,
    output_directory: &str,
    custom_title: Option<&str>,
    suffix: &str,
    screenshot_theme: Option<&str>,
    pb: &ProgressBar,
    report_structure: &ReportStructure,
    current_group: &str,
    current_subgroup: &str,
    template_dir: Option<&String>,
    base_url: Option<&str>,
    local_browsing: bool,
) -> Result<()> {
    // Create output directory for PNG files if screenshots are enabled
    let png_dir = if screenshot_theme.is_some() {
        let dir = PathBuf::from(output_directory).join("png");
        fs::create_dir_all(&dir)?;
        Some(dir)
    } else {
        None
    };

    // Read all JSON files in the directory
    let mut results = Vec::new();
    let mut function_names = Vec::new();

    // Collect all files first
    let mut entries = Vec::new();
    for entry in fs::read_dir(input_directory)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) == Some("json") {
            entries.push((
                path.clone(),
                path.file_stem().unwrap().to_string_lossy().to_string(),
            ));
        }
    }

    // Sort entries by function name for consistent ordering
    entries.sort_by(|a, b| a.1.cmp(&b.1));

    // Process sorted entries
    for (path, name) in entries {
        let content = fs::read_to_string(&path)?;
        let report: BenchmarkReport = serde_json::from_str(&content)?;
        results.push(report);
        function_names.push(name);
    }

    if results.is_empty() {
        return Err(anyhow::anyhow!("No benchmark results found in '{}' or its subdirectories. Please check the directory path.", input_directory));
    }

    // Calculate statistics and generate charts
    let cold_init_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_init_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0)) // 5-tuple default
        })
        .collect();

    let cold_server_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_server_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    let client_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_client_stats(&report.client_measurements).unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    let server_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_warm_start_stats(&report.warm_starts, |m| m.duration)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    let cold_extension_overhead_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_extension_overhead_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    let cold_total_duration_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_total_duration_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    let memory_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_memory_stats(&report.warm_starts).unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    // --- Calculate New Platform Metrics Stats ---
    // Cold Start
    let cold_response_latency_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_response_latency_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let cold_response_duration_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_response_duration_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let cold_runtime_overhead_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_runtime_overhead_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let cold_runtime_done_duration_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_cold_start_runtime_done_metrics_duration_stats(&report.cold_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();

    // Warm Start (also for produced_bytes, though it could be cold or warm)
    let warm_response_latency_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_warm_start_response_latency_stats(&report.warm_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let warm_response_duration_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_warm_start_response_duration_stats(&report.warm_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let warm_runtime_overhead_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_warm_start_runtime_overhead_stats(&report.warm_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let warm_runtime_done_duration_stats: Vec<_> = results
        .iter()
        .map(|report| {
            calculate_warm_start_runtime_done_metrics_duration_stats(&report.warm_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    let produced_bytes_stats: Vec<_> = results // Assuming we take produced_bytes from warm starts, could be cold too.
        .iter()
        .map(|report| {
            calculate_warm_start_produced_bytes_stats(&report.warm_starts)
                .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
        })
        .collect();
    // --- End New Platform Metrics Stats ---

    // Generate cold start init duration chart if we have data
    if results.iter().any(|r| !r.cold_starts.is_empty()) {
        // Cold Start Init Duration - Combined Chart
        let cold_init_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_init_stats,
            &results,
            "Cold Start - Init Duration",
            "ms",
            "cold_init",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .map(|cs| cs.init_duration)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_init",
            &cold_init_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Server Duration - Combined Chart
        let cold_server_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_server_stats,
            &results,
            "Cold Start - Server Duration",
            "ms",
            "cold_server",
            |report| report.cold_starts.iter().map(|cs| cs.duration).collect(),
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_server",
            &cold_server_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Extension Overhead - Combined Chart
        let cold_ext_overhead_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_extension_overhead_stats,
            &results,
            "Cold Start - Extension Overhead",
            "ms",
            "cold_extension_overhead",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .map(|cs| cs.extension_overhead)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_extension_overhead",
            &cold_ext_overhead_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Total Duration - Combined Chart
        let cold_total_duration_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_total_duration_stats,
            &results,
            "Cold Start - Total Cold Start Duration",
            "ms",
            "cold_total_duration",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .filter_map(|cs| cs.total_cold_start_duration)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_total_duration",
            &cold_total_duration_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // --- Generate New Cold Start Platform Metric Charts (Now Combined) ---
        // Cold Start Response Latency - Combined Chart
        let cold_resp_latency_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_response_latency_stats,
            &results,
            "Cold Start - Response Latency",
            "ms",
            "cold_start_response_latency",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .filter_map(|cs| cs.response_latency_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_response_latency",
            &cold_resp_latency_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Response Duration - Combined Chart
        let cold_resp_duration_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_response_duration_stats,
            &results,
            "Cold Start - Response Duration",
            "ms",
            "cold_start_response_duration",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .filter_map(|cs| cs.response_duration_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_response_duration",
            &cold_resp_duration_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Runtime Overhead - Combined Chart
        let cold_runtime_overhead_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_runtime_overhead_stats,
            &results,
            "Cold Start - Runtime Overhead",
            "ms",
            "cold_start_runtime_overhead",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .filter_map(|cs| cs.runtime_overhead_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_runtime_overhead",
            &cold_runtime_overhead_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Runtime Done Duration - Combined Chart
        let cold_runtime_done_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_runtime_done_duration_stats,
            &results,
            "Cold Start - Runtime Done Duration",
            "ms",
            "cold_start_runtime_done_duration",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .filter_map(|cs| cs.runtime_done_metrics_duration_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_runtime_done_duration",
            &cold_runtime_done_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;
        // --- End New Cold Start Platform Metric Charts ---

        // --- Add Missing Cold Start Resource Metric Charts ---
        // Cold Start Memory Usage - Combined Chart
        let cold_memory_stats: Vec<_> = results
            .iter()
            .map(|report| {
                // Calculate memory stats for cold starts inline
                if report.cold_starts.is_empty() {
                    (0.0, 0.0, 0.0, 0.0, 0.0)
                } else {
                    let memory: Vec<f64> = report
                        .cold_starts
                        .iter()
                        .map(|cs| cs.max_memory_used as f64)
                        .collect();
                    let stats = crate::stats::calculate_stats(&memory);
                    (stats.mean, stats.p99, stats.p95, stats.p50, stats.std_dev)
                }
            })
            .collect();
        let cold_memory_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_memory_stats,
            &results,
            "Cold Start - Memory Usage",
            "MB",
            "cold_start_memory",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .map(|cs| cs.max_memory_used as f64)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_memory_usage",
            &cold_memory_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Cold Start Produced Bytes - Combined Chart
        let cold_produced_bytes_stats: Vec<_> = results
            .iter()
            .map(|report| {
                calculate_cold_start_produced_bytes_stats(&report.cold_starts)
                    .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
            })
            .collect();
        let cold_produced_bytes_combined = prepare_combined_chart_render_data(
            &function_names,
            &cold_produced_bytes_stats,
            &results,
            "Cold Start - Produced Bytes",
            "bytes",
            "cold_start_produced_bytes",
            |report| {
                report
                    .cold_starts
                    .iter()
                    .filter_map(|cs| cs.produced_bytes.map(|b| b as f64))
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "cold_start_produced_bytes",
            &cold_produced_bytes_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;
        // --- End Missing Cold Start Resource Metric Charts ---
    }

    // Generate client duration chart if we have data
    if results.iter().any(|r| !r.client_measurements.is_empty()) {
        // Warm Start Client Duration - Combined Chart (RENAMED for consistency)
        let client_duration_combined = prepare_combined_chart_render_data(
            &function_names,
            &client_stats,
            &results,
            "Warm Start - Client Duration",
            "ms",
            "warm_start_client_duration", // CHANGED: was "client"
            |report| {
                report
                    .client_measurements
                    .iter()
                    .map(|m| m.client_duration)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_client_duration", // CHANGED: was "client_duration"
            &client_duration_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;
    }

    // Generate server duration chart if we have data
    if results.iter().any(|r| !r.warm_starts.is_empty()) {
        // Warm Start Server Duration - Combined Chart (RENAMED for consistency)
        let server_duration_combined = prepare_combined_chart_render_data(
            &function_names,
            &server_stats,
            &results,
            "Warm Start - Server Duration",
            "ms",
            "warm_start_server_duration", // CHANGED: was "server"
            |report| report.warm_starts.iter().map(|ws| ws.duration).collect(),
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_server_duration", // CHANGED: was "server_duration"
            &server_duration_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Warm Start Extension Overhead - Combined Chart (RENAMED for consistency)
        let warm_extension_overhead_stats: Vec<_> = results
            .iter()
            .map(|report| {
                calculate_warm_start_stats(&report.warm_starts, |m| m.extension_overhead)
                    .unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0))
            })
            .collect();
        let ext_overhead_combined = prepare_combined_chart_render_data(
            &function_names,
            &warm_extension_overhead_stats,
            &results,
            "Warm Start - Extension Overhead",
            "ms",
            "warm_start_extension_overhead", // CHANGED: was "extension_overhead"
            |report| {
                report
                    .warm_starts
                    .iter()
                    .map(|ws| ws.extension_overhead)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_extension_overhead", // CHANGED: was "extension_overhead"
            &ext_overhead_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Warm Start Memory Usage - Combined Chart (RENAMED for consistency)
        let memory_combined = prepare_combined_chart_render_data(
            &function_names,
            &memory_stats,
            &results,
            "Warm Start - Memory Usage",
            "MB",
            "warm_start_memory", // CHANGED: was "memory"
            |report| {
                report
                    .warm_starts
                    .iter()
                    .map(|ws| ws.max_memory_used as f64)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_memory_usage", // CHANGED: was "memory_usage"
            &memory_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // --- Generate Complete Set of Warm Start Platform Metric Charts ---
        // Warm Start Response Latency - Combined Chart
        let warm_resp_latency_combined = prepare_combined_chart_render_data(
            &function_names,
            &warm_response_latency_stats,
            &results,
            "Warm Start - Response Latency",
            "ms",
            "warm_start_response_latency",
            |report| {
                report
                    .warm_starts
                    .iter()
                    .filter_map(|ws| ws.response_latency_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_response_latency",
            &warm_resp_latency_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Warm Start Response Duration - Combined Chart
        let warm_resp_duration_combined = prepare_combined_chart_render_data(
            &function_names,
            &warm_response_duration_stats,
            &results,
            "Warm Start - Response Duration",
            "ms",
            "warm_start_response_duration",
            |report| {
                report
                    .warm_starts
                    .iter()
                    .filter_map(|ws| ws.response_duration_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_response_duration",
            &warm_resp_duration_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Warm Start Runtime Overhead - Combined Chart
        let warm_runtime_overhead_combined = prepare_combined_chart_render_data(
            &function_names,
            &warm_runtime_overhead_stats,
            &results,
            "Warm Start - Runtime Overhead",
            "ms",
            "warm_start_runtime_overhead",
            |report| {
                report
                    .warm_starts
                    .iter()
                    .filter_map(|ws| ws.runtime_overhead_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_runtime_overhead",
            &warm_runtime_overhead_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Warm Start Runtime Done Duration - Combined Chart
        let warm_runtime_done_combined = prepare_combined_chart_render_data(
            &function_names,
            &warm_runtime_done_duration_stats,
            &results,
            "Warm Start - Runtime Done Duration",
            "ms",
            "warm_start_runtime_done_duration",
            |report| {
                report
                    .warm_starts
                    .iter()
                    .filter_map(|ws| ws.runtime_done_metrics_duration_ms)
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_runtime_done_duration",
            &warm_runtime_done_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;

        // Warm Start Produced Bytes - Combined Chart (RENAMED for consistency)
        let produced_bytes_combined = prepare_combined_chart_render_data(
            &function_names,
            &produced_bytes_stats,
            &results,
            "Warm Start - Produced Bytes",
            "bytes",
            "warm_start_produced_bytes", // CHANGED: was "produced_bytes"
            |report| {
                report
                    .warm_starts
                    .iter()
                    .filter_map(|ws| ws.produced_bytes.map(|b| b as f64))
                    .collect()
            },
        );
        generate_chart(
            &PathBuf::from(output_directory),
            png_dir.as_deref(),
            "warm_start_produced_bytes", // CHANGED: was "produced_bytes"
            &produced_bytes_combined,
            &results[0].config,
            suffix,
            screenshot_theme,
            pb,
            report_structure,
            current_group,
            current_subgroup,
            template_dir,
            base_url,
            local_browsing,
        )
        .await?;
        // --- End Complete Set of Warm Start Platform Metric Charts ---
    }

    // Generate Summary Page
    let summary_combined = prepare_summary_chart_render_data(
        &function_names,
        &results,
        custom_title.unwrap_or("Performance Summary"),
    );
    generate_chart(
        &PathBuf::from(output_directory),
        png_dir.as_deref(),
        "summary",
        &summary_combined,
        &results[0].config,
        suffix,
        screenshot_theme,
        pb,
        report_structure,
        current_group,
        current_subgroup,
        template_dir,
        base_url,
        local_browsing,
    )
    .await?;

    Ok(())
}

fn prepare_bar_chart_render_data(
    function_names: &[String],
    stats: &[(f64, f64, f64, f64, f64)], // Expects (avg, p99, p95, p50, std_dev)
    title: &str,
    unit: &str,
    page_type: &str,
) -> BarChartRenderData {
    let series_render_data = function_names
        .iter()
        .zip(stats.iter())
        .map(|(name, &(avg, p99, p95, p50, _std_dev))| {
            // Use Decimal for precise rounding to 3 decimal places
            let rounded_avg = Decimal::from_f64(avg)
                .unwrap_or_default()
                .round_dp(3)
                .to_f64()
                .unwrap_or(0.0);
            let rounded_p50 = Decimal::from_f64(p50)
                .unwrap_or_default()
                .round_dp(3)
                .to_f64()
                .unwrap_or(0.0);
            let rounded_p95 = Decimal::from_f64(p95)
                .unwrap_or_default()
                .round_dp(3)
                .to_f64()
                .unwrap_or(0.0);
            let rounded_p99 = Decimal::from_f64(p99)
                .unwrap_or_default()
                .round_dp(3)
                .to_f64()
                .unwrap_or(0.0);

            SeriesRenderData {
                name: name.clone(),
                values: vec![
                    rounded_avg, // AVG
                    rounded_p50, // P50
                    rounded_p95, // P95
                    rounded_p99, // P99
                ],
            }
        })
        .collect();

    BarChartRenderData {
        title: title.to_string(),
        unit: unit.to_string(),
        y_axis_categories: vec![
            "AVG".to_string(),
            "P50".to_string(),
            "P95".to_string(),
            "P99".to_string(),
        ],
        series: series_render_data,
        page_type: page_type.to_string(),
        description: get_metric_description(page_type).map(|s| s.to_string()),
    }
}

/// Prepares a combined chart with both bar chart (aggregates) and line chart (time series) data
fn prepare_combined_chart_render_data(
    function_names: &[String],
    stats: &[(f64, f64, f64, f64, f64)], // Expects (avg, p99, p95, p50, std_dev)
    results: &[BenchmarkReport],
    title: &str,
    unit: &str,
    page_type: &str,
    value_extractor: impl Fn(&BenchmarkReport) -> Vec<f64>,
) -> ChartRenderData {
    // Prepare bar chart data
    let bar_data = prepare_bar_chart_render_data(function_names, stats, title, unit, page_type);

    // Prepare line chart data for the same metric over time
    let line_title = format!("{} - Over Time", title);
    let line_data = prepare_metric_line_chart_render_data(
        results,
        function_names,
        &line_title,
        unit,
        page_type,
        value_extractor,
    );

    ChartRenderData::Combined {
        bar: Box::new(bar_data),
        line: Box::new(line_data),
    }
}

/// Prepares line chart data for a specific metric using a value extraction function
fn prepare_metric_line_chart_render_data(
    results: &[BenchmarkReport],
    function_names: &[String],
    title: &str,
    unit: &str,
    page_type: &str,
    value_extractor: impl Fn(&BenchmarkReport) -> Vec<f64>,
) -> LineChartRenderData {
    let gap = 5; // Gap between series
    let mut current_offset = 0;
    let mut max_x = 0;

    let series_render_data: Vec<LineSeriesRenderData> = function_names
        .iter()
        .zip(results.iter())
        .map(|(name, report)| {
            let x_offset = current_offset;

            // Extract values for this specific metric
            let values = value_extractor(report);
            let num_points = values.len();

            current_offset += num_points + gap; // Update offset for next series
            if current_offset > gap {
                // Update max_x only if points were added
                max_x = current_offset - gap;
            } else {
                // If a series has 0 points, don't let max_x be negative or zero based on gap
                max_x = max_x.max(0);
            }

            let mut points_sum = 0.0;
            let points_data: Vec<ScatterPoint> = values
                .iter()
                .enumerate()
                .map(|(index, &value)| {
                    let duration = Decimal::from_f64(value)
                        .unwrap_or_default()
                        .round_dp(2)
                        .to_f64()
                        .unwrap_or(0.0);
                    points_sum += duration;
                    ScatterPoint {
                        x: x_offset + index,
                        y: duration,
                    }
                })
                .collect();

            let mean = if num_points > 0 {
                let mean_decimal = Decimal::from_f64(points_sum / num_points as f64)
                    .unwrap_or_default()
                    .round_dp(2);
                Some(mean_decimal.to_f64().unwrap_or(0.0))
            } else {
                None
            };

            LineSeriesRenderData {
                name: name.clone(),
                points: points_data,
                mean,
            }
        })
        .collect();

    LineChartRenderData {
        title: title.to_string(),
        x_axis_label: "Test Sequence".to_string(),
        y_axis_label: format!("Duration ({})", unit),
        unit: unit.to_string(),
        series: series_render_data,
        total_x_points: max_x,
        page_type: format!("{}_time", page_type),
        description: get_metric_description(page_type).map(|s| s.to_string()),
    }
}

/// Gets the AWS-documentation-based description for a metric type
/// These descriptions are based on official AWS Lambda documentation and help users understand
/// what each metric represents in terms of Lambda performance characteristics.
fn get_metric_description(page_type: &str) -> Option<&'static str> {
    match page_type {
        // Cold Start Metrics
        "cold_init" => Some(
            "The time AWS Lambda spends initializing your function during a cold start. This includes downloading code/layers, \
            initializing the runtime, and running initialization code outside the main handler. Cold starts occur when Lambda \
            creates a new execution environment (first invocation or after inactivity). The Init phase is limited to 10 seconds \
            for standard functions. Measured in milliseconds."
        ),
        "cold_server" => Some(
            "The time your function code spends processing an event during a cold start invocation. This measures only the \
            execution time of your function handler logic, excluding the initialization overhead. This is equivalent to the \
            AWS CloudWatch 'Duration' metric for cold start invocations. Measured in milliseconds."
        ),
        "cold_extension_overhead" => Some(
            "The additional time consumed by Lambda extensions after your function code completes during cold start. Extensions \
            are external processes that run alongside your function (e.g., monitoring, security tools). This is part of the \
            AWS CloudWatch 'PostRuntimeExtensionsDuration' metric. Higher values indicate extensions are impacting performance. \
            Measured in milliseconds."
        ),
        "cold_total_duration" => Some(
            "The complete end-to-end time for a cold start invocation, including initialization, function execution, and \
            extension processing. This represents the total latency experienced when Lambda creates a new execution environment. \
            This is the sum of Init Duration + Function Duration + Extension Overhead. Measured in milliseconds."
        ),
        "cold_start_response_latency" => Some(
            "The time between when the Lambda service receives an invocation request and when the response becomes available \
            during cold starts. This is measured at the platform level and includes network and service processing overhead \
            beyond your function's execution time. Part of the platform.runtimeDone metrics. Measured in milliseconds."
        ),
        "cold_start_response_duration" => Some(
            "The time taken by the Lambda runtime to prepare and send the response back to the caller during cold start invocations. \
            This measures the overhead of response serialization and transmission at the platform level. Part of the \
            platform.runtimeDone metrics from AWS Lambda's internal instrumentation. Measured in milliseconds."
        ),
        "cold_start_runtime_overhead" => Some(
            "The additional time consumed by the Lambda runtime infrastructure beyond your function's execution time during \
            cold starts. This includes runtime initialization, request/response handling, and internal Lambda service overhead. \
            Derived from platform.runtimeDone metrics that provide insight into Lambda's internal performance. Measured in milliseconds."
        ),
        "cold_start_runtime_done_duration" => Some(
            "The total time measured by Lambda's runtime from invocation start to completion during cold starts. This is an \
            internal AWS metric that captures the complete runtime processing time including function execution and runtime \
            overhead. Part of the platform.runtimeDone telemetry that provides deep runtime insights. Measured in milliseconds."
        ),

        // Warm Start Metrics  
        "warm_start_client_duration" => Some(
            "The end-to-end response time measured from the client perspective during warm start invocations. This includes \
            network latency, Lambda service processing time, and function execution time. Warm starts reuse existing execution \
            environments, skipping the Init phase, resulting in significantly lower latency than cold starts. Measured in milliseconds."
        ),
        "warm_start_server_duration" => Some(
            "The time your function code spends processing an event during warm start invocations. Since warm starts reuse \
            existing execution environments, this excludes initialization overhead and focuses purely on your application logic \
            performance. This corresponds to the AWS CloudWatch 'Duration' metric for warm invocations. Measured in milliseconds."
        ),
        "warm_start_extension_overhead" => Some(
            "The additional time consumed by Lambda extensions after your function code completes during warm starts. Even though \
            extensions are already initialized in warm starts, they may still perform post-invocation processing (e.g., sending \
            telemetry, cleanup). This is the AWS CloudWatch 'PostRuntimeExtensionsDuration' metric. Measured in milliseconds."
        ),
        "warm_start_response_latency" => Some(
            "The time between when the Lambda service receives an invocation request and when the response becomes available \
            during warm start invocations. Since warm starts skip initialization, this latency is typically much lower than \
            cold starts. Part of the platform.runtimeDone metrics providing platform-level insights. Measured in milliseconds."
        ),
        "warm_start_response_duration" => Some(
            "The time taken by the Lambda runtime to prepare and send the response back to the caller during warm start invocations. \
            This measures response processing overhead at the platform level for reused execution environments. Part of the \
            platform.runtimeDone metrics from AWS Lambda's internal instrumentation. Measured in milliseconds."
        ),
        "warm_start_runtime_overhead" => Some(
            "The additional time consumed by the Lambda runtime infrastructure beyond your function's execution time during \
            warm starts. While typically lower than cold starts, this still includes request/response handling and internal \
            service overhead. Derived from platform.runtimeDone metrics for runtime performance analysis. Measured in milliseconds."
        ),
        "warm_start_runtime_done_duration" => Some(
            "The total time measured by Lambda's runtime from invocation start to completion during warm starts. This internal \
            AWS metric captures the complete runtime processing time for reused execution environments. Part of the \
            platform.runtimeDone telemetry providing detailed runtime performance insights. Measured in milliseconds."
        ),

        // Resource Metrics
        "cold_start_memory" => Some(
            "The maximum amount of memory used by your Lambda function during cold start execution. This is reported by AWS CloudWatch \
            as 'MaxMemoryUsed' and helps you understand actual memory consumption versus allocated memory during initialization. \
            Cold starts may use slightly more memory due to runtime loading. Measured in megabytes (MB)."
        ),
        "warm_start_memory" => Some(
            "The maximum amount of memory used by your Lambda function during warm start execution. This is reported by AWS CloudWatch \
            as 'MaxMemoryUsed' and helps you understand actual memory consumption versus allocated memory in steady-state operations. \
            Optimizing memory allocation can improve both performance and cost-effectiveness. Memory impacts CPU allocation proportionally. Measured in megabytes (MB)."
        ),
        "cold_start_produced_bytes" => Some(
            "The number of bytes produced by your Lambda function during cold start execution, typically representing the size of the \
            response payload. This metric helps track data transfer during initialization scenarios and can indicate response \
            serialization efficiency during cold starts. Part of the platform.runtimeDone metrics. Measured in bytes."
        ),
        "warm_start_produced_bytes" => Some(
            "The number of bytes produced by your Lambda function during warm start execution, typically representing the size of the \
            response payload. This metric helps track data transfer and can indicate the efficiency of your response \
            serialization in steady-state operations. Large responses may impact performance and incur additional data transfer costs. Part of the \
            platform.runtimeDone metrics. Measured in bytes."
        ),

        _ => None,
    }
}

/// Prepares summary chart data containing avg values for selected key metrics
fn prepare_summary_chart_render_data(
    function_names: &[String],
    results: &[BenchmarkReport],
    title: &str,
) -> ChartRenderData {
    let metrics = vec![
        // Key Cold Start Metrics
        (
            "cold-start-total-duration",
            "Cold Start Total Duration",
            "ms",
            collect_avg_values(results, |r| {
                r.cold_starts
                    .iter()
                    .filter_map(|cs| cs.total_cold_start_duration)
                    .collect()
            }),
        ),
        (
            "cold-start-init",
            "Cold Start Init Duration",
            "ms",
            collect_avg_values(results, |r| {
                r.cold_starts.iter().map(|cs| cs.init_duration).collect()
            }),
        ),
        (
            "cold-start-server",
            "Cold Start Server Duration",
            "ms",
            collect_avg_values(results, |r| {
                r.cold_starts.iter().map(|cs| cs.duration).collect()
            }),
        ),
        (
            "cold-start-response-latency",
            "Cold Start Response Latency",
            "ms",
            collect_avg_values(results, |r| {
                r.cold_starts
                    .iter()
                    .filter_map(|cs| cs.response_latency_ms)
                    .collect()
            }),
        ),
        // Key Warm Start Metrics
        (
            "warm-start-client-duration",
            "Warm Start Client Duration",
            "ms",
            collect_avg_values(results, |r| {
                r.client_measurements
                    .iter()
                    .map(|cm| cm.client_duration)
                    .collect()
            }),
        ),
        (
            "warm-start-server-duration",
            "Warm Start Server Duration",
            "ms",
            collect_avg_values(results, |r| {
                r.warm_starts.iter().map(|ws| ws.duration).collect()
            }),
        ),
        (
            "warm-start-response-latency",
            "Warm Start Response Latency",
            "ms",
            collect_avg_values(results, |r| {
                r.warm_starts
                    .iter()
                    .filter_map(|ws| ws.response_latency_ms)
                    .collect()
            }),
        ),
        // Resource Metrics
        (
            "warm-start-memory-usage",
            "Warm Start Memory Usage",
            "MB",
            collect_avg_values(results, |r| {
                r.warm_starts
                    .iter()
                    .map(|ws| ws.max_memory_used as f64)
                    .collect()
            }),
        ),
    ];

    let summary_metrics: Vec<SummaryMetricData> = metrics
        .into_iter()
        .map(|(id, title, unit, avg_values)| {
            let data: Vec<SummarySeriesData> = function_names
                .iter()
                .zip(avg_values.iter())
                .map(|(name, &value)| SummarySeriesData {
                    name: name.clone(),
                    value,
                })
                .collect();

            SummaryMetricData {
                id: id.to_string(),
                title: title.to_string(),
                unit: unit.to_string(),
                link: format!("../{}/", id),
                data,
            }
        })
        .collect();

    let summary_data = SummaryChartRenderData {
        title: title.to_string(),
        description: "Overview of key performance metrics across all functions".to_string(),
        metrics: summary_metrics,
        page_type: "summary".to_string(),
    };

    ChartRenderData::Summary(summary_data)
}

/// Helper function to collect average values for a metric across all results
fn collect_avg_values(
    results: &[BenchmarkReport],
    value_extractor: impl Fn(&BenchmarkReport) -> Vec<f64>,
) -> Vec<f64> {
    results
        .iter()
        .map(|report| {
            let values = value_extractor(report);
            if values.is_empty() {
                0.0
            } else {
                let sum: f64 = values.iter().sum();
                let avg = sum / values.len() as f64;
                // Round to 3 decimal places using Decimal
                Decimal::from_f64(avg)
                    .unwrap_or_default()
                    .round_dp(3)
                    .to_f64()
                    .unwrap_or(0.0)
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{BenchmarkConfig, BenchmarkReport, ClientMetrics}; // Removed unused ColdStartMetrics, EnvVar, WarmStartMetrics
    use std::path::PathBuf;

    #[test]
    fn test_snake_to_kebab() {
        assert_eq!(snake_to_kebab("hello_world"), "hello-world");
        assert_eq!(snake_to_kebab("another_test_case"), "another-test-case");
        assert_eq!(snake_to_kebab("single"), "single");
        assert_eq!(snake_to_kebab(""), "");
        assert_eq!(snake_to_kebab("_leading_underscore"), "-leading-underscore");
        assert_eq!(
            snake_to_kebab("trailing_underscore_"),
            "trailing-underscore-"
        );
    }

    #[test]
    fn test_calculate_base_path_no_base_url() {
        let _path0 = PathBuf::from(""); // Represents being at the root before any group/subgroup
        let _path1 = PathBuf::from("group1");
        let _path2 = PathBuf::from("group1/subgroupA");
        let _path3 = PathBuf::from("group1/subgroupA/chart_type"); // Max depth for calculation logic
        let _path4 = PathBuf::from("group1/subgroupA/chart_type/another_level");

        // The logic in calculate_base_path adds 1 to component count, then caps at 3.
        // current_dir is the output_directory/group_name/subgroup_name
        // The actual HTML file will be one level deeper (e.g., .../chart_name/index.html)
        // So, if current_dir is "group1/subgroupA", components = 2. depth = min(2+1, 3) = 3. Result: "../../../"

        // If html_dir is root of output (e.g. "output_dir")
        // This case is not directly hit by generate_chart's usage, as html_dir is usually deeper.
        // However, testing the function directly:
        // If current_dir is "output_dir", components = 1. depth = min(1+1, 3) = 2. Result: "../../"
        assert_eq!(
            calculate_base_path(&PathBuf::from("output_dir"), None).unwrap(),
            "../../"
        );

        // If html_dir is "output_dir/group1"
        // This means the chart's index.html will be at "output_dir/group1/chart_name/index.html"
        // current_dir for calculate_base_path is "output_dir/group1"
        // components = 2. depth = min(2+1, 3) = 3. Result: "../../../"
        assert_eq!(
            calculate_base_path(&PathBuf::from("output_dir/group1"), None).unwrap(),
            "../../../"
        );

        // If html_dir is "output_dir/group1/subgroupA" (typical case for generate_chart)
        // Chart's index.html will be at "output_dir/group1/subgroupA/chart_name/index.html"
        // current_dir for calculate_base_path is "output_dir/group1/subgroupA"
        // components = 3. depth = min(3+1, 3) = 3. Result: "../../../"
        assert_eq!(
            calculate_base_path(&PathBuf::from("output_dir/group1/subgroupA"), None).unwrap(),
            "../../../"
        );

        // Test with a path that would exceed max depth if not capped
        assert_eq!(
            calculate_base_path(&PathBuf::from("output_dir/group1/subgroupA/extra"), None).unwrap(),
            "../../../"
        );
    }

    #[test]
    fn test_calculate_base_path_with_base_url() {
        let current_dir = PathBuf::from("any/path");
        assert_eq!(
            calculate_base_path(&current_dir, Some("http://example.com")).unwrap(),
            "http://example.com/"
        );
        assert_eq!(
            calculate_base_path(&current_dir, Some("http://example.com/")).unwrap(),
            "http://example.com/"
        );
        assert_eq!(
            calculate_base_path(&current_dir, Some("https://cdn.test/reports/")).unwrap(),
            "https://cdn.test/reports/"
        );
        assert_eq!(calculate_base_path(&current_dir, Some("")).unwrap(), "/"); // Empty base_url becomes "/"
    }

    #[test]
    fn test_prepare_bar_chart_render_data() {
        let function_names = vec!["func_a".to_string(), "func_b".to_string()];
        let stats = vec![
            (10.5126, 15.1001, 14.2999, 12.3456, 1.0), // avg, p99, p95, p50, std_dev for func_a
            (20.0004, 25.5555, 24.0011, 22.5678, 1.5), // avg, p99, p95, p50, std_dev for func_b
        ];
        let title = "Test Bar Chart";
        let unit = "ms";
        let page_type = "test_bar";

        let render_data =
            prepare_bar_chart_render_data(&function_names, &stats, title, unit, page_type);

        assert_eq!(render_data.title, title);
        assert_eq!(render_data.unit, unit);
        assert_eq!(render_data.page_type, page_type);
        assert_eq!(render_data.description, None); // test_bar doesn't have a description
        assert_eq!(
            render_data.y_axis_categories,
            vec!["AVG", "P50", "P95", "P99"]
        );

        assert_eq!(render_data.series.len(), 2);
        // Series 1 (func_a) - avg=10.513, p50=12.346, p95=14.300, p99=15.100
        assert_eq!(render_data.series[0].name, "func_a");
        assert_eq!(
            render_data.series[0].values,
            vec![10.513, 12.346, 14.300, 15.100] // Expected rounded values
        );
        // Series 2 (func_b) - avg=20.000, p50=22.568, p95=24.001, p99=25.556
        assert_eq!(render_data.series[1].name, "func_b");
        assert_eq!(
            render_data.series[1].values,
            vec![20.000, 22.568, 24.001, 25.556] // Expected rounded values
        );
    }

    #[test]
    fn test_prepare_line_chart_render_data() {
        let func_a_metrics = vec![
            ClientMetrics {
                timestamp: "t1".to_string(),
                client_duration: 10.12,
                memory_size: 128,
            },
            ClientMetrics {
                timestamp: "t2".to_string(),
                client_duration: 12.34,
                memory_size: 128,
            },
        ];
        let func_b_metrics = vec![ClientMetrics {
            timestamp: "t3".to_string(),
            client_duration: 20.56,
            memory_size: 128,
        }];

        let results = vec![
            BenchmarkReport {
                config: BenchmarkConfig {
                    function_name: "func_a".to_string(),
                    memory_size: 128,
                    concurrent_invocations: 1,
                    number: 1,
                    timestamp: "".to_string(),
                    runtime: None,
                    architecture: None,
                    environment: vec![],
                },
                cold_starts: vec![],
                warm_starts: vec![],
                client_measurements: func_a_metrics,
            },
            BenchmarkReport {
                config: BenchmarkConfig {
                    function_name: "func_b".to_string(),
                    memory_size: 128,
                    concurrent_invocations: 1,
                    number: 1,
                    timestamp: "".to_string(),
                    runtime: None,
                    architecture: None,
                    environment: vec![],
                },
                cold_starts: vec![],
                warm_starts: vec![],
                client_measurements: func_b_metrics,
            },
        ];
        let function_names = vec!["func_a".to_string(), "func_b".to_string()];
        let title = "Test Line Chart";
        let unit = "ms";
        let page_type = "test_line";

        let render_data = prepare_metric_line_chart_render_data(
            &results,
            &function_names,
            title,
            unit,
            page_type,
            |report| {
                report
                    .client_measurements
                    .iter()
                    .map(|m| m.client_duration)
                    .collect()
            },
        );

        assert_eq!(render_data.title, title);
        assert_eq!(render_data.unit, unit);
        assert_eq!(render_data.page_type, format!("{}_time", page_type));
        assert_eq!(render_data.description, None); // test_line doesn't have a description
        assert_eq!(render_data.x_axis_label, "Test Sequence");
        assert_eq!(render_data.y_axis_label, "Duration (ms)");

        assert_eq!(render_data.series.len(), 2);

        // Series 1 (func_a)
        assert_eq!(render_data.series[0].name, "func_a");
        assert_eq!(render_data.series[0].points.len(), 2);
        assert_eq!(render_data.series[0].points[0].x, 0); // offset 0, index 0
        assert_eq!(render_data.series[0].points[0].y, 10.12);
        assert_eq!(render_data.series[0].points[1].x, 1); // offset 0, index 1
        assert_eq!(render_data.series[0].points[1].y, 12.34);
        assert_eq!(render_data.series[0].mean, Some(11.23)); // (10.12 + 12.34) / 2 = 11.23

        // Series 2 (func_b)
        // current_offset for func_b starts at num_points_func_a (2) + gap (5) = 7
        assert_eq!(render_data.series[1].name, "func_b");
        assert_eq!(render_data.series[1].points.len(), 1);
        assert_eq!(render_data.series[1].points[0].x, 7); // offset 7, index 0
        assert_eq!(render_data.series[1].points[0].y, 20.56);
        assert_eq!(render_data.series[1].mean, Some(20.56));

        // total_x_points = last_offset (7) + num_points_func_b (1) - gap (if series added)
        // current_offset after func_a = 2 (len) + 5 (gap) = 7
        // max_x after func_a = 7 - 5 = 2
        // current_offset after func_b = 7 (prev_offset) + 1 (len) + 5 (gap) = 13
        // max_x after func_b = 13 - 5 = 8
        assert_eq!(render_data.total_x_points, 8);
    }

    #[test]
    fn test_prepare_line_chart_render_data_empty_measurements() {
        let results = vec![BenchmarkReport {
            config: BenchmarkConfig {
                function_name: "func_a".to_string(),
                memory_size: 128,
                concurrent_invocations: 1,
                number: 1,
                timestamp: "".to_string(),
                runtime: None,
                architecture: None,
                environment: vec![],
            },
            cold_starts: vec![],
            warm_starts: vec![],
            client_measurements: vec![], // Empty
        }];
        let function_names = vec!["func_a".to_string()];
        let render_data = prepare_metric_line_chart_render_data(
            &results,
            &function_names,
            "Empty",
            "ms",
            "empty_line",
            |report| {
                report
                    .client_measurements
                    .iter()
                    .map(|m| m.client_duration)
                    .collect()
            },
        );

        assert_eq!(render_data.series.len(), 1);
        assert_eq!(render_data.series[0].name, "func_a");
        assert_eq!(render_data.series[0].points.len(), 0);
        assert_eq!(render_data.series[0].mean, None);
        assert_eq!(render_data.total_x_points, 0); // max_x remains 0 if no points
    }

    #[test]
    fn test_metric_descriptions() {
        // Test known cold start metric types have descriptions
        assert!(get_metric_description("cold_init").is_some());
        assert!(get_metric_description("cold_server").is_some());
        assert!(get_metric_description("cold_start_memory").is_some());
        assert!(get_metric_description("cold_start_produced_bytes").is_some());

        // Test known warm start metric types have descriptions
        assert!(get_metric_description("warm_start_client_duration").is_some());
        assert!(get_metric_description("warm_start_server_duration").is_some());
        assert!(get_metric_description("warm_start_extension_overhead").is_some());
        assert!(get_metric_description("warm_start_memory").is_some());
        assert!(get_metric_description("warm_start_produced_bytes").is_some());

        // Test unknown metric type returns None
        assert!(get_metric_description("unknown_metric").is_none());

        // Test that bar chart includes description for known metric types
        let function_names = vec!["test_func".to_string()];
        let stats = vec![(10.0, 15.0, 14.0, 12.0, 1.0)];

        let bar_data = prepare_bar_chart_render_data(
            &function_names,
            &stats,
            "Cold Start - Init Duration",
            "ms",
            "cold_init",
        );

        assert!(bar_data.description.is_some());
        assert!(bar_data
            .description
            .unwrap()
            .contains("AWS Lambda spends initializing"));
    }
}