sonda-core 0.7.0

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

pub mod validate;

use std::collections::HashMap;

use crate::encoder::EncoderConfig;
use crate::generator::{CsvColumnSpec, GeneratorConfig, LogGeneratorConfig};
use crate::sink::SinkConfig;
use crate::{ConfigError, SondaError};

/// Gap window configuration — a recurring silent period within a scenario.
///
/// During a gap the scheduler emits no events. The gap repeats on a fixed
/// cycle defined by `every`, and each instance lasts for `for`.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct GapConfig {
    /// How often the gap recurs (e.g. `"2m"`).
    pub every: String,
    /// How long each gap lasts (e.g. `"20s"`). Must be less than `every`.
    pub r#for: String,
}

/// Strategy for generating unique label values during a cardinality spike.
///
/// Determines how the spike window produces distinct values for the injected
/// label key on each tick.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
#[cfg_attr(feature = "config", serde(rename_all = "snake_case"))]
pub enum SpikeStrategy {
    /// Sequential counter: `prefix + (tick % cardinality)`.
    ///
    /// Produces deterministic, predictable label values without needing a seed.
    #[default]
    Counter,
    /// Deterministic random: SplitMix64 hash of `seed ^ tick`, formatted as hex.
    ///
    /// Produces label values that look random but are reproducible given the
    /// same seed.
    Random,
}

/// Configuration for a cardinality spike — a recurring window that injects
/// dynamic label values to simulate cardinality explosions.
///
/// During the spike window, a label key is injected with one of `cardinality`
/// unique values per tick. Outside the window, the label key is absent.
///
/// # Example YAML
///
/// ```yaml
/// cardinality_spikes:
///   - label: pod_name
///     every: 2m
///     for: 30s
///     cardinality: 500
///     strategy: counter
///     prefix: "pod-"
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct CardinalitySpikeConfig {
    /// The label key to inject during the spike window.
    ///
    /// Must be a valid Prometheus label key: `[a-zA-Z_][a-zA-Z0-9_]*`.
    pub label: String,
    /// How often the spike recurs (e.g. `"2m"`).
    pub every: String,
    /// How long each spike lasts (e.g. `"30s"`). Must be less than `every`.
    pub r#for: String,
    /// Number of unique label values generated during the spike.
    ///
    /// Must be greater than zero.
    pub cardinality: u64,
    /// Strategy for generating unique label values.
    ///
    /// Defaults to `counter` if not specified.
    #[cfg_attr(feature = "config", serde(default))]
    pub strategy: SpikeStrategy,
    /// Optional prefix for generated label values.
    ///
    /// Defaults to `"{label}_"` when not specified.
    #[cfg_attr(feature = "config", serde(default))]
    pub prefix: Option<String>,
    /// Optional RNG seed for the `random` strategy.
    ///
    /// Ignored for the `counter` strategy.
    #[cfg_attr(feature = "config", serde(default))]
    pub seed: Option<u64>,
}

/// Strategy for generating dynamic label values.
///
/// Determines how a [`DynamicLabelConfig`] produces per-tick values for the
/// label key.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
#[cfg_attr(feature = "config", serde(untagged))]
pub enum DynamicLabelStrategy {
    /// Cycle through an explicit list of values.
    ///
    /// The label value at each tick is `values[tick % values.len()]`.
    /// Cardinality is implicit (length of the list).
    ValuesList {
        /// The explicit list of label values to cycle through.
        values: Vec<String>,
    },
    /// Sequential counter: `"{prefix}{tick % cardinality}"`.
    ///
    /// Produces deterministic, predictable label values that cycle through
    /// `cardinality` distinct values indefinitely.
    Counter {
        /// Prefix prepended to the counter index (e.g. `"host-"` produces
        /// `"host-0"`, `"host-1"`, ...).
        #[cfg_attr(feature = "config", serde(default))]
        prefix: Option<String>,
        /// Number of unique label values in the cycle. Must be greater than zero.
        cardinality: u64,
    },
}

/// Configuration for a dynamic label — an always-on rotating label value
/// attached to every emitted event.
///
/// Unlike [`CardinalitySpikeConfig`], dynamic labels are not time-windowed:
/// they appear in every event for the lifetime of the scenario. This enables
/// simulating a stable fleet of N distinct sources (e.g., 10 hostnames, 5 pod
/// names) without a spike/window concept.
///
/// # Example YAML (counter strategy)
///
/// ```yaml
/// dynamic_labels:
///   - key: hostname
///     prefix: "host-"
///     cardinality: 10
/// ```
///
/// # Example YAML (values list strategy)
///
/// ```yaml
/// dynamic_labels:
///   - key: region
///     values: [us-east-1, us-west-2, eu-west-1]
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct DynamicLabelConfig {
    /// The label key to attach to every event.
    ///
    /// Must be a valid Prometheus label key: `[a-zA-Z_][a-zA-Z0-9_]*`.
    pub key: String,
    /// The strategy for generating per-tick label values.
    ///
    /// Deserialized via untagged enum: provide either `values: [...]` or
    /// `prefix: / cardinality:` fields directly alongside `key:`.
    #[cfg_attr(feature = "config", serde(flatten))]
    pub strategy: DynamicLabelStrategy,
}

/// Burst window configuration — a recurring high-rate period within a scenario.
///
/// During a burst the event rate is multiplied by `multiplier`. The burst
/// repeats on a fixed cycle defined by `every`, and each instance lasts for `for`.
///
/// If a gap and burst overlap in time, the gap takes priority and no events
/// are emitted.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct BurstConfig {
    /// How often the burst recurs (e.g. `"10s"`).
    pub every: String,
    /// How long each burst lasts (e.g. `"2s"`). Must be less than `every`.
    pub r#for: String,
    /// Rate multiplier during the burst (must be strictly positive).
    pub multiplier: f64,
}

#[cfg(feature = "config")]
fn default_encoder() -> EncoderConfig {
    EncoderConfig::PrometheusText { precision: None }
}

#[cfg(feature = "config")]
fn default_log_encoder() -> EncoderConfig {
    EncoderConfig::JsonLines { precision: None }
}

#[cfg(feature = "config")]
fn default_sink() -> SinkConfig {
    SinkConfig::Stdout
}

/// Shared schedule and delivery fields common to all signal types.
///
/// Both [`ScenarioConfig`] (metrics) and [`LogScenarioConfig`] (logs) embed
/// this struct via `#[serde(flatten)]`. It contains every field that is
/// identical across signal types — everything except the generator
/// configuration and the encoder default.
///
/// New schedule-level fields (rate control, windows, labels, sink, phase
/// offset) should be added here once and automatically propagate to both
/// signal types.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct BaseScheduleConfig {
    /// Scenario name (metric name for metrics, identifier for logs).
    pub name: String,
    /// Target event rate in events per second. Must be strictly positive.
    pub rate: f64,
    /// Optional total run duration (e.g. `"30s"`, `"5m"`). `None` means run indefinitely.
    #[cfg_attr(feature = "config", serde(default))]
    pub duration: Option<String>,
    /// Optional gap window: recurring silent periods in the event stream.
    #[cfg_attr(feature = "config", serde(default))]
    pub gaps: Option<GapConfig>,
    /// Optional burst window: recurring high-rate periods in the event stream.
    ///
    /// When both a gap and a burst overlap in time, the gap takes priority.
    #[cfg_attr(feature = "config", serde(default))]
    pub bursts: Option<BurstConfig>,
    /// Optional cardinality spikes: recurring windows that inject dynamic
    /// labels to simulate cardinality explosions.
    #[cfg_attr(feature = "config", serde(default))]
    pub cardinality_spikes: Option<Vec<CardinalitySpikeConfig>>,
    /// Optional dynamic labels: always-on rotating label values that cycle
    /// through a fixed set of values on every tick.
    ///
    /// Unlike [`CardinalitySpikeConfig`], dynamic labels are never gated by a
    /// time window — they appear in every emitted event. Use this to simulate
    /// a fleet of N hosts, pods, or regions.
    #[cfg_attr(feature = "config", serde(default))]
    pub dynamic_labels: Option<Vec<DynamicLabelConfig>>,
    /// Static labels attached to every emitted event.
    #[cfg_attr(feature = "config", serde(default))]
    pub labels: Option<HashMap<String, String>>,
    /// Output sink. Defaults to `stdout`.
    #[cfg_attr(feature = "config", serde(default = "default_sink"))]
    pub sink: SinkConfig,
    /// Delay before starting this scenario, relative to the group start time.
    ///
    /// Only meaningful in multi-scenario mode. Enables temporal correlation
    /// between scenarios: "metric A starts immediately, metric B starts 30s
    /// later". Accepts a duration string (e.g. `"30s"`, `"1m"`, `"500ms"`).
    #[cfg_attr(feature = "config", serde(default))]
    pub phase_offset: Option<String>,
    /// Clock group identifier for multi-scenario correlation.
    ///
    /// Scenarios with the same `clock_group` value share a common start time
    /// reference. For MVP this provides a shared start reference only; advanced
    /// cross-scenario signaling is deferred to a future phase.
    #[cfg_attr(feature = "config", serde(default))]
    pub clock_group: Option<String>,
    /// Optional jitter amplitude. When set, adds uniform noise in
    /// `[-jitter, +jitter]` to every generated value. Defaults to `None` (no jitter).
    #[cfg_attr(feature = "config", serde(default))]
    pub jitter: Option<f64>,
    /// Optional seed for jitter noise. Defaults to `0` when absent.
    /// Different seeds produce different noise sequences.
    #[cfg_attr(feature = "config", serde(default))]
    pub jitter_seed: Option<u64>,
}

/// Full configuration for a single metric scenario run.
///
/// Embeds [`BaseScheduleConfig`] for the shared schedule and delivery fields,
/// adding only the metric-specific value generator and a Prometheus-defaulting
/// encoder.
///
/// Fields from [`BaseScheduleConfig`] are accessible directly via `Deref` (e.g.
/// `config.name`, `config.rate`) for ergonomic read access. Struct construction
/// uses the explicit `base` field.
///
/// # Example YAML
///
/// ```yaml
/// name: interface_oper_state
/// rate: 1000
/// duration: 30s
/// generator:
///   type: sine
///   amplitude: 5.0
///   period_secs: 30
///   offset: 10.0
/// gaps:
///   every: 2m
///   for: 20s
/// labels:
///   hostname: t0-a1
///   zone: eu1
/// encoder:
///   type: prometheus_text
/// sink:
///   type: stdout
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct ScenarioConfig {
    /// Shared schedule and delivery fields.
    #[cfg_attr(feature = "config", serde(flatten))]
    pub base: BaseScheduleConfig,
    /// Value generator configuration.
    pub generator: GeneratorConfig,
    /// Output encoder. Defaults to `prometheus_text`.
    #[cfg_attr(feature = "config", serde(default = "default_encoder"))]
    pub encoder: EncoderConfig,
}

impl std::ops::Deref for ScenarioConfig {
    type Target = BaseScheduleConfig;

    fn deref(&self) -> &BaseScheduleConfig {
        &self.base
    }
}

impl std::ops::DerefMut for ScenarioConfig {
    fn deref_mut(&mut self) -> &mut BaseScheduleConfig {
        &mut self.base
    }
}

/// Distribution model configuration for histogram and summary generators.
///
/// Determines how sample values are distributed when the generator produces
/// observations on each tick. Deserialized from YAML via the `type` tag.
///
/// # Example YAML
///
/// ```yaml
/// distribution:
///   type: exponential
///   rate: 10.0
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
#[cfg_attr(feature = "config", serde(tag = "type"))]
pub enum DistributionConfig {
    /// Exponential distribution with rate parameter lambda.
    ///
    /// Mean = 1/lambda. Models latency distributions.
    #[cfg_attr(feature = "config", serde(rename = "exponential"))]
    Exponential {
        /// Rate parameter (lambda). Must be strictly positive.
        rate: f64,
    },
    /// Normal (Gaussian) distribution.
    #[cfg_attr(feature = "config", serde(rename = "normal"))]
    Normal {
        /// Center of the distribution.
        mean: f64,
        /// Spread of the distribution. Must be strictly positive.
        stddev: f64,
    },
    /// Uniform distribution over `[min, max]`.
    #[cfg_attr(feature = "config", serde(rename = "uniform"))]
    Uniform {
        /// Lower bound (inclusive).
        min: f64,
        /// Upper bound (inclusive).
        max: f64,
    },
}

/// Full configuration for a single histogram scenario run.
///
/// Embeds [`BaseScheduleConfig`] for the shared schedule and delivery fields,
/// adding histogram-specific parameters: bucket boundaries, distribution model,
/// observations per tick, mean shift, and seed.
///
/// # Example YAML
///
/// ```yaml
/// signal_type: histogram
/// name: http_request_duration_seconds
/// rate: 1
/// duration: 5m
/// buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
/// distribution:
///   type: exponential
///   rate: 10.0
/// observations_per_tick: 100
/// seed: 42
/// labels:
///   method: GET
/// encoder:
///   type: prometheus_text
/// sink:
///   type: stdout
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct HistogramScenarioConfig {
    /// Shared schedule and delivery fields.
    #[cfg_attr(feature = "config", serde(flatten))]
    pub base: BaseScheduleConfig,
    /// Histogram bucket upper bounds. When `None`, uses the default Prometheus
    /// bucket boundaries: `[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]`.
    #[cfg_attr(feature = "config", serde(default))]
    pub buckets: Option<Vec<f64>>,
    /// Distribution model for generating observations.
    pub distribution: DistributionConfig,
    /// Number of observations to sample per tick. Defaults to 100.
    #[cfg_attr(feature = "config", serde(default))]
    pub observations_per_tick: Option<u64>,
    /// Linear drift applied to the distribution center per second. Defaults to 0.0.
    #[cfg_attr(feature = "config", serde(default))]
    pub mean_shift_per_sec: Option<f64>,
    /// Determinism seed for the RNG. Defaults to 0.
    #[cfg_attr(feature = "config", serde(default))]
    pub seed: Option<u64>,
    /// Output encoder. Defaults to `prometheus_text`.
    #[cfg_attr(feature = "config", serde(default = "default_encoder"))]
    pub encoder: EncoderConfig,
}

impl std::ops::Deref for HistogramScenarioConfig {
    type Target = BaseScheduleConfig;

    fn deref(&self) -> &BaseScheduleConfig {
        &self.base
    }
}

impl std::ops::DerefMut for HistogramScenarioConfig {
    fn deref_mut(&mut self) -> &mut BaseScheduleConfig {
        &mut self.base
    }
}

/// Full configuration for a single summary scenario run.
///
/// Embeds [`BaseScheduleConfig`] for the shared schedule and delivery fields,
/// adding summary-specific parameters: quantile targets, distribution model,
/// observations per tick, mean shift, and seed.
///
/// # Example YAML
///
/// ```yaml
/// signal_type: summary
/// name: rpc_duration_seconds
/// rate: 1
/// duration: 5m
/// quantiles: [0.5, 0.9, 0.95, 0.99]
/// distribution:
///   type: normal
///   mean: 0.1
///   stddev: 0.02
/// observations_per_tick: 100
/// seed: 42
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct SummaryScenarioConfig {
    /// Shared schedule and delivery fields.
    #[cfg_attr(feature = "config", serde(flatten))]
    pub base: BaseScheduleConfig,
    /// Quantile targets to compute. When `None`, uses default quantiles:
    /// `[0.5, 0.9, 0.95, 0.99]`.
    #[cfg_attr(feature = "config", serde(default))]
    pub quantiles: Option<Vec<f64>>,
    /// Distribution model for generating observations.
    pub distribution: DistributionConfig,
    /// Number of observations to sample per tick. Defaults to 100.
    #[cfg_attr(feature = "config", serde(default))]
    pub observations_per_tick: Option<u64>,
    /// Linear drift applied to the distribution center per second. Defaults to 0.0.
    #[cfg_attr(feature = "config", serde(default))]
    pub mean_shift_per_sec: Option<f64>,
    /// Determinism seed for the RNG. Defaults to 0.
    #[cfg_attr(feature = "config", serde(default))]
    pub seed: Option<u64>,
    /// Output encoder. Defaults to `prometheus_text`.
    #[cfg_attr(feature = "config", serde(default = "default_encoder"))]
    pub encoder: EncoderConfig,
}

impl std::ops::Deref for SummaryScenarioConfig {
    type Target = BaseScheduleConfig;

    fn deref(&self) -> &BaseScheduleConfig {
        &self.base
    }
}

impl std::ops::DerefMut for SummaryScenarioConfig {
    fn deref_mut(&mut self) -> &mut BaseScheduleConfig {
        &mut self.base
    }
}

/// A single entry in a multi-scenario configuration.
///
/// The `signal_type` tag selects whether this entry is a metrics, logs,
/// histogram, or summary scenario.
/// Deserialized from a YAML multi-scenario file where each element of the
/// `scenarios` list carries a `signal_type` key.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
#[cfg_attr(feature = "config", serde(tag = "signal_type"))]
pub enum ScenarioEntry {
    /// A metrics scenario entry.
    #[cfg_attr(feature = "config", serde(rename = "metrics"))]
    Metrics(ScenarioConfig),
    /// A logs scenario entry.
    #[cfg_attr(feature = "config", serde(rename = "logs"))]
    Logs(LogScenarioConfig),
    /// A histogram scenario entry.
    #[cfg_attr(feature = "config", serde(rename = "histogram"))]
    Histogram(HistogramScenarioConfig),
    /// A summary scenario entry.
    #[cfg_attr(feature = "config", serde(rename = "summary"))]
    Summary(SummaryScenarioConfig),
}

impl ScenarioEntry {
    /// Return a reference to the shared [`BaseScheduleConfig`].
    ///
    /// Useful when only schedule-level fields (name, rate, duration, gaps,
    /// labels, sink, etc.) are needed regardless of signal type.
    pub fn base(&self) -> &BaseScheduleConfig {
        match self {
            ScenarioEntry::Metrics(c) => &c.base,
            ScenarioEntry::Logs(c) => &c.base,
            ScenarioEntry::Histogram(c) => &c.base,
            ScenarioEntry::Summary(c) => &c.base,
        }
    }

    /// Return the `phase_offset` duration string, if set on the inner config.
    pub fn phase_offset(&self) -> Option<&str> {
        self.base().phase_offset.as_deref()
    }

    /// Return the `clock_group` identifier, if set on the inner config.
    pub fn clock_group(&self) -> Option<&str> {
        self.base().clock_group.as_deref()
    }
}

/// Full configuration for running multiple concurrent scenarios.
///
/// Deserialized from a multi-scenario YAML file that contains a top-level
/// `scenarios:` list. Each entry specifies its `signal_type` (either `metrics`
/// or `logs`) along with the scenario-specific fields.
///
/// # Example YAML
///
/// ```yaml
/// scenarios:
///   - signal_type: metrics
///     name: cpu_usage
///     rate: 100
///     duration: 30s
///     generator: { type: sine, amplitude: 50, period_secs: 60, offset: 50 }
///     encoder:
///       type: prometheus_text
///     sink:
///       type: stdout
///   - signal_type: logs
///     name: app_logs
///     rate: 10
///     duration: 30s
///     generator:
///       type: template
///       templates: [{ message: "event", field_pools: {} }]
///     encoder:
///       type: json_lines
///     sink:
///       type: file
///       path: /tmp/logs.json
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct MultiScenarioConfig {
    /// The list of scenarios to run concurrently.
    pub scenarios: Vec<ScenarioEntry>,
}

/// Validate the `column` / `columns` fields of a `CsvReplay` generator config.
///
/// Returns an error when:
/// - Both `column` and `columns` are set (mutually exclusive).
/// - `columns` is `Some` but the list is empty.
///
/// This validation is called before expansion so that invalid configs are
/// rejected early with a clear error message.
///
/// # Errors
///
/// Returns [`SondaError::Config`] with a descriptive message.
fn validate_csv_columns(
    column: &Option<usize>,
    columns: &Option<Vec<CsvColumnSpec>>,
) -> Result<(), SondaError> {
    if let Some(ref cols) = columns {
        if column.is_some() {
            return Err(SondaError::Config(ConfigError::invalid(
                "csv_replay: 'column' and 'columns' are mutually exclusive; use one or the other",
            )));
        }
        if cols.is_empty() {
            return Err(SondaError::Config(ConfigError::invalid(
                "csv_replay: 'columns' must not be empty; provide at least one column spec or omit the field",
            )));
        }

        // Reject duplicate column indices.
        let mut seen_indices = std::collections::HashSet::with_capacity(cols.len());
        for spec in cols {
            if !seen_indices.insert(spec.index) {
                return Err(SondaError::Config(ConfigError::invalid(format!(
                    "csv_replay: duplicate column index {}; each column index must be unique",
                    spec.index
                ))));
            }
        }

        // Reject duplicate metric names.
        let mut seen_names = std::collections::HashSet::with_capacity(cols.len());
        for spec in cols {
            if !seen_names.insert(&spec.name) {
                return Err(SondaError::Config(ConfigError::invalid(format!(
                    "csv_replay: duplicate column name '{}'; each column name must be unique",
                    spec.name
                ))));
            }
        }
    }
    Ok(())
}

/// Expand a [`ScenarioConfig`] that uses multi-column `csv_replay` into N
/// independent single-column scenarios.
///
/// When the `generator` is `CsvReplay` with `columns: Some(specs)`, this
/// function returns one `ScenarioConfig` per column spec. Each expanded config
/// has:
/// - `name` set to the column spec's `name`.
/// - `generator.column` set to `Some(spec.index)`.
/// - `generator.columns` set to `None`.
/// - All other fields (rate, duration, labels, sink, encoder, gaps, bursts,
///   jitter, etc.) cloned from the parent.
///
/// When `columns` is `None`, returns `vec![config]` unchanged.
///
/// # Errors
///
/// Returns [`SondaError::Config`] if:
/// - Both `column` and `columns` are set.
/// - `columns` is an empty list.
pub fn expand_scenario(config: ScenarioConfig) -> Result<Vec<ScenarioConfig>, SondaError> {
    // Only the CsvReplay variant can have `columns`.
    let columns = match &config.generator {
        GeneratorConfig::CsvReplay {
            columns, column, ..
        } => {
            validate_csv_columns(column, columns)?;
            columns.clone()
        }
        _ => None,
    };

    let specs = match columns {
        Some(specs) => specs,
        None => return Ok(vec![config]),
    };

    let expanded = specs
        .into_iter()
        .map(|spec| {
            let mut child = config.clone();
            child.base.name = spec.name;
            // Replace the generator's column/columns fields.
            if let GeneratorConfig::CsvReplay {
                ref mut column,
                ref mut columns,
                ..
            } = child.generator
            {
                *column = Some(spec.index);
                *columns = None;
            }
            child
        })
        .collect();

    Ok(expanded)
}

/// Expand a [`ScenarioEntry`] that uses multi-column `csv_replay`.
///
/// For `ScenarioEntry::Metrics`, delegates to [`expand_scenario`] and wraps
/// the results back in `ScenarioEntry::Metrics`. For `ScenarioEntry::Logs`,
/// returns the entry unchanged (log scenarios do not use `csv_replay`).
///
/// # Errors
///
/// Propagates errors from [`expand_scenario`].
pub fn expand_entry(entry: ScenarioEntry) -> Result<Vec<ScenarioEntry>, SondaError> {
    match entry {
        ScenarioEntry::Metrics(config) => {
            let expanded = expand_scenario(config)?;
            Ok(expanded.into_iter().map(ScenarioEntry::Metrics).collect())
        }
        // Histogram, Summary, and Logs entries do not support csv_replay expansion.
        other => Ok(vec![other]),
    }
}

/// Full configuration for a single log scenario run.
///
/// Embeds [`BaseScheduleConfig`] for the shared schedule and delivery fields,
/// adding only the log-specific generator and a JSON-Lines-defaulting encoder.
///
/// Fields from [`BaseScheduleConfig`] are accessible directly via `Deref` (e.g.
/// `config.name`, `config.rate`) for ergonomic read access. Struct construction
/// uses the explicit `base` field.
///
/// # Example YAML
///
/// ```yaml
/// name: app_logs
/// rate: 10
/// duration: 60s
/// generator:
///   type: template
///   templates:
///     - message: "Request from {ip} to {endpoint}"
///       field_pools:
///         ip: ["10.0.0.1", "10.0.0.2"]
///         endpoint: ["/api", "/health"]
///   severity_weights:
///     info: 0.7
///     warn: 0.2
///     error: 0.1
/// encoder:
///   type: json_lines
/// sink:
///   type: stdout
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct LogScenarioConfig {
    /// Shared schedule and delivery fields.
    #[cfg_attr(feature = "config", serde(flatten))]
    pub base: BaseScheduleConfig,
    /// Log generator configuration.
    pub generator: LogGeneratorConfig,
    /// Output encoder. Defaults to `json_lines`.
    #[cfg_attr(feature = "config", serde(default = "default_log_encoder"))]
    pub encoder: EncoderConfig,
}

impl std::ops::Deref for LogScenarioConfig {
    type Target = BaseScheduleConfig;

    fn deref(&self) -> &BaseScheduleConfig {
        &self.base
    }
}

impl std::ops::DerefMut for LogScenarioConfig {
    fn deref_mut(&mut self) -> &mut BaseScheduleConfig {
        &mut self.base
    }
}

#[cfg(all(test, feature = "config"))]
mod tests {
    use std::collections::BTreeMap;

    use super::*;

    // -----------------------------------------------------------------------
    // phase_offset deserialization: ScenarioConfig
    // -----------------------------------------------------------------------

    /// phase_offset deserializes from YAML on ScenarioConfig.
    #[test]
    fn scenario_config_phase_offset_deserializes_from_yaml() {
        let yaml = r#"
name: test_metric
rate: 10
generator:
  type: constant
  value: 1.0
phase_offset: "5s"
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.phase_offset.as_deref(), Some("5s"));
    }

    /// phase_offset defaults to None when not specified in YAML.
    #[test]
    fn scenario_config_phase_offset_defaults_to_none() {
        let yaml = r#"
name: test_metric
rate: 10
generator:
  type: constant
  value: 1.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.phase_offset.is_none());
    }

    /// phase_offset with milliseconds deserializes correctly.
    #[test]
    fn scenario_config_phase_offset_milliseconds() {
        let yaml = r#"
name: ms_test
rate: 10
generator:
  type: constant
  value: 1.0
phase_offset: "500ms"
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.phase_offset.as_deref(), Some("500ms"));
    }

    /// phase_offset with minutes deserializes correctly.
    #[test]
    fn scenario_config_phase_offset_minutes() {
        let yaml = r#"
name: min_test
rate: 10
generator:
  type: constant
  value: 1.0
phase_offset: "2m"
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.phase_offset.as_deref(), Some("2m"));
    }

    // -----------------------------------------------------------------------
    // phase_offset deserialization: LogScenarioConfig
    // -----------------------------------------------------------------------

    /// phase_offset deserializes from YAML on LogScenarioConfig.
    #[test]
    fn log_scenario_config_phase_offset_deserializes_from_yaml() {
        let yaml = r#"
name: log_test
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
phase_offset: "3s"
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.phase_offset.as_deref(), Some("3s"));
    }

    /// phase_offset defaults to None for LogScenarioConfig.
    #[test]
    fn log_scenario_config_phase_offset_defaults_to_none() {
        let yaml = r#"
name: log_test
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.phase_offset.is_none());
    }

    // -----------------------------------------------------------------------
    // clock_group deserialization
    // -----------------------------------------------------------------------

    /// clock_group deserializes from YAML on ScenarioConfig.
    #[test]
    fn scenario_config_clock_group_deserializes_from_yaml() {
        let yaml = r#"
name: group_test
rate: 10
generator:
  type: constant
  value: 1.0
clock_group: alert-test
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.clock_group.as_deref(), Some("alert-test"));
    }

    /// clock_group defaults to None when absent.
    #[test]
    fn scenario_config_clock_group_defaults_to_none() {
        let yaml = r#"
name: no_group
rate: 10
generator:
  type: constant
  value: 1.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.clock_group.is_none());
    }

    /// clock_group deserializes from YAML on LogScenarioConfig.
    #[test]
    fn log_scenario_config_clock_group_deserializes_from_yaml() {
        let yaml = r#"
name: log_group
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
clock_group: log-sync
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.clock_group.as_deref(), Some("log-sync"));
    }

    /// clock_group defaults to None for LogScenarioConfig.
    #[test]
    fn log_scenario_config_clock_group_defaults_to_none() {
        let yaml = r#"
name: log_no_group
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.clock_group.is_none());
    }

    // -----------------------------------------------------------------------
    // jitter deserialization
    // -----------------------------------------------------------------------

    /// jitter and jitter_seed deserialize from YAML on ScenarioConfig.
    #[test]
    fn scenario_config_jitter_deserializes_from_yaml() {
        let yaml = r#"
name: jitter_test
rate: 10
generator:
  type: constant
  value: 1.0
jitter: 3.5
jitter_seed: 42
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.jitter, Some(3.5));
        assert_eq!(config.jitter_seed, Some(42));
    }

    /// jitter defaults to None when not specified in YAML.
    #[test]
    fn scenario_config_jitter_defaults_to_none() {
        let yaml = r#"
name: no_jitter
rate: 10
generator:
  type: constant
  value: 1.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.jitter.is_none());
        assert!(config.jitter_seed.is_none());
    }

    /// jitter_seed defaults to None when only jitter is specified.
    #[test]
    fn scenario_config_jitter_without_seed() {
        let yaml = r#"
name: jitter_no_seed
rate: 10
generator:
  type: sine
  amplitude: 20
  period_secs: 60
  offset: 50
jitter: 5.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.jitter, Some(5.0));
        assert!(config.jitter_seed.is_none());
    }

    /// jitter deserializes from YAML on LogScenarioConfig.
    #[test]
    fn log_scenario_config_jitter_deserializes_from_yaml() {
        let yaml = r#"
name: log_jitter
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
jitter: 2.0
jitter_seed: 99
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.jitter, Some(2.0));
        assert_eq!(config.jitter_seed, Some(99));
    }

    // -----------------------------------------------------------------------
    // LogScenarioConfig: labels deserialization
    // -----------------------------------------------------------------------

    /// YAML with labels section deserializes into Some(HashMap).
    #[test]
    fn log_scenario_config_labels_deserialize_from_yaml() {
        let yaml = r#"
name: labeled_logs
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
labels:
  device: wlan0
  hostname: router-01
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let labels = config.labels.as_ref().expect("labels must be Some");
        assert_eq!(labels.get("device").map(String::as_str), Some("wlan0"));
        assert_eq!(
            labels.get("hostname").map(String::as_str),
            Some("router-01")
        );
        assert_eq!(labels.len(), 2);
    }

    /// YAML without labels field deserializes with labels: None.
    #[test]
    fn log_scenario_config_labels_default_to_none() {
        let yaml = r#"
name: no_labels_logs
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(
            config.labels.is_none(),
            "labels must default to None when not in YAML"
        );
    }

    /// YAML with empty labels section deserializes as Some(empty HashMap).
    #[test]
    fn log_scenario_config_empty_labels_deserializes_as_some_empty_map() {
        let yaml = r#"
name: empty_labels
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
labels: {}
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let labels = config
            .labels
            .as_ref()
            .expect("labels must be Some for explicit empty map");
        assert!(labels.is_empty(), "labels must be an empty map");
    }

    /// ScenarioConfig (metrics) also supports labels deserialization.
    #[test]
    fn scenario_config_labels_deserialize_from_yaml() {
        let yaml = r#"
name: metric_with_labels
rate: 10
generator:
  type: constant
  value: 1.0
labels:
  zone: eu1
  env: production
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let labels = config.labels.as_ref().expect("labels must be Some");
        assert_eq!(labels.get("zone").map(String::as_str), Some("eu1"));
        assert_eq!(labels.get("env").map(String::as_str), Some("production"));
    }

    // -----------------------------------------------------------------------
    // Both phase_offset and clock_group together
    // -----------------------------------------------------------------------

    /// Both phase_offset and clock_group set on ScenarioConfig.
    #[test]
    fn scenario_config_both_phase_offset_and_clock_group() {
        let yaml = r#"
name: both_fields
rate: 10
generator:
  type: constant
  value: 1.0
phase_offset: "30s"
clock_group: compound-alert
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.phase_offset.as_deref(), Some("30s"));
        assert_eq!(config.clock_group.as_deref(), Some("compound-alert"));
    }

    // -----------------------------------------------------------------------
    // ScenarioEntry::phase_offset() accessor
    // -----------------------------------------------------------------------

    /// ScenarioEntry::phase_offset() returns the phase_offset for a Metrics entry.
    #[test]
    fn scenario_entry_phase_offset_returns_value_for_metrics() {
        let entry = ScenarioEntry::Metrics(ScenarioConfig {
            base: BaseScheduleConfig {
                name: "accessor_test".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: Some("5s".to_string()),
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        assert_eq!(entry.phase_offset(), Some("5s"));
    }

    /// ScenarioEntry::phase_offset() returns None when not set on Metrics.
    #[test]
    fn scenario_entry_phase_offset_returns_none_for_metrics_without_offset() {
        let entry = ScenarioEntry::Metrics(ScenarioConfig {
            base: BaseScheduleConfig {
                name: "no_offset".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        assert_eq!(entry.phase_offset(), None);
    }

    /// ScenarioEntry::phase_offset() returns the phase_offset for a Logs entry.
    #[test]
    fn scenario_entry_phase_offset_returns_value_for_logs() {
        let entry = ScenarioEntry::Logs(LogScenarioConfig {
            base: BaseScheduleConfig {
                name: "log_accessor".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: Some("10s".to_string()),
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: LogGeneratorConfig::Template {
                templates: vec![crate::generator::TemplateConfig {
                    message: "test".to_string(),
                    field_pools: BTreeMap::new(),
                }],
                severity_weights: None,
                seed: Some(0),
            },
            encoder: EncoderConfig::JsonLines { precision: None },
        });
        assert_eq!(entry.phase_offset(), Some("10s"));
    }

    // -----------------------------------------------------------------------
    // ScenarioEntry::clock_group() accessor
    // -----------------------------------------------------------------------

    /// ScenarioEntry::clock_group() returns the value for a Metrics entry.
    #[test]
    fn scenario_entry_clock_group_returns_value_for_metrics() {
        let entry = ScenarioEntry::Metrics(ScenarioConfig {
            base: BaseScheduleConfig {
                name: "group_accessor".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: Some("my-group".to_string()),
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        assert_eq!(entry.clock_group(), Some("my-group"));
    }

    /// ScenarioEntry::clock_group() returns None when not set.
    #[test]
    fn scenario_entry_clock_group_returns_none_when_absent() {
        let entry = ScenarioEntry::Metrics(ScenarioConfig {
            base: BaseScheduleConfig {
                name: "no_group_acc".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        assert_eq!(entry.clock_group(), None);
    }

    // -----------------------------------------------------------------------
    // ScenarioEntry::base() accessor
    // -----------------------------------------------------------------------

    /// ScenarioEntry::base() returns the shared config for a Metrics entry.
    #[test]
    fn scenario_entry_base_returns_shared_config_for_metrics() {
        let entry = ScenarioEntry::Metrics(ScenarioConfig {
            base: BaseScheduleConfig {
                name: "base_test".to_string(),
                rate: 42.0,
                duration: Some("5s".to_string()),
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        assert_eq!(entry.base().name, "base_test");
        assert_eq!(entry.base().rate, 42.0);
    }

    /// ScenarioEntry::base() returns the shared config for a Logs entry.
    #[test]
    fn scenario_entry_base_returns_shared_config_for_logs() {
        let entry = ScenarioEntry::Logs(LogScenarioConfig {
            base: BaseScheduleConfig {
                name: "log_base".to_string(),
                rate: 99.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: LogGeneratorConfig::Template {
                templates: vec![crate::generator::TemplateConfig {
                    message: "test".to_string(),
                    field_pools: BTreeMap::new(),
                }],
                severity_weights: None,
                seed: Some(0),
            },
            encoder: EncoderConfig::JsonLines { precision: None },
        });
        assert_eq!(entry.base().name, "log_base");
        assert_eq!(entry.base().rate, 99.0);
    }

    // -----------------------------------------------------------------------
    // Multi-scenario YAML with phase_offset and clock_group
    // -----------------------------------------------------------------------

    /// Multi-scenario YAML with phase_offset and clock_group deserializes correctly.
    #[test]
    fn multi_scenario_config_with_phase_offset_and_clock_group_deserializes() {
        let yaml = r#"
scenarios:
  - signal_type: metrics
    name: cpu_usage
    rate: 1
    duration: 10s
    phase_offset: "0s"
    clock_group: alert-test
    generator:
      type: constant
      value: 95.0
    encoder:
      type: prometheus_text
    sink:
      type: stdout
  - signal_type: metrics
    name: memory_usage
    rate: 1
    duration: 10s
    phase_offset: "3s"
    clock_group: alert-test
    generator:
      type: constant
      value: 88.0
    encoder:
      type: prometheus_text
    sink:
      type: stdout
"#;
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 2);

        assert_eq!(config.scenarios[0].phase_offset(), Some("0s"));
        assert_eq!(config.scenarios[0].clock_group(), Some("alert-test"));
        assert_eq!(config.scenarios[1].phase_offset(), Some("3s"));
        assert_eq!(config.scenarios[1].clock_group(), Some("alert-test"));
    }

    /// Existing multi-scenario YAML without phase_offset/clock_group still works.
    #[test]
    fn multi_scenario_config_without_phase_offset_backward_compatible() {
        let yaml = r#"
scenarios:
  - signal_type: metrics
    name: cpu_usage
    rate: 100
    duration: 10s
    generator:
      type: constant
      value: 1.0
    encoder:
      type: prometheus_text
    sink:
      type: stdout
"#;
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 1);
        assert_eq!(config.scenarios[0].phase_offset(), None);
        assert_eq!(config.scenarios[0].clock_group(), None);
    }

    /// The example multi-metric-correlation.yaml file deserializes correctly.
    #[test]
    fn multi_metric_correlation_example_deserializes() {
        let yaml = include_str!("../../../examples/multi-metric-correlation.yaml");
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 2, "example must have 2 scenarios");

        // First scenario: cpu_usage with phase_offset "0s"
        assert_eq!(config.scenarios[0].phase_offset(), Some("0s"));
        assert_eq!(config.scenarios[0].clock_group(), Some("alert-test"));

        // Second scenario: memory_usage_percent with phase_offset "3s"
        assert_eq!(config.scenarios[1].phase_offset(), Some("3s"));
        assert_eq!(config.scenarios[1].clock_group(), Some("alert-test"));

        // Both should be metrics entries
        assert!(matches!(config.scenarios[0], ScenarioEntry::Metrics(_)));
        assert!(matches!(config.scenarios[1], ScenarioEntry::Metrics(_)));
    }

    /// Multi-scenario YAML with a Logs entry including phase_offset deserializes.
    #[test]
    fn multi_scenario_config_logs_entry_with_phase_offset() {
        let yaml = r#"
scenarios:
  - signal_type: logs
    name: delayed_logs
    rate: 10
    duration: 10s
    phase_offset: "2s"
    clock_group: log-group
    generator:
      type: template
      templates:
        - message: "log event"
          field_pools: {}
    encoder:
      type: json_lines
    sink:
      type: stdout
"#;
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 1);
        assert_eq!(config.scenarios[0].phase_offset(), Some("2s"));
        assert_eq!(config.scenarios[0].clock_group(), Some("log-group"));
    }

    // -----------------------------------------------------------------------
    // phase_offset parseable by parse_duration
    // -----------------------------------------------------------------------

    /// phase_offset values are parseable by parse_duration.
    #[test]
    fn phase_offset_values_are_parseable_as_durations() {
        use crate::config::validate::parse_duration;

        let yaml = r#"
name: parse_test
rate: 10
generator:
  type: constant
  value: 1.0
phase_offset: "3s"
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let dur = parse_duration(config.phase_offset.as_deref().unwrap()).unwrap();
        assert_eq!(dur, std::time::Duration::from_secs(3));
    }

    // -----------------------------------------------------------------------
    // cardinality_spikes deserialization
    // -----------------------------------------------------------------------

    /// YAML with cardinality_spikes deserializes into Some(Vec).
    #[test]
    fn scenario_config_cardinality_spikes_deserializes_from_yaml() {
        let yaml = r#"
name: spike_test
rate: 10
generator:
  type: constant
  value: 1.0
cardinality_spikes:
  - label: pod_name
    every: 2m
    for: 30s
    cardinality: 500
    strategy: counter
    prefix: "pod-"
  - label: error_msg
    every: 5m
    for: 1m
    cardinality: 1000
    strategy: random
    seed: 42
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let spikes = config
            .cardinality_spikes
            .as_ref()
            .expect("cardinality_spikes must be Some");
        assert_eq!(spikes.len(), 2);
        assert_eq!(spikes[0].label, "pod_name");
        assert_eq!(spikes[0].cardinality, 500);
        assert_eq!(spikes[0].strategy, SpikeStrategy::Counter);
        assert_eq!(spikes[0].prefix.as_deref(), Some("pod-"));
        assert_eq!(spikes[1].label, "error_msg");
        assert_eq!(spikes[1].strategy, SpikeStrategy::Random);
        assert_eq!(spikes[1].seed, Some(42));
    }

    /// YAML without cardinality_spikes defaults to None.
    #[test]
    fn scenario_config_cardinality_spikes_defaults_to_none() {
        let yaml = r#"
name: no_spike
rate: 10
generator:
  type: constant
  value: 1.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(
            config.cardinality_spikes.is_none(),
            "cardinality_spikes must be None when absent from YAML"
        );
    }

    /// SpikeStrategy defaults to Counter when not specified in YAML.
    #[test]
    fn spike_strategy_defaults_to_counter() {
        let yaml = r#"
name: default_strategy
rate: 10
generator:
  type: constant
  value: 1.0
cardinality_spikes:
  - label: pod_name
    every: 1m
    for: 10s
    cardinality: 10
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let spikes = config.base.cardinality_spikes.unwrap();
        assert_eq!(spikes[0].strategy, SpikeStrategy::Counter);
    }

    /// LogScenarioConfig also supports cardinality_spikes.
    #[test]
    fn log_scenario_config_cardinality_spikes_deserializes() {
        let yaml = r#"
name: log_spike
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
cardinality_spikes:
  - label: pod_name
    every: 1m
    for: 10s
    cardinality: 100
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let spikes = config.base.cardinality_spikes.unwrap();
        assert_eq!(spikes.len(), 1);
        assert_eq!(spikes[0].label, "pod_name");
    }

    /// Backward compatibility: existing YAML without cardinality_spikes still works.
    #[test]
    fn backward_compatible_yaml_without_spikes() {
        let yaml = r#"
name: compat_test
rate: 100
generator:
  type: sine
  amplitude: 5.0
  period_secs: 30
  offset: 10.0
labels:
  hostname: t0-a1
gaps:
  every: 2m
  for: 20s
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.cardinality_spikes.is_none());
        assert!(config.gaps.is_some());
        assert_eq!(config.name, "compat_test");
    }

    // -----------------------------------------------------------------------
    // BaseScheduleConfig: Clone + Debug contract
    // -----------------------------------------------------------------------

    /// BaseScheduleConfig is Clone and Debug.
    #[test]
    fn base_schedule_config_is_clone_and_debug() {
        let base = BaseScheduleConfig {
            name: "test".to_string(),
            rate: 42.0,
            duration: Some("10s".to_string()),
            gaps: None,
            bursts: None,
            cardinality_spikes: None,
            dynamic_labels: None,
            labels: None,
            sink: SinkConfig::Stdout,
            phase_offset: None,
            clock_group: None,
            jitter: None,
            jitter_seed: None,
        };
        let cloned = base.clone();
        assert_eq!(cloned.name, "test");
        assert_eq!(cloned.rate, 42.0);
        let dbg = format!("{base:?}");
        assert!(
            dbg.contains("BaseScheduleConfig"),
            "Debug output must contain type name"
        );
    }

    // -----------------------------------------------------------------------
    // Deref: ScenarioConfig fields accessible directly
    // -----------------------------------------------------------------------

    /// ScenarioConfig fields from BaseScheduleConfig are accessible via Deref.
    #[test]
    fn scenario_config_deref_accesses_base_fields() {
        let config = ScenarioConfig {
            base: BaseScheduleConfig {
                name: "deref_test".to_string(),
                rate: 99.0,
                duration: Some("5s".to_string()),
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: Some("1s".to_string()),
                clock_group: Some("group-a".to_string()),
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        };
        // All these access via Deref — no explicit `.base.` needed.
        assert_eq!(config.name, "deref_test");
        assert_eq!(config.rate, 99.0);
        assert_eq!(config.duration.as_deref(), Some("5s"));
        assert!(config.gaps.is_none());
        assert_eq!(config.phase_offset.as_deref(), Some("1s"));
        assert_eq!(config.clock_group.as_deref(), Some("group-a"));
    }

    /// LogScenarioConfig fields from BaseScheduleConfig are accessible via Deref.
    #[test]
    fn log_scenario_config_deref_accesses_base_fields() {
        let config = LogScenarioConfig {
            base: BaseScheduleConfig {
                name: "log_deref".to_string(),
                rate: 50.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: LogGeneratorConfig::Template {
                templates: vec![crate::generator::TemplateConfig {
                    message: "test".to_string(),
                    field_pools: BTreeMap::new(),
                }],
                severity_weights: None,
                seed: Some(0),
            },
            encoder: EncoderConfig::JsonLines { precision: None },
        };
        assert_eq!(config.name, "log_deref");
        assert_eq!(config.rate, 50.0);
        assert!(config.duration.is_none());
    }

    // -----------------------------------------------------------------------
    // DerefMut: ScenarioConfig base fields mutable via DerefMut
    // -----------------------------------------------------------------------

    /// ScenarioConfig base fields can be mutated via DerefMut.
    #[test]
    fn scenario_config_deref_mut_allows_base_field_mutation() {
        let mut config = ScenarioConfig {
            base: BaseScheduleConfig {
                name: "original".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            generator: GeneratorConfig::Constant { value: 1.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        };
        config.name = "mutated".to_string();
        config.rate = 999.0;
        config.duration = Some("30s".to_string());
        assert_eq!(config.name, "mutated");
        assert_eq!(config.rate, 999.0);
        assert_eq!(config.duration.as_deref(), Some("30s"));
    }

    // -----------------------------------------------------------------------
    // Flatten: YAML with base fields and generator deserializes correctly
    // -----------------------------------------------------------------------

    /// ScenarioConfig deserializes with all fields at the top level (serde flatten).
    #[test]
    fn scenario_config_flatten_deserializes_all_fields() {
        let yaml = r#"
name: flatten_test
rate: 100
duration: 30s
generator:
  type: sine
  amplitude: 5.0
  period_secs: 30
  offset: 10.0
gaps:
  every: 2m
  for: 20s
bursts:
  every: 10s
  for: 2s
  multiplier: 5.0
labels:
  hostname: t0-a1
  zone: eu1
encoder:
  type: prometheus_text
sink:
  type: stdout
phase_offset: "5s"
clock_group: correlation
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.name, "flatten_test");
        assert_eq!(config.rate, 100.0);
        assert_eq!(config.duration.as_deref(), Some("30s"));
        assert!(config.gaps.is_some());
        assert!(config.bursts.is_some());
        let labels = config.labels.as_ref().unwrap();
        assert_eq!(labels.get("hostname").map(String::as_str), Some("t0-a1"));
        assert!(matches!(
            config.encoder,
            EncoderConfig::PrometheusText { .. }
        ));
        assert!(matches!(config.base.sink, SinkConfig::Stdout));
        assert_eq!(config.phase_offset.as_deref(), Some("5s"));
        assert_eq!(config.clock_group.as_deref(), Some("correlation"));
    }

    /// LogScenarioConfig deserializes with all fields at the top level (serde flatten).
    #[test]
    fn log_scenario_config_flatten_deserializes_all_fields() {
        let yaml = r#"
name: log_flatten
rate: 20
duration: 60s
generator:
  type: template
  templates:
    - message: "hello"
      field_pools: {}
labels:
  env: prod
encoder:
  type: syslog
  hostname: myhost
  app_name: myapp
sink:
  type: stdout
phase_offset: "2s"
clock_group: log-group
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.name, "log_flatten");
        assert_eq!(config.rate, 20.0);
        assert_eq!(config.duration.as_deref(), Some("60s"));
        let labels = config.labels.as_ref().unwrap();
        assert_eq!(labels.get("env").map(String::as_str), Some("prod"));
        assert_eq!(config.phase_offset.as_deref(), Some("2s"));
        assert_eq!(config.clock_group.as_deref(), Some("log-group"));
    }

    // -----------------------------------------------------------------------
    // Encoder defaults remain correct per signal type
    // -----------------------------------------------------------------------

    /// ScenarioConfig defaults encoder to prometheus_text.
    #[test]
    fn scenario_config_encoder_defaults_to_prometheus_text() {
        let yaml = r#"
name: enc_default
rate: 10
generator:
  type: constant
  value: 1.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(
            matches!(config.encoder, EncoderConfig::PrometheusText { .. }),
            "ScenarioConfig encoder default must be prometheus_text, got {:?}",
            config.encoder
        );
    }

    /// LogScenarioConfig defaults encoder to json_lines.
    #[test]
    fn log_scenario_config_encoder_defaults_to_json_lines() {
        let yaml = r#"
name: log_enc_default
rate: 10
generator:
  type: template
  templates:
    - message: "test"
      field_pools: {}
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(
            matches!(config.encoder, EncoderConfig::JsonLines { .. }),
            "LogScenarioConfig encoder default must be json_lines, got {:?}",
            config.encoder
        );
    }

    // -----------------------------------------------------------------------
    // dynamic_labels deserialization
    // -----------------------------------------------------------------------

    /// dynamic_labels with counter strategy deserializes from YAML.
    #[test]
    fn dynamic_labels_counter_deserializes_from_yaml() {
        let yaml = r#"
name: test
rate: 10
generator:
  type: constant
  value: 1.0
dynamic_labels:
  - key: hostname
    prefix: "host-"
    cardinality: 10
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let dls = config
            .dynamic_labels
            .as_ref()
            .expect("dynamic_labels must be present");
        assert_eq!(dls.len(), 1);
        assert_eq!(dls[0].key, "hostname");
        match &dls[0].strategy {
            DynamicLabelStrategy::Counter {
                prefix,
                cardinality,
            } => {
                assert_eq!(prefix.as_deref(), Some("host-"));
                assert_eq!(*cardinality, 10);
            }
            other => panic!("expected Counter strategy, got {other:?}"),
        }
    }

    /// dynamic_labels with values list strategy deserializes from YAML.
    #[test]
    fn dynamic_labels_values_list_deserializes_from_yaml() {
        let yaml = r#"
name: test
rate: 10
generator:
  type: constant
  value: 1.0
dynamic_labels:
  - key: region
    values: [us-east-1, us-west-2, eu-west-1]
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let dls = config
            .dynamic_labels
            .as_ref()
            .expect("dynamic_labels must be present");
        assert_eq!(dls.len(), 1);
        assert_eq!(dls[0].key, "region");
        match &dls[0].strategy {
            DynamicLabelStrategy::ValuesList { values } => {
                assert_eq!(values, &["us-east-1", "us-west-2", "eu-west-1"]);
            }
            other => panic!("expected ValuesList strategy, got {other:?}"),
        }
    }

    /// dynamic_labels defaults to None when not specified.
    #[test]
    fn dynamic_labels_defaults_to_none() {
        let yaml = r#"
name: test
rate: 10
generator:
  type: constant
  value: 1.0
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.dynamic_labels.is_none());
    }

    /// Multiple dynamic_labels entries deserialize correctly.
    #[test]
    fn dynamic_labels_multiple_entries_deserialize() {
        let yaml = r#"
name: test
rate: 10
generator:
  type: constant
  value: 1.0
dynamic_labels:
  - key: hostname
    prefix: "host-"
    cardinality: 10
  - key: region
    values: [us-east, eu-west]
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let dls = config
            .dynamic_labels
            .as_ref()
            .expect("dynamic_labels must be present");
        assert_eq!(dls.len(), 2);
        assert_eq!(dls[0].key, "hostname");
        assert_eq!(dls[1].key, "region");
    }

    /// dynamic_labels on LogScenarioConfig deserializes from YAML.
    #[test]
    fn dynamic_labels_on_log_config_deserializes() {
        let yaml = r#"
name: test_logs
rate: 10
generator:
  type: template
  templates:
    - message: "test event"
      field_pools: {}
dynamic_labels:
  - key: pod_name
    prefix: "pod-"
    cardinality: 5
"#;
        let config: LogScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let dls = config
            .dynamic_labels
            .as_ref()
            .expect("dynamic_labels must be present");
        assert_eq!(dls.len(), 1);
        assert_eq!(dls[0].key, "pod_name");
    }

    /// Counter strategy with no prefix defaults prefix to None in config.
    #[test]
    fn dynamic_labels_counter_no_prefix_deserializes() {
        let yaml = r#"
name: test
rate: 10
generator:
  type: constant
  value: 1.0
dynamic_labels:
  - key: zone
    cardinality: 3
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let dls = config
            .dynamic_labels
            .as_ref()
            .expect("dynamic_labels must be present");
        match &dls[0].strategy {
            DynamicLabelStrategy::Counter {
                prefix,
                cardinality,
            } => {
                assert!(prefix.is_none(), "prefix should be None when not specified");
                assert_eq!(*cardinality, 3);
            }
            other => panic!("expected Counter strategy, got {other:?}"),
        }
    }

    /// static labels and dynamic_labels coexist in the same config.
    #[test]
    fn dynamic_labels_and_static_labels_coexist() {
        let yaml = r#"
name: test
rate: 10
generator:
  type: constant
  value: 1.0
labels:
  env: prod
dynamic_labels:
  - key: hostname
    prefix: "host-"
    cardinality: 5
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.labels.is_some(), "static labels must be present");
        assert!(
            config.dynamic_labels.is_some(),
            "dynamic labels must be present"
        );
        let static_labels = config.labels.as_ref().unwrap();
        assert_eq!(static_labels.get("env"), Some(&"prod".to_string()));
    }

    // -----------------------------------------------------------------------
    // csv_replay multi-column: YAML deserialization
    // -----------------------------------------------------------------------

    /// csv_replay with `columns` deserializes correctly from YAML.
    #[test]
    fn csv_replay_columns_deserializes_from_yaml() {
        let yaml = r#"
name: multi_col
rate: 1
generator:
  type: csv_replay
  file: data.csv
  has_header: true
  columns:
    - index: 1
      name: cpu_percent
    - index: 2
      name: mem_percent
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        match &config.generator {
            GeneratorConfig::CsvReplay {
                columns, column, ..
            } => {
                assert!(
                    column.is_none(),
                    "column should be None when columns is set"
                );
                let cols = columns.as_ref().expect("columns should be Some");
                assert_eq!(cols.len(), 2);
                assert_eq!(cols[0].index, 1);
                assert_eq!(cols[0].name, "cpu_percent");
                assert_eq!(cols[1].index, 2);
                assert_eq!(cols[1].name, "mem_percent");
            }
            other => panic!("expected CsvReplay variant, got {other:?}"),
        }
    }

    /// csv_replay without `columns` deserializes with columns as None.
    #[test]
    fn csv_replay_without_columns_field_has_none() {
        let yaml = r#"
name: single_col
rate: 1
generator:
  type: csv_replay
  file: data.csv
  column: 1
"#;
        let config: ScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        match &config.generator {
            GeneratorConfig::CsvReplay {
                columns, column, ..
            } => {
                assert_eq!(*column, Some(1));
                assert!(
                    columns.is_none(),
                    "columns should be None when not specified"
                );
            }
            other => panic!("expected CsvReplay variant, got {other:?}"),
        }
    }
}

#[cfg(test)]
mod expand_tests {
    use super::*;
    use crate::encoder::EncoderConfig;
    use crate::generator::{CsvColumnSpec, GeneratorConfig};
    use crate::sink::SinkConfig;

    /// Build a base `ScenarioConfig` with a csv_replay generator for testing.
    fn csv_replay_config(
        name: &str,
        column: Option<usize>,
        columns: Option<Vec<CsvColumnSpec>>,
    ) -> ScenarioConfig {
        ScenarioConfig {
            base: BaseScheduleConfig {
                name: name.to_string(),
                rate: 10.0,
                duration: Some("30s".to_string()),
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                labels: Some([("host".to_string(), "srv1".to_string())].into()),
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: Some(0.5),
                jitter_seed: Some(42),
                dynamic_labels: None,
            },
            generator: GeneratorConfig::CsvReplay {
                file: "data.csv".to_string(),
                column,
                has_header: Some(true),
                repeat: Some(true),
                columns,
            },
            encoder: EncoderConfig::PrometheusText { precision: None },
        }
    }

    // -----------------------------------------------------------------------
    // expand_scenario: pass-through (no columns)
    // -----------------------------------------------------------------------

    /// When columns is None, expand_scenario returns the config unchanged.
    #[test]
    fn pass_through_when_no_columns() {
        let config = csv_replay_config("single_metric", Some(1), None);
        let result = expand_scenario(config.clone()).expect("must succeed");
        assert_eq!(result.len(), 1, "should return exactly one config");
        assert_eq!(result[0].name, "single_metric");
    }

    /// A non-csv_replay generator passes through unchanged.
    #[test]
    fn non_csv_replay_passes_through() {
        let config = ScenarioConfig {
            base: BaseScheduleConfig {
                name: "const_metric".to_string(),
                rate: 1.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
                dynamic_labels: None,
            },
            generator: GeneratorConfig::Constant { value: 42.0 },
            encoder: EncoderConfig::PrometheusText { precision: None },
        };
        let result = expand_scenario(config).expect("must succeed");
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "const_metric");
    }

    // -----------------------------------------------------------------------
    // expand_scenario: two-column expansion
    // -----------------------------------------------------------------------

    /// Two columns expand into two configs with correct names and column indices.
    #[test]
    fn two_column_expansion() {
        let cols = vec![
            CsvColumnSpec {
                index: 1,
                name: "cpu_percent".to_string(),
            },
            CsvColumnSpec {
                index: 2,
                name: "mem_percent".to_string(),
            },
        ];
        let config = csv_replay_config("parent", None, Some(cols));
        let result = expand_scenario(config).expect("must succeed");

        assert_eq!(result.len(), 2, "should produce two expanded configs");

        // First expanded config
        assert_eq!(result[0].name, "cpu_percent");
        match &result[0].generator {
            GeneratorConfig::CsvReplay {
                column,
                columns,
                file,
                has_header,
                repeat,
                ..
            } => {
                assert_eq!(*column, Some(1));
                assert!(columns.is_none(), "columns must be None after expansion");
                assert_eq!(file, "data.csv", "file must be inherited");
                assert_eq!(*has_header, Some(true), "has_header must be inherited");
                assert_eq!(*repeat, Some(true), "repeat must be inherited");
            }
            other => panic!("expected CsvReplay, got {other:?}"),
        }

        // Second expanded config
        assert_eq!(result[1].name, "mem_percent");
        match &result[1].generator {
            GeneratorConfig::CsvReplay {
                column, columns, ..
            } => {
                assert_eq!(*column, Some(2));
                assert!(columns.is_none());
            }
            other => panic!("expected CsvReplay, got {other:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // expand_scenario: three-column expansion
    // -----------------------------------------------------------------------

    /// Three columns expand into three configs.
    #[test]
    fn three_column_expansion() {
        let cols = vec![
            CsvColumnSpec {
                index: 1,
                name: "cpu".to_string(),
            },
            CsvColumnSpec {
                index: 2,
                name: "mem".to_string(),
            },
            CsvColumnSpec {
                index: 3,
                name: "disk_io".to_string(),
            },
        ];
        let config = csv_replay_config("parent", None, Some(cols));
        let result = expand_scenario(config).expect("must succeed");

        assert_eq!(result.len(), 3);
        assert_eq!(result[0].name, "cpu");
        assert_eq!(result[1].name, "mem");
        assert_eq!(result[2].name, "disk_io");

        // Verify each has the correct column index
        for (i, expected_col) in [(0, 1), (1, 2), (2, 3)] {
            match &result[i].generator {
                GeneratorConfig::CsvReplay { column, .. } => {
                    assert_eq!(*column, Some(expected_col), "config[{i}] column");
                }
                other => panic!("expected CsvReplay, got {other:?}"),
            }
        }
    }

    // -----------------------------------------------------------------------
    // expand_scenario: inherited fields
    // -----------------------------------------------------------------------

    /// Expanded configs inherit all schedule/delivery fields from the parent.
    #[test]
    fn expanded_configs_inherit_parent_fields() {
        let cols = vec![CsvColumnSpec {
            index: 1,
            name: "metric_a".to_string(),
        }];
        let config = csv_replay_config("parent", None, Some(cols));
        let result = expand_scenario(config).expect("must succeed");

        assert_eq!(result.len(), 1);
        let child = &result[0];

        // Schedule fields
        assert_eq!(child.rate, 10.0, "rate must be inherited");
        assert_eq!(
            child.duration.as_deref(),
            Some("30s"),
            "duration must be inherited"
        );

        // Labels
        let labels = child.labels.as_ref().expect("labels must be inherited");
        assert_eq!(labels.get("host").map(|s| s.as_str()), Some("srv1"));

        // Jitter
        assert_eq!(child.jitter, Some(0.5));
        assert_eq!(child.jitter_seed, Some(42));

        // Encoder and sink
        assert!(matches!(
            child.encoder,
            EncoderConfig::PrometheusText { .. }
        ));
        assert!(matches!(child.sink, SinkConfig::Stdout));
    }

    /// Expanded configs inherit non-None schedule fields (gaps, bursts) from the parent.
    #[test]
    fn expanded_configs_inherit_non_none_gaps_and_bursts() {
        let cols = vec![CsvColumnSpec {
            index: 1,
            name: "metric_a".to_string(),
        }];
        let mut config = csv_replay_config("parent", None, Some(cols));
        config.base.gaps = Some(GapConfig {
            every: "2m".to_string(),
            r#for: "20s".to_string(),
        });
        config.base.bursts = Some(BurstConfig {
            every: "10s".to_string(),
            r#for: "2s".to_string(),
            multiplier: 3.0,
        });
        let result = expand_scenario(config).expect("must succeed");
        assert_eq!(result.len(), 1);
        let child = &result[0];

        let gaps = child.gaps.as_ref().expect("gaps must be inherited");
        assert_eq!(gaps.every, "2m");
        assert_eq!(gaps.r#for, "20s");

        let bursts = child.bursts.as_ref().expect("bursts must be inherited");
        assert_eq!(bursts.every, "10s");
        assert_eq!(bursts.r#for, "2s");
        assert_eq!(bursts.multiplier, 3.0);
    }

    // -----------------------------------------------------------------------
    // expand_scenario: error — column and columns both set
    // -----------------------------------------------------------------------

    /// Setting both column and columns returns an error.
    #[test]
    fn column_and_columns_both_set_returns_error() {
        let cols = vec![CsvColumnSpec {
            index: 1,
            name: "cpu".to_string(),
        }];
        let config = csv_replay_config("conflict", Some(1), Some(cols));
        let err = expand_scenario(config).expect_err("must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("mutually exclusive"),
            "error must mention mutual exclusivity, got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // expand_scenario: error — empty columns list
    // -----------------------------------------------------------------------

    /// An empty columns list returns an error.
    #[test]
    fn empty_columns_list_returns_error() {
        let config = csv_replay_config("empty", None, Some(vec![]));
        let err = expand_scenario(config).expect_err("must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("must not be empty"),
            "error must mention empty list, got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // expand_scenario: error — duplicate column indices
    // -----------------------------------------------------------------------

    /// Two columns with the same index returns an error.
    #[test]
    fn duplicate_column_index_returns_error() {
        let cols = vec![
            CsvColumnSpec {
                index: 2,
                name: "cpu".to_string(),
            },
            CsvColumnSpec {
                index: 2,
                name: "mem".to_string(),
            },
        ];
        let config = csv_replay_config("dupe_idx", None, Some(cols));
        let err = expand_scenario(config).expect_err("must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate column index 2"),
            "error must mention duplicate index, got: {msg}"
        );
    }

    /// Three columns where only the last two share an index.
    #[test]
    fn duplicate_column_index_not_first_returns_error() {
        let cols = vec![
            CsvColumnSpec {
                index: 1,
                name: "cpu".to_string(),
            },
            CsvColumnSpec {
                index: 3,
                name: "mem".to_string(),
            },
            CsvColumnSpec {
                index: 3,
                name: "disk".to_string(),
            },
        ];
        let config = csv_replay_config("dupe_idx_late", None, Some(cols));
        let err = expand_scenario(config).expect_err("must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate column index 3"),
            "error must mention duplicate index, got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // expand_scenario: error — duplicate column names
    // -----------------------------------------------------------------------

    /// Two columns with the same name returns an error.
    #[test]
    fn duplicate_column_name_returns_error() {
        let cols = vec![
            CsvColumnSpec {
                index: 1,
                name: "cpu".to_string(),
            },
            CsvColumnSpec {
                index: 2,
                name: "cpu".to_string(),
            },
        ];
        let config = csv_replay_config("dupe_name", None, Some(cols));
        let err = expand_scenario(config).expect_err("must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate column name 'cpu'"),
            "error must mention duplicate name, got: {msg}"
        );
    }

    /// Three columns where only the last two share a name.
    #[test]
    fn duplicate_column_name_not_first_returns_error() {
        let cols = vec![
            CsvColumnSpec {
                index: 1,
                name: "cpu".to_string(),
            },
            CsvColumnSpec {
                index: 2,
                name: "mem".to_string(),
            },
            CsvColumnSpec {
                index: 3,
                name: "mem".to_string(),
            },
        ];
        let config = csv_replay_config("dupe_name_late", None, Some(cols));
        let err = expand_scenario(config).expect_err("must fail");
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate column name 'mem'"),
            "error must mention duplicate name, got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // expand_entry: metrics wrapping
    // -----------------------------------------------------------------------

    /// expand_entry wraps expanded metrics configs back in ScenarioEntry::Metrics.
    #[test]
    fn expand_entry_metrics_two_columns() {
        let cols = vec![
            CsvColumnSpec {
                index: 1,
                name: "cpu".to_string(),
            },
            CsvColumnSpec {
                index: 2,
                name: "mem".to_string(),
            },
        ];
        let config = csv_replay_config("parent", None, Some(cols));
        let entry = ScenarioEntry::Metrics(config);
        let result = expand_entry(entry).expect("must succeed");

        assert_eq!(result.len(), 2);
        assert!(matches!(result[0], ScenarioEntry::Metrics(_)));
        assert!(matches!(result[1], ScenarioEntry::Metrics(_)));
    }

    /// expand_entry passes log entries through unchanged.
    #[test]
    fn expand_entry_logs_passes_through() {
        use crate::generator::{LogGeneratorConfig, TemplateConfig};
        use std::collections::BTreeMap;

        let entry = ScenarioEntry::Logs(LogScenarioConfig {
            base: BaseScheduleConfig {
                name: "app_logs".to_string(),
                rate: 10.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                labels: None,
                sink: SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
                dynamic_labels: None,
            },
            generator: LogGeneratorConfig::Template {
                templates: vec![TemplateConfig {
                    message: "test".to_string(),
                    field_pools: BTreeMap::new(),
                }],
                severity_weights: None,
                seed: Some(0),
            },
            encoder: EncoderConfig::JsonLines { precision: None },
        });
        let result = expand_entry(entry).expect("must succeed");
        assert_eq!(result.len(), 1);
        assert!(matches!(result[0], ScenarioEntry::Logs(_)));
    }

    // -----------------------------------------------------------------------
    // HistogramScenarioConfig deserialization
    // -----------------------------------------------------------------------

    /// Histogram config deserializes from YAML with all fields.
    #[test]
    #[cfg(feature = "config")]
    fn histogram_config_deserializes_from_yaml() {
        let yaml = r#"
name: http_request_duration_seconds
rate: 1
duration: 5m
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
distribution:
  type: exponential
  rate: 10.0
observations_per_tick: 100
mean_shift_per_sec: 0.001
seed: 42
labels:
  method: GET
"#;
        let config: HistogramScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.name, "http_request_duration_seconds");
        assert_eq!(config.rate, 1.0);
        assert_eq!(config.buckets.as_ref().unwrap().len(), 11);
        assert_eq!(config.observations_per_tick, Some(100));
        assert_eq!(config.mean_shift_per_sec, Some(0.001));
        assert_eq!(config.seed, Some(42));
    }

    /// Histogram config with omitted optional fields uses defaults.
    #[test]
    #[cfg(feature = "config")]
    fn histogram_config_defaults_when_omitted() {
        let yaml = r#"
name: latency
rate: 1
distribution:
  type: exponential
  rate: 5.0
"#;
        let config: HistogramScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.buckets.is_none());
        assert!(config.observations_per_tick.is_none());
        assert!(config.mean_shift_per_sec.is_none());
        assert!(config.seed.is_none());
    }

    /// Histogram config with normal distribution.
    #[test]
    #[cfg(feature = "config")]
    fn histogram_config_normal_distribution() {
        let yaml = r#"
name: latency
rate: 1
distribution:
  type: normal
  mean: 0.1
  stddev: 0.02
"#;
        let config: HistogramScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        match config.distribution {
            DistributionConfig::Normal { mean, stddev } => {
                assert_eq!(mean, 0.1);
                assert_eq!(stddev, 0.02);
            }
            _ => panic!("expected Normal distribution"),
        }
    }

    /// Histogram config with uniform distribution.
    #[test]
    #[cfg(feature = "config")]
    fn histogram_config_uniform_distribution() {
        let yaml = r#"
name: latency
rate: 1
distribution:
  type: uniform
  min: 0.0
  max: 1.0
"#;
        let config: HistogramScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        match config.distribution {
            DistributionConfig::Uniform { min, max } => {
                assert_eq!(min, 0.0);
                assert_eq!(max, 1.0);
            }
            _ => panic!("expected Uniform distribution"),
        }
    }

    // -----------------------------------------------------------------------
    // SummaryScenarioConfig deserialization
    // -----------------------------------------------------------------------

    /// Summary config deserializes from YAML with all fields.
    #[test]
    #[cfg(feature = "config")]
    fn summary_config_deserializes_from_yaml() {
        let yaml = r#"
name: rpc_duration_seconds
rate: 1
duration: 5m
quantiles: [0.5, 0.9, 0.95, 0.99]
distribution:
  type: normal
  mean: 0.1
  stddev: 0.02
observations_per_tick: 100
seed: 42
"#;
        let config: SummaryScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.name, "rpc_duration_seconds");
        assert_eq!(config.rate, 1.0);
        assert_eq!(config.quantiles.as_ref().unwrap().len(), 4);
        assert_eq!(config.observations_per_tick, Some(100));
        assert_eq!(config.seed, Some(42));
    }

    /// Summary config with omitted optional fields uses defaults.
    #[test]
    #[cfg(feature = "config")]
    fn summary_config_defaults_when_omitted() {
        let yaml = r#"
name: rpc_latency
rate: 1
distribution:
  type: exponential
  rate: 5.0
"#;
        let config: SummaryScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.quantiles.is_none());
        assert!(config.observations_per_tick.is_none());
        assert!(config.seed.is_none());
    }

    // -----------------------------------------------------------------------
    // ScenarioEntry: Histogram and Summary variants
    // -----------------------------------------------------------------------

    /// Multi-scenario YAML with histogram entry deserializes correctly.
    #[test]
    #[cfg(feature = "config")]
    fn multi_scenario_histogram_entry_deserializes() {
        let yaml = r#"
scenarios:
  - signal_type: histogram
    name: http_request_duration_seconds
    rate: 1
    duration: 1m
    distribution:
      type: exponential
      rate: 10.0
"#;
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 1);
        assert!(matches!(config.scenarios[0], ScenarioEntry::Histogram(_)));
    }

    /// Multi-scenario YAML with summary entry deserializes correctly.
    #[test]
    #[cfg(feature = "config")]
    fn multi_scenario_summary_entry_deserializes() {
        let yaml = r#"
scenarios:
  - signal_type: summary
    name: rpc_duration_seconds
    rate: 1
    duration: 1m
    distribution:
      type: normal
      mean: 0.1
      stddev: 0.02
"#;
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 1);
        assert!(matches!(config.scenarios[0], ScenarioEntry::Summary(_)));
    }

    /// Multi-scenario YAML with mixed metrics, logs, histogram, and summary.
    #[test]
    #[cfg(feature = "config")]
    fn multi_scenario_mixed_types_deserialize() {
        let yaml = r#"
scenarios:
  - signal_type: metrics
    name: cpu_usage
    rate: 10
    duration: 1m
    generator:
      type: constant
      value: 1.0
  - signal_type: histogram
    name: latency_hist
    rate: 1
    duration: 1m
    distribution:
      type: exponential
      rate: 10.0
  - signal_type: summary
    name: latency_sum
    rate: 1
    duration: 1m
    distribution:
      type: normal
      mean: 0.1
      stddev: 0.02
"#;
        let config: MultiScenarioConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.scenarios.len(), 3);
        assert!(matches!(config.scenarios[0], ScenarioEntry::Metrics(_)));
        assert!(matches!(config.scenarios[1], ScenarioEntry::Histogram(_)));
        assert!(matches!(config.scenarios[2], ScenarioEntry::Summary(_)));
    }

    /// ScenarioEntry::base() works for histogram entries.
    #[test]
    #[cfg(feature = "config")]
    fn scenario_entry_base_works_for_histogram() {
        let yaml = r#"
signal_type: histogram
name: test_hist
rate: 5
distribution:
  type: exponential
  rate: 10.0
"#;
        let entry: ScenarioEntry = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(entry.base().name, "test_hist");
        assert_eq!(entry.base().rate, 5.0);
    }

    /// ScenarioEntry::base() works for summary entries.
    #[test]
    #[cfg(feature = "config")]
    fn scenario_entry_base_works_for_summary() {
        let yaml = r#"
signal_type: summary
name: test_sum
rate: 5
distribution:
  type: normal
  mean: 0.1
  stddev: 0.02
"#;
        let entry: ScenarioEntry = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(entry.base().name, "test_sum");
        assert_eq!(entry.base().rate, 5.0);
    }

    /// expand_entry passes through Histogram and Summary unchanged.
    #[test]
    fn expand_entry_passes_through_histogram() {
        let entry = ScenarioEntry::Histogram(HistogramScenarioConfig {
            base: BaseScheduleConfig {
                name: "test_hist".to_string(),
                rate: 1.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: crate::sink::SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            buckets: None,
            distribution: DistributionConfig::Exponential { rate: 10.0 },
            observations_per_tick: None,
            mean_shift_per_sec: None,
            seed: None,
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        let result = expand_entry(entry).expect("must succeed");
        assert_eq!(result.len(), 1);
        assert!(matches!(result[0], ScenarioEntry::Histogram(_)));
    }

    /// expand_entry passes through Summary unchanged.
    #[test]
    fn expand_entry_passes_through_summary() {
        let entry = ScenarioEntry::Summary(SummaryScenarioConfig {
            base: BaseScheduleConfig {
                name: "test_sum".to_string(),
                rate: 1.0,
                duration: None,
                gaps: None,
                bursts: None,
                cardinality_spikes: None,
                dynamic_labels: None,
                labels: None,
                sink: crate::sink::SinkConfig::Stdout,
                phase_offset: None,
                clock_group: None,
                jitter: None,
                jitter_seed: None,
            },
            quantiles: None,
            distribution: DistributionConfig::Normal {
                mean: 0.1,
                stddev: 0.02,
            },
            observations_per_tick: None,
            mean_shift_per_sec: None,
            seed: None,
            encoder: EncoderConfig::PrometheusText { precision: None },
        });
        let result = expand_entry(entry).expect("must succeed");
        assert_eq!(result.len(), 1);
        assert!(matches!(result[0], ScenarioEntry::Summary(_)));
    }
}