sonda 1.2.1

CLI for Sonda — synthetic telemetry generator for testing observability pipelines
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
//! Interactive prompt logic for `sonda init`.
//!
//! Uses `dialoguer` for terminal prompts. Every prompt has a sensible default.
//! Questions use operational language ("What situation?"), not generator
//! internals ("sawtooth period").
//!
//! Prompt groups are visually separated by styled section headers with step
//! indicators so the user knows where they are in the flow.
//!
//! ## Features
//!
//! - **Signal types**: metrics, logs, histogram, and summary. Each has its own
//!   section 2 prompt flow. Histogram and summary prompt for distribution model,
//!   observations per tick, and bucket/quantile configuration.
//! - **Pack filtering**: when selecting a metric pack, the list is filtered by
//!   the chosen domain. Falls back to all packs if none match.
//! - **Advanced sinks**: a two-tier sink menu keeps the primary selection simple
//!   (stdout, http_push, file) while offering advanced sinks (remote_write,
//!   loki, otlp_grpc, kafka, tcp, udp) behind an "Advanced..." option.
//! - **Run-now prompt**: after writing the scenario file, asks the user whether
//!   to execute the scenario immediately.
//! - **Prefill support**: when CLI flags or `--from` supply values, each prompt
//!   checks its [`Prefill`] field and uses the value directly when present,
//!   skipping the interactive prompt. Invalid prefill values fall through to
//!   the interactive prompt with a warning.

use std::collections::BTreeMap;
use std::io;
use std::io::IsTerminal;

use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
use owo_colors::OwoColorize;
use owo_colors::Stream::Stderr;

use crate::packs::PackCatalog;

use super::yaml_gen::{
    required_encoder_for_sink, DeliveryAnswers, HistogramAnswers, LogAnswers, MetricAnswers,
    PackAnswers, ParamValue, ScenarioKind, SummaryAnswers,
};

/// Optional pre-filled values for the init prompts.
///
/// When a field is `Some`, it serves as the answer for the corresponding
/// prompt, skipping the interactive question entirely. When a field is `None`,
/// the prompt runs interactively as usual.
///
/// CLI flags and `--from` data are merged into a single `Prefill` before
/// prompts begin. Explicit CLI flags take precedence over `--from` values.
#[derive(Debug, Default, Clone)]
pub struct Prefill {
    /// Signal type: `"metrics"`, `"logs"`, `"histogram"`, or `"summary"`.
    pub signal_type: Option<String>,
    /// Domain category (infrastructure, network, application, custom).
    pub domain: Option<String>,
    /// Operational situation/pattern alias.
    pub situation: Option<String>,
    /// Metric name (or log scenario name).
    pub metric: Option<String>,
    /// Metric pack name (mutually exclusive with `metric` + `situation`).
    pub pack: Option<String>,
    /// Events per second.
    pub rate: Option<f64>,
    /// Scenario duration string (e.g. `"60s"`, `"5m"`).
    pub duration: Option<String>,
    /// Encoder format name.
    pub encoder: Option<String>,
    /// Sink type name.
    pub sink: Option<String>,
    /// Sink endpoint (URL, file path, or host:port).
    pub endpoint: Option<String>,
    /// Static labels to attach to every event.
    pub labels: BTreeMap<String, String>,
    /// Log message template (for logs signal type).
    pub message_template: Option<String>,
    /// Severity distribution preset: `"mostly_info"`, `"balanced"`, or `"error_heavy"`.
    pub severity: Option<String>,
    /// Kafka broker(s) for sink-specific configuration.
    pub kafka_brokers: Option<String>,
    /// Kafka topic for sink-specific configuration.
    pub kafka_topic: Option<String>,
    /// OTLP signal type (`"metrics"` or `"logs"`) for sink-specific configuration.
    pub otlp_signal_type: Option<String>,
}

/// All valid sink type names (primary + advanced), used for prefill validation.
const ALL_SINKS: &[&str] = &[
    "stdout",
    "http_push",
    "file",
    "remote_write",
    "loki",
    "otlp_grpc",
    "kafka",
    "tcp",
    "udp",
];

/// All valid encoder names (metric + log), used for prefill validation.
const ALL_ENCODERS: &[&str] = &[
    "prometheus_text",
    "influx_lp",
    "json_lines",
    "syslog",
    "remote_write",
    "otlp",
];

/// Available operational vocabulary aliases for metric scenarios.
///
/// These match the aliases defined in `sonda-core/src/config/aliases.rs`.
const SITUATIONS: &[&str] = &[
    "steady",
    "spike_event",
    "flap",
    "leak",
    "saturation",
    "degradation",
];

/// Human-readable descriptions for each situation.
const SITUATION_DESCRIPTIONS: &[&str] = &[
    "steady       - stable value with gentle oscillation and noise",
    "spike_event  - baseline with periodic spikes (anomaly testing)",
    "flap         - value toggling between two states (up/down)",
    "leak         - gradual climb to a ceiling (memory leak)",
    "saturation   - repeating fill-and-reset cycles",
    "degradation  - slow ramp with increasing noise",
];

/// Section header width for the styled horizontal rule.
///
/// Shared with `mod.rs` so the welcome banner and section headers use
/// consistent widths.
pub const SECTION_WIDTH: usize = 45;

/// Available metric encoder formats.
const METRIC_ENCODERS: &[&str] = &["prometheus_text", "influx_lp", "json_lines"];

/// Available log encoder formats.
const LOG_ENCODERS: &[&str] = &["json_lines", "syslog"];

/// Primary sink types shown in the first-tier selection menu.
///
/// These are the three most common sinks, keeping the initial prompt simple
/// for new users. The "Advanced..." option opens a second-tier menu with
/// protocol-specific sinks.
const SINKS: &[&str] = &["stdout", "http_push", "file", "Advanced..."];

/// Advanced sink types shown in the second-tier selection menu.
///
/// Each has protocol-specific prompts for endpoint details.
const ADVANCED_SINKS: &[&str] = &["remote_write", "loki", "otlp_grpc", "kafka", "tcp", "udp"];

/// Human-readable descriptions for each advanced sink.
const ADVANCED_SINK_DESCRIPTIONS: &[&str] = &[
    "remote_write  - Prometheus remote write (protobuf + snappy)",
    "loki          - Grafana Loki log push (HTTP)",
    "otlp_grpc     - OpenTelemetry Collector (gRPC)",
    "kafka         - Apache Kafka producer",
    "tcp           - TCP socket (host:port)",
    "udp           - UDP socket (host:port)",
];

/// Available distribution model types for histogram and summary scenarios.
const DISTRIBUTION_MODELS: &[&str] = &["normal", "exponential", "uniform"];

/// Human-readable descriptions for each distribution model.
const DISTRIBUTION_MODEL_DESCRIPTIONS: &[&str] = &[
    "normal       - Gaussian (mean + stddev)",
    "exponential  - latency-style (rate parameter)",
    "uniform      - even spread over [min, max]",
];

/// Available domain categories.
const DOMAINS: &[&str] = &["infrastructure", "network", "application", "custom"];

/// Result of a sink prompt: `(sink_type, endpoint, extra_fields)`.
///
/// The extra fields map carries additional sink-specific configuration for
/// advanced sinks that need more than one endpoint parameter (e.g., kafka
/// brokers + topic).
type SinkPromptResult = (String, Option<String>, BTreeMap<String, String>);

/// Print a styled section header with a step indicator to stderr.
///
/// Renders a dimmed horizontal rule with a bold section title and a step
/// counter (e.g., `[1/4]`). The total width is [`SECTION_WIDTH`] characters.
///
/// # Example output
///
/// ```text
/// ── [1/4] Signal ─────────────────────────────
/// ```
pub fn print_section(step: usize, total: usize, title: &str) {
    let prefix = "\u{2500}\u{2500}";
    let tag = format!("[{step}/{total}]");
    // Display width: "── " (3) + tag + " " + title + " " + tail.
    let prefix_display = 2; // Two box-drawing chars, each 1 column wide.
    let used = prefix_display + 1 + tag.len() + 1 + title.len() + 1;
    let remaining = if SECTION_WIDTH > used {
        SECTION_WIDTH - used
    } else {
        3
    };
    let tail: String = "\u{2500}".repeat(remaining);

    let rule = format!("{prefix} {tag} {title} {tail}");
    eprintln!("\n{}", rule.if_supports_color(Stderr, |t| t.dimmed()));
    eprintln!();
}

/// Run the full interactive prompt flow and return the collected answers.
///
/// Pre-filled values in `prefill` skip their corresponding prompts. When a
/// prefill value is invalid for its prompt (e.g., an unknown domain), a
/// warning is printed and the prompt falls through to interactive mode.
///
/// # Errors
///
/// Returns an I/O error if terminal interaction fails (e.g., stdin is not a TTY).
pub fn run_prompts(
    pack_catalog: &PackCatalog,
    prefill: &Prefill,
) -> Result<(ScenarioKind, DeliveryAnswers), io::Error> {
    let theme = ColorfulTheme::default();

    // Section 1: Signal.
    print_section(1, 4, "Signal");

    let signal_type = prompt_signal_type(&theme, prefill)?;
    let domain = prompt_domain(&theme, prefill)?;

    match signal_type.as_str() {
        "metrics" => run_metrics_prompts(&theme, &domain, pack_catalog, prefill),
        "logs" => run_logs_prompts(&theme, &domain, prefill),
        "histogram" => run_histogram_prompts(&theme, &domain, prefill),
        "summary" => run_summary_prompts(&theme, &domain, prefill),
        _ => unreachable!("signal type is constrained by prompt"),
    }
}

/// Prompt for signal type: metrics, logs, histogram, or summary.
///
/// When `prefill.signal_type` is a valid value, returns it without prompting.
fn prompt_signal_type(theme: &ColorfulTheme, prefill: &Prefill) -> Result<String, io::Error> {
    let items = &["metrics", "logs", "histogram", "summary"];
    if let Some(ref val) = prefill.signal_type {
        if items.contains(&val.as_str()) {
            return Ok(val.clone());
        }
        print_invalid_prefill("signal_type", val, items);
    }
    let selection = Select::with_theme(theme)
        .with_prompt("What type of signal?")
        .items(items)
        .default(0)
        .interact()?;
    Ok(items[selection].to_string())
}

/// Prompt for domain category.
///
/// When `prefill.domain` is a valid value, returns it without prompting.
fn prompt_domain(theme: &ColorfulTheme, prefill: &Prefill) -> Result<String, io::Error> {
    if let Some(ref val) = prefill.domain {
        if DOMAINS.contains(&val.as_str()) {
            return Ok(val.clone());
        }
        print_invalid_prefill("domain", val, DOMAINS);
    }
    let selection = Select::with_theme(theme)
        .with_prompt("What domain?")
        .items(DOMAINS)
        .default(0)
        .interact()?;
    Ok(DOMAINS[selection].to_string())
}

/// Full metrics prompt flow.
fn run_metrics_prompts(
    theme: &ColorfulTheme,
    domain: &str,
    pack_catalog: &PackCatalog,
    prefill: &Prefill,
) -> Result<(ScenarioKind, DeliveryAnswers), io::Error> {
    let available_packs = pack_catalog.list();

    // Section 2: Metric.
    print_section(2, 4, "Metric");

    // If prefill has a pack name, go directly to pack flow.
    let kind = if prefill.pack.is_some() {
        prompt_pack(theme, pack_catalog, domain, prefill)?
    } else if !available_packs.is_empty() && prefill.metric.is_none() && prefill.situation.is_none()
    {
        // Only ask the approach question when packs are available and neither
        // metric name nor situation has been pre-filled.
        let approach_items = &["Single metric", "Use a metric pack"];
        let approach = Select::with_theme(theme)
            .with_prompt("How would you like to define metrics?")
            .items(approach_items)
            .default(0)
            .interact()?;

        match approach {
            0 => prompt_single_metric(theme, prefill)?,
            1 => prompt_pack(theme, pack_catalog, domain, prefill)?,
            _ => unreachable!(),
        }
    } else {
        prompt_single_metric(theme, prefill)?
    };

    // Section 3: Delivery.
    print_section(3, 4, "Delivery");

    let rate = prompt_rate(theme, prefill)?;
    let duration = prompt_duration(theme, prefill)?;
    let encoder = prompt_encoder(theme, METRIC_ENCODERS, prefill)?;
    let (sink, endpoint, sink_extra) = prompt_sink(theme, prefill)?;

    // Enforce encoder/sink pairing: some sinks require a specific encoder.
    let encoder = enforce_encoder_for_sink(encoder, &sink);

    let delivery = DeliveryAnswers {
        domain: domain.to_string(),
        rate,
        duration,
        encoder,
        sink,
        endpoint,
        sink_extra,
    };

    Ok((kind, delivery))
}

/// Full logs prompt flow.
fn run_logs_prompts(
    theme: &ColorfulTheme,
    domain: &str,
    prefill: &Prefill,
) -> Result<(ScenarioKind, DeliveryAnswers), io::Error> {
    // Section 2: Log.
    print_section(2, 4, "Log");

    let name = if let Some(ref val) = prefill.metric {
        val.clone()
    } else {
        Input::with_theme(theme)
            .with_prompt("Log scenario name")
            .default("app_logs".to_string())
            .interact_text()?
    };

    // Message template.
    let message_template = if let Some(ref val) = prefill.message_template {
        val.clone()
    } else {
        Input::with_theme(theme)
            .with_prompt("Message template (use {field} for placeholders)")
            .default("Request to {endpoint} completed with status {status}".to_string())
            .interact_text()?
    };

    // Severity distribution — aligned columns for readability.
    let severity_weights = if let Some(ref val) = prefill.severity {
        match severity_preset_weights(val) {
            Some(weights) => weights,
            None => {
                print_invalid_prefill("severity", val, &["mostly_info", "balanced", "error_heavy"]);
                prompt_severity_interactive(theme)?
            }
        }
    } else {
        prompt_severity_interactive(theme)?
    };

    // Merge prefill labels with interactive labels.
    let labels = prompt_labels(theme, &prefill.labels)?;

    // Section 3: Delivery.
    print_section(3, 4, "Delivery");

    let rate = prompt_rate(theme, prefill)?;
    let duration = prompt_duration(theme, prefill)?;
    let encoder = prompt_encoder(theme, LOG_ENCODERS, prefill)?;
    let (sink, endpoint, sink_extra) = prompt_sink(theme, prefill)?;

    // Enforce encoder/sink pairing: some sinks require a specific encoder.
    let encoder = enforce_encoder_for_sink(encoder, &sink);

    let kind = ScenarioKind::Logs(LogAnswers {
        name,
        message_template,
        severity_weights,
        labels,
    });

    let delivery = DeliveryAnswers {
        domain: domain.to_string(),
        rate,
        duration,
        encoder,
        sink,
        endpoint,
        sink_extra,
    };

    Ok((kind, delivery))
}

/// Full histogram prompt flow.
fn run_histogram_prompts(
    theme: &ColorfulTheme,
    domain: &str,
    prefill: &Prefill,
) -> Result<(ScenarioKind, DeliveryAnswers), io::Error> {
    // Section 2: Histogram.
    print_section(2, 4, "Histogram");

    let name = if let Some(ref val) = prefill.metric {
        val.clone()
    } else {
        Input::with_theme(theme)
            .with_prompt("Metric name")
            .default("http_request_duration_seconds".to_string())
            .interact_text()?
    };

    // When the signal type was prefilled, use sensible defaults for all
    // distribution-related prompts so we never touch the terminal.
    let use_defaults = prefill.signal_type.is_some();

    // Distribution model.
    let distribution_type = if use_defaults {
        "normal".to_string()
    } else {
        let dist_idx = Select::with_theme(theme)
            .with_prompt("Distribution model")
            .items(DISTRIBUTION_MODEL_DESCRIPTIONS)
            .default(0)
            .interact()?;
        DISTRIBUTION_MODELS[dist_idx].to_string()
    };

    // Distribution-specific parameters.
    let distribution_params = if use_defaults {
        default_distribution_params(&distribution_type)
    } else {
        prompt_distribution_params(theme, &distribution_type)?
    };

    // Observations per tick.
    let observations_per_tick: u64 = if use_defaults {
        100
    } else {
        Input::with_theme(theme)
            .with_prompt("Observations per tick")
            .default(100u64)
            .interact_text()?
    };

    // Bucket boundaries.
    let buckets: Option<Vec<f64>> = if use_defaults {
        None
    } else {
        let bucket_items = &["Prometheus defaults", "Custom"];
        let bucket_idx = Select::with_theme(theme)
            .with_prompt("Bucket boundaries")
            .items(bucket_items)
            .default(0)
            .interact()?;
        if bucket_idx == 1 {
            let raw: String = Input::with_theme(theme)
                .with_prompt("Custom buckets (comma-separated floats)")
                .default("0.01, 0.05, 0.1, 0.5, 1.0, 5.0".to_string())
                .interact_text()?;
            let parsed: Vec<f64> = raw
                .split(',')
                .filter_map(|s| s.trim().parse::<f64>().ok())
                .collect();
            if parsed.is_empty() {
                None
            } else {
                Some(parsed)
            }
        } else {
            None
        }
    };

    // Seed.
    let seed: u64 = if use_defaults {
        42
    } else {
        Input::with_theme(theme)
            .with_prompt("RNG seed")
            .default(42u64)
            .interact_text()?
    };

    // Labels.
    let labels = prompt_labels(theme, &prefill.labels)?;

    // Section 3: Delivery.
    print_section(3, 4, "Delivery");

    let rate = prompt_rate(theme, prefill)?;
    let duration = prompt_duration(theme, prefill)?;
    let encoder = prompt_encoder(theme, METRIC_ENCODERS, prefill)?;
    let (sink, endpoint, sink_extra) = prompt_sink(theme, prefill)?;

    let encoder = enforce_encoder_for_sink(encoder, &sink);

    let kind = ScenarioKind::Histogram(HistogramAnswers {
        name,
        distribution_type,
        distribution_params,
        observations_per_tick,
        buckets,
        seed,
        labels,
    });

    let delivery = DeliveryAnswers {
        domain: domain.to_string(),
        rate,
        duration,
        encoder,
        sink,
        endpoint,
        sink_extra,
    };

    Ok((kind, delivery))
}

/// Full summary prompt flow.
fn run_summary_prompts(
    theme: &ColorfulTheme,
    domain: &str,
    prefill: &Prefill,
) -> Result<(ScenarioKind, DeliveryAnswers), io::Error> {
    // Section 2: Summary.
    print_section(2, 4, "Summary");

    let name = if let Some(ref val) = prefill.metric {
        val.clone()
    } else {
        Input::with_theme(theme)
            .with_prompt("Metric name")
            .default("rpc_duration_seconds".to_string())
            .interact_text()?
    };

    // When the signal type was prefilled, use sensible defaults for all
    // distribution-related prompts so we never touch the terminal.
    let use_defaults = prefill.signal_type.is_some();

    // Distribution model.
    let distribution_type = if use_defaults {
        "normal".to_string()
    } else {
        let dist_idx = Select::with_theme(theme)
            .with_prompt("Distribution model")
            .items(DISTRIBUTION_MODEL_DESCRIPTIONS)
            .default(0)
            .interact()?;
        DISTRIBUTION_MODELS[dist_idx].to_string()
    };

    // Distribution-specific parameters.
    let distribution_params = if use_defaults {
        default_distribution_params(&distribution_type)
    } else {
        prompt_distribution_params(theme, &distribution_type)?
    };

    // Observations per tick.
    let observations_per_tick: u64 = if use_defaults {
        100
    } else {
        Input::with_theme(theme)
            .with_prompt("Observations per tick")
            .default(100u64)
            .interact_text()?
    };

    // Quantile targets.
    let quantiles: Option<Vec<f64>> = if use_defaults {
        None
    } else {
        let quantile_items = &["Standard quantiles", "Custom"];
        let quantile_idx = Select::with_theme(theme)
            .with_prompt("Quantile targets")
            .items(quantile_items)
            .default(0)
            .interact()?;
        if quantile_idx == 1 {
            let raw: String = Input::with_theme(theme)
                .with_prompt("Custom quantiles (comma-separated, values in (0,1))")
                .default("0.5, 0.9, 0.95, 0.99".to_string())
                .interact_text()?;
            let parsed: Vec<f64> = raw
                .split(',')
                .filter_map(|s| {
                    let v = s.trim().parse::<f64>().ok()?;
                    if v > 0.0 && v < 1.0 {
                        Some(v)
                    } else {
                        None
                    }
                })
                .collect();
            if parsed.is_empty() {
                None
            } else {
                Some(parsed)
            }
        } else {
            None
        }
    };

    // Seed.
    let seed: u64 = if use_defaults {
        42
    } else {
        Input::with_theme(theme)
            .with_prompt("RNG seed")
            .default(42u64)
            .interact_text()?
    };

    // Labels.
    let labels = prompt_labels(theme, &prefill.labels)?;

    // Section 3: Delivery.
    print_section(3, 4, "Delivery");

    let rate = prompt_rate(theme, prefill)?;
    let duration = prompt_duration(theme, prefill)?;
    let encoder = prompt_encoder(theme, METRIC_ENCODERS, prefill)?;
    let (sink, endpoint, sink_extra) = prompt_sink(theme, prefill)?;

    let encoder = enforce_encoder_for_sink(encoder, &sink);

    let kind = ScenarioKind::Summary(SummaryAnswers {
        name,
        distribution_type,
        distribution_params,
        observations_per_tick,
        quantiles,
        seed,
        labels,
    });

    let delivery = DeliveryAnswers {
        domain: domain.to_string(),
        rate,
        duration,
        encoder,
        sink,
        endpoint,
        sink_extra,
    };

    Ok((kind, delivery))
}

/// Prompt for distribution-specific parameters.
///
/// Each distribution model has its own set of numeric parameters.
fn prompt_distribution_params(
    theme: &ColorfulTheme,
    distribution_type: &str,
) -> Result<Vec<(String, ParamValue)>, io::Error> {
    let params = match distribution_type {
        "normal" => {
            let mean: f64 = Input::with_theme(theme)
                .with_prompt("Mean")
                .default(0.1)
                .interact_text()?;
            let stddev: f64 = Input::with_theme(theme)
                .with_prompt("Standard deviation")
                .default(0.03)
                .interact_text()?;
            vec![
                ("mean".to_string(), ParamValue::Float(mean)),
                ("stddev".to_string(), ParamValue::Float(stddev)),
            ]
        }
        "exponential" => {
            let rate: f64 = Input::with_theme(theme)
                .with_prompt("Rate (lambda)")
                .default(10.0)
                .interact_text()?;
            vec![("rate".to_string(), ParamValue::Float(rate))]
        }
        "uniform" => {
            let min: f64 = Input::with_theme(theme)
                .with_prompt("Min value")
                .default(0.0)
                .interact_text()?;
            let max: f64 = Input::with_theme(theme)
                .with_prompt("Max value")
                .default(1.0)
                .interact_text()?;
            vec![
                ("min".to_string(), ParamValue::Float(min)),
                ("max".to_string(), ParamValue::Float(max)),
            ]
        }
        _ => vec![],
    };
    Ok(params)
}

/// Return sensible default parameters for a distribution model.
///
/// Used when the signal type was prefilled (via CLI flags or `--from`) so that
/// all distribution-related prompts can be skipped without touching the terminal.
/// The defaults match the interactive prompt defaults exactly.
fn default_distribution_params(distribution_type: &str) -> Vec<(String, ParamValue)> {
    match distribution_type {
        "normal" => vec![
            ("mean".to_string(), ParamValue::Float(0.1)),
            ("stddev".to_string(), ParamValue::Float(0.03)),
        ],
        "exponential" => vec![("rate".to_string(), ParamValue::Float(10.0))],
        "uniform" => vec![
            ("min".to_string(), ParamValue::Float(0.0)),
            ("max".to_string(), ParamValue::Float(1.0)),
        ],
        _ => vec![],
    }
}

/// Prompt for a single metric: name, situation, parameters, labels.
fn prompt_single_metric(
    theme: &ColorfulTheme,
    prefill: &Prefill,
) -> Result<ScenarioKind, io::Error> {
    // Metric name.
    let name = if let Some(ref val) = prefill.metric {
        val.clone()
    } else {
        Input::with_theme(theme)
            .with_prompt("Metric name")
            .default("my_metric".to_string())
            .interact_text()?
    };

    // Situation (operational vocabulary).
    let situation = prompt_situation(theme, prefill)?;

    // Situation-specific parameters.
    let situation_params = prompt_situation_params(theme, &situation, prefill)?;

    // Merge prefill labels with interactive labels.
    let labels = prompt_labels(theme, &prefill.labels)?;

    Ok(ScenarioKind::SingleMetric(MetricAnswers {
        name,
        situation,
        situation_params,
        labels,
    }))
}

/// Prompt for an operational situation alias.
///
/// When `prefill.situation` is a valid alias, returns it without prompting.
fn prompt_situation(theme: &ColorfulTheme, prefill: &Prefill) -> Result<String, io::Error> {
    if let Some(ref val) = prefill.situation {
        if SITUATIONS.contains(&val.as_str()) {
            return Ok(val.clone());
        }
        print_invalid_prefill("situation", val, SITUATIONS);
    }
    let situation_idx = Select::with_theme(theme)
        .with_prompt("What situation should this metric simulate?")
        .items(SITUATION_DESCRIPTIONS)
        .default(0)
        .interact()?;
    Ok(SITUATIONS[situation_idx].to_string())
}

/// Prompt for pack selection and pack-specific labels.
///
/// Filters the pack list to show only packs whose `category` matches the
/// selected domain. If no packs match the domain, falls back to showing all
/// packs so the user is never dead-ended.
///
/// When `prefill.pack` names a pack that exists in the catalog, its
/// interactive prompt is skipped.
fn prompt_pack(
    theme: &ColorfulTheme,
    catalog: &PackCatalog,
    domain: &str,
    prefill: &Prefill,
) -> Result<ScenarioKind, io::Error> {
    // If prefill has a pack name, validate it exists in the catalog.
    let pack_name = if let Some(ref prefill_pack) = prefill.pack {
        if catalog.find(prefill_pack).is_some() {
            prefill_pack.clone()
        } else {
            let warning = format!(
                "Pack '{}' not found in catalog, falling through to prompt.",
                prefill_pack
            );
            eprintln!("  {}", warning.if_supports_color(Stderr, |t| t.dimmed()));
            prompt_pack_interactive(theme, catalog, domain)?
        }
    } else {
        prompt_pack_interactive(theme, catalog, domain)?
    };

    // Read the pack YAML to find shared_labels with empty values.
    let mut labels = prefill.labels.clone();

    if let Some(Ok(yaml_content)) = catalog.read_yaml(&pack_name) {
        // Parse shared_labels to find required values.
        if let Ok(pack_def) =
            serde_yaml_ng::from_str::<sonda_core::packs::MetricPackDef>(&yaml_content)
        {
            if let Some(shared_labels) = &pack_def.shared_labels {
                for (key, value) in shared_labels {
                    // Skip keys already provided via prefill.
                    if labels.contains_key(key) {
                        continue;
                    }
                    if value.is_empty() {
                        // Prompt the user for this label value.
                        let label_value: String = Input::with_theme(theme)
                            .with_prompt(format!("Value for label '{key}'"))
                            .default(format!("my-{key}"))
                            .interact_text()?;
                        labels.insert(key.clone(), label_value);
                    } else {
                        // Carry forward the default value from the pack.
                        labels.insert(key.clone(), value.clone());
                    }
                }
            }
        }
    }

    // Ask for any additional labels. When prefill already has labels, pass
    // them through so prompt_labels returns immediately. Otherwise the TTY
    // guard inside prompt_labels handles non-interactive mode.
    if prefill.labels.is_empty() {
        let empty = BTreeMap::new();
        let extra_labels = prompt_labels(theme, &empty)?;
        for (k, v) in extra_labels {
            labels.insert(k, v);
        }
    }

    Ok(ScenarioKind::Pack(PackAnswers { pack_name, labels }))
}

/// Interactive pack selection prompt (extracted for prefill fallthrough).
fn prompt_pack_interactive(
    theme: &ColorfulTheme,
    catalog: &PackCatalog,
    domain: &str,
) -> Result<String, io::Error> {
    let domain_packs = catalog.list_by_category(domain);

    let packs_to_show = if domain_packs.is_empty() {
        eprintln!(
            "  {}",
            format!("No packs found for domain \"{domain}\", showing all packs.")
                .if_supports_color(Stderr, |t| t.dimmed()),
        );
        catalog.list().iter().collect()
    } else {
        eprintln!(
            "  {}",
            format!("Showing packs for domain: {domain}").if_supports_color(Stderr, |t| t.dimmed()),
        );
        domain_packs
    };

    let pack_names: Vec<String> = packs_to_show
        .iter()
        .map(|p| {
            format!(
                "{} - {} ({} metrics)",
                p.name, p.description, p.metric_count
            )
        })
        .collect();

    let pack_idx = Select::with_theme(theme)
        .with_prompt("Which metric pack?")
        .items(&pack_names)
        .default(0)
        .interact()?;

    let selected_pack = packs_to_show[pack_idx];
    Ok(selected_pack.name.clone())
}

/// Return the default situation-specific parameters for a known alias.
///
/// These defaults match the values used as interactive prompt defaults in
/// [`prompt_situation_params`]. When the situation is prefilled via CLI flags,
/// these defaults are used directly without prompting.
fn default_situation_params(situation: &str) -> Vec<(String, ParamValue)> {
    match situation {
        "steady" => vec![
            ("center".to_string(), ParamValue::Float(50.0)),
            ("amplitude".to_string(), ParamValue::Float(10.0)),
            ("period".to_string(), ParamValue::String("60s".to_string())),
        ],
        "spike_event" => vec![
            ("baseline".to_string(), ParamValue::Float(0.0)),
            ("spike_height".to_string(), ParamValue::Float(100.0)),
            (
                "spike_duration".to_string(),
                ParamValue::String("10s".to_string()),
            ),
            (
                "spike_interval".to_string(),
                ParamValue::String("30s".to_string()),
            ),
        ],
        "flap" => vec![
            ("up_value".to_string(), ParamValue::Float(1.0)),
            ("down_value".to_string(), ParamValue::Float(0.0)),
            (
                "up_duration".to_string(),
                ParamValue::String("10s".to_string()),
            ),
            (
                "down_duration".to_string(),
                ParamValue::String("5s".to_string()),
            ),
        ],
        "leak" => vec![
            ("baseline".to_string(), ParamValue::Float(0.0)),
            ("ceiling".to_string(), ParamValue::Float(100.0)),
            (
                "time_to_ceiling".to_string(),
                ParamValue::String("10m".to_string()),
            ),
        ],
        "saturation" => vec![
            ("baseline".to_string(), ParamValue::Float(0.0)),
            ("ceiling".to_string(), ParamValue::Float(100.0)),
            (
                "time_to_saturate".to_string(),
                ParamValue::String("5m".to_string()),
            ),
        ],
        "degradation" => vec![
            ("baseline".to_string(), ParamValue::Float(0.0)),
            ("ceiling".to_string(), ParamValue::Float(100.0)),
            (
                "time_to_degrade".to_string(),
                ParamValue::String("5m".to_string()),
            ),
            ("noise".to_string(), ParamValue::Float(1.0)),
        ],
        _ => vec![],
    }
}

/// Prompt for situation-specific parameters with sensible defaults.
///
/// Each alias has its own set of parameters matching the fields in
/// `sonda-core/src/config/aliases.rs`.
///
/// When the situation was prefilled (i.e., it came from CLI flags or `--from`),
/// the defaults are used directly without prompting. This enables fully
/// non-interactive operation when the caller already chose a situation.
fn prompt_situation_params(
    theme: &ColorfulTheme,
    situation: &str,
    prefill: &Prefill,
) -> Result<Vec<(String, ParamValue)>, io::Error> {
    // When the situation was prefilled, use defaults silently so we never
    // touch the terminal for situation parameters.
    if prefill.situation.is_some() {
        return Ok(default_situation_params(situation));
    }

    let params = match situation {
        "steady" => {
            let center: f64 = Input::with_theme(theme)
                .with_prompt("Center value")
                .default(50.0)
                .interact_text()?;
            let amplitude: f64 = Input::with_theme(theme)
                .with_prompt("Amplitude (oscillation range)")
                .default(10.0)
                .interact_text()?;
            let period: String = Input::with_theme(theme)
                .with_prompt("Oscillation period")
                .default("60s".to_string())
                .interact_text()?;
            vec![
                ("center".to_string(), ParamValue::Float(center)),
                ("amplitude".to_string(), ParamValue::Float(amplitude)),
                ("period".to_string(), ParamValue::String(period)),
            ]
        }
        "spike_event" => {
            let baseline: f64 = Input::with_theme(theme)
                .with_prompt("Baseline value (between spikes)")
                .default(0.0)
                .interact_text()?;
            let spike_height: f64 = Input::with_theme(theme)
                .with_prompt("Spike height (amount added during spike)")
                .default(100.0)
                .interact_text()?;
            let spike_duration: String = Input::with_theme(theme)
                .with_prompt("Spike duration")
                .default("10s".to_string())
                .interact_text()?;
            let spike_interval: String = Input::with_theme(theme)
                .with_prompt("Spike interval (time between spikes)")
                .default("30s".to_string())
                .interact_text()?;
            vec![
                ("baseline".to_string(), ParamValue::Float(baseline)),
                ("spike_height".to_string(), ParamValue::Float(spike_height)),
                (
                    "spike_duration".to_string(),
                    ParamValue::String(spike_duration),
                ),
                (
                    "spike_interval".to_string(),
                    ParamValue::String(spike_interval),
                ),
            ]
        }
        "flap" => {
            let up_value: f64 = Input::with_theme(theme)
                .with_prompt("Up-state value")
                .default(1.0)
                .interact_text()?;
            let down_value: f64 = Input::with_theme(theme)
                .with_prompt("Down-state value")
                .default(0.0)
                .interact_text()?;
            let up_duration: String = Input::with_theme(theme)
                .with_prompt("Up-state duration")
                .default("10s".to_string())
                .interact_text()?;
            let down_duration: String = Input::with_theme(theme)
                .with_prompt("Down-state duration")
                .default("5s".to_string())
                .interact_text()?;
            vec![
                ("up_value".to_string(), ParamValue::Float(up_value)),
                ("down_value".to_string(), ParamValue::Float(down_value)),
                ("up_duration".to_string(), ParamValue::String(up_duration)),
                (
                    "down_duration".to_string(),
                    ParamValue::String(down_duration),
                ),
            ]
        }
        "leak" => {
            let baseline: f64 = Input::with_theme(theme)
                .with_prompt("Starting value")
                .default(0.0)
                .interact_text()?;
            let ceiling: f64 = Input::with_theme(theme)
                .with_prompt("Ceiling value")
                .default(100.0)
                .interact_text()?;
            let time_to_ceiling: String = Input::with_theme(theme)
                .with_prompt("Time to reach ceiling")
                .default("10m".to_string())
                .interact_text()?;
            vec![
                ("baseline".to_string(), ParamValue::Float(baseline)),
                ("ceiling".to_string(), ParamValue::Float(ceiling)),
                (
                    "time_to_ceiling".to_string(),
                    ParamValue::String(time_to_ceiling),
                ),
            ]
        }
        "saturation" => {
            let baseline: f64 = Input::with_theme(theme)
                .with_prompt("Baseline value")
                .default(0.0)
                .interact_text()?;
            let ceiling: f64 = Input::with_theme(theme)
                .with_prompt("Ceiling value")
                .default(100.0)
                .interact_text()?;
            let time_to_saturate: String = Input::with_theme(theme)
                .with_prompt("Time to saturate")
                .default("5m".to_string())
                .interact_text()?;
            vec![
                ("baseline".to_string(), ParamValue::Float(baseline)),
                ("ceiling".to_string(), ParamValue::Float(ceiling)),
                (
                    "time_to_saturate".to_string(),
                    ParamValue::String(time_to_saturate),
                ),
            ]
        }
        "degradation" => {
            let baseline: f64 = Input::with_theme(theme)
                .with_prompt("Starting value")
                .default(0.0)
                .interact_text()?;
            let ceiling: f64 = Input::with_theme(theme)
                .with_prompt("Ceiling value")
                .default(100.0)
                .interact_text()?;
            let time_to_degrade: String = Input::with_theme(theme)
                .with_prompt("Time to degrade")
                .default("5m".to_string())
                .interact_text()?;
            let noise: f64 = Input::with_theme(theme)
                .with_prompt("Noise amplitude")
                .default(1.0)
                .interact_text()?;
            vec![
                ("baseline".to_string(), ParamValue::Float(baseline)),
                ("ceiling".to_string(), ParamValue::Float(ceiling)),
                (
                    "time_to_degrade".to_string(),
                    ParamValue::String(time_to_degrade),
                ),
                ("noise".to_string(), ParamValue::Float(noise)),
            ]
        }
        _ => vec![],
    };

    Ok(params)
}

/// Return severity weights for a named preset, or `None` if the name is invalid.
///
/// Supported presets:
/// - `"mostly_info"`: info 70%, warn 20%, error 10%
/// - `"balanced"`: info 40%, warn 30%, error 20%, debug 10%
/// - `"error_heavy"`: error 60%, warn 30%, info 10%
fn severity_preset_weights(preset: &str) -> Option<Vec<(String, f64)>> {
    match preset {
        "mostly_info" => Some(vec![
            ("info".to_string(), 0.7),
            ("warn".to_string(), 0.2),
            ("error".to_string(), 0.1),
        ]),
        "balanced" => Some(vec![
            ("info".to_string(), 0.4),
            ("warn".to_string(), 0.3),
            ("error".to_string(), 0.2),
            ("debug".to_string(), 0.1),
        ]),
        "error_heavy" => Some(vec![
            ("error".to_string(), 0.6),
            ("warn".to_string(), 0.3),
            ("info".to_string(), 0.1),
        ]),
        _ => None,
    }
}

/// Interactive severity distribution prompt (extracted for prefill fallthrough).
fn prompt_severity_interactive(theme: &ColorfulTheme) -> Result<Vec<(String, f64)>, io::Error> {
    let severity_items = &[
        "Mostly info   info 70%  warn 20%  error 10%",
        "Balanced      info 40%  warn 30%  error 20%  debug 10%",
        "Error-heavy   error 60%  warn 30%  info 10%",
    ];
    let severity_idx = Select::with_theme(theme)
        .with_prompt("Severity distribution")
        .items(severity_items)
        .default(0)
        .interact()?;
    let weights = match severity_idx {
        0 => vec![
            ("info".to_string(), 0.7),
            ("warn".to_string(), 0.2),
            ("error".to_string(), 0.1),
        ],
        1 => vec![
            ("info".to_string(), 0.4),
            ("warn".to_string(), 0.3),
            ("error".to_string(), 0.2),
            ("debug".to_string(), 0.1),
        ],
        2 => vec![
            ("error".to_string(), 0.6),
            ("warn".to_string(), 0.3),
            ("info".to_string(), 0.1),
        ],
        _ => unreachable!(),
    };
    Ok(weights)
}

/// Prompt for key=value labels, one at a time.
///
/// The user enters labels as `key=value` strings. An empty input ends the
/// label collection. After each successful addition, the accumulated labels
/// are shown in dimmed text so the user can see what has been collected.
///
/// When `prefilled` is non-empty, those labels are returned directly without
/// prompting. When stdin is not a TTY and no labels are prefilled, returns
/// an empty map (non-interactive mode).
fn prompt_labels(
    theme: &ColorfulTheme,
    prefilled: &BTreeMap<String, String>,
) -> Result<BTreeMap<String, String>, io::Error> {
    // If the caller already has labels (from --label flags or --from), use them.
    if !prefilled.is_empty() {
        return Ok(prefilled.clone());
    }

    // Non-interactive: no prefilled labels and no TTY — return empty.
    if !io::stdin().is_terminal() {
        return Ok(BTreeMap::new());
    }

    let mut labels = BTreeMap::new();

    loop {
        let input: String = Input::with_theme(theme)
            .with_prompt("Add a label (key=value, empty to finish)")
            .default(String::new())
            .allow_empty(true)
            .interact_text()?;

        if input.is_empty() {
            break;
        }

        if let Some(pos) = input.find('=') {
            let key = input[..pos].trim().to_string();
            let value = input[pos + 1..].trim().to_string();
            if !key.is_empty() {
                labels.insert(key, value);
                // Show accumulated labels as feedback.
                let summary = format_label_summary(&labels);
                eprintln!("  {}", summary.if_supports_color(Stderr, |t| t.dimmed()));
            }
        } else {
            eprintln!("  Labels must be in key=value format. Try again.");
        }
    }

    Ok(labels)
}

/// Format a label map as a compact `key=value, key=value` summary string.
fn format_label_summary(labels: &BTreeMap<String, String>) -> String {
    let pairs: Vec<String> = labels.iter().map(|(k, v)| format!("{k}={v}")).collect();
    format!("Labels: {}", pairs.join(", "))
}

/// Prompt for events-per-second rate.
///
/// When `prefill.rate` is set and strictly positive, returns it without
/// prompting. Invalid values (zero or negative) print a warning and fall
/// through to the interactive prompt; in non-interactive mode the default
/// `1.0` is used.
fn prompt_rate(theme: &ColorfulTheme, prefill: &Prefill) -> Result<f64, io::Error> {
    if let Some(val) = prefill.rate {
        if val > 0.0 {
            return Ok(val);
        }
        let warning = format!(
            "Invalid --rate value '{}': must be strictly positive. Using default 1.0.",
            val
        );
        eprintln!("  {}", warning.if_supports_color(Stderr, |t| t.dimmed()));
        // In non-interactive mode (all fields prefilled), use the default
        // rather than trying to prompt.
        if !std::io::stdin().is_terminal() {
            return Ok(1.0);
        }
    }
    let rate: f64 = Input::with_theme(theme)
        .with_prompt("Events per second (rate)")
        .default(1.0)
        .interact_text()?;
    Ok(rate)
}

/// Prompt for scenario duration.
///
/// When `prefill.duration` is set and passes basic validation (recognized by
/// `sonda_core::config::validate::parse_duration`), returns it without
/// prompting. Invalid values print a warning and fall through to the
/// interactive prompt; in non-interactive mode the default `"60s"` is used.
fn prompt_duration(theme: &ColorfulTheme, prefill: &Prefill) -> Result<String, io::Error> {
    if let Some(ref val) = prefill.duration {
        if sonda_core::config::validate::parse_duration(val).is_ok() {
            return Ok(val.clone());
        }
        let warning = format!(
            "Invalid --duration value '{}': expected format like 30s, 5m, 1h. Using default 60s.",
            val
        );
        eprintln!("  {}", warning.if_supports_color(Stderr, |t| t.dimmed()));
        if !std::io::stdin().is_terminal() {
            return Ok("60s".to_string());
        }
    }
    let duration: String = Input::with_theme(theme)
        .with_prompt("Duration (e.g., 30s, 5m, 1h)")
        .default("60s".to_string())
        .interact_text()?;
    Ok(duration)
}

/// Prompt for encoder format.
///
/// When `prefill.encoder` is a valid encoder name, returns it without
/// prompting. The value is validated against [`ALL_ENCODERS`], not just the
/// provided `options` slice, because the encoder may be overridden later by
/// sink constraints (e.g., `remote_write`, `otlp`).
fn prompt_encoder(
    theme: &ColorfulTheme,
    options: &[&str],
    prefill: &Prefill,
) -> Result<String, io::Error> {
    if let Some(ref val) = prefill.encoder {
        if ALL_ENCODERS.contains(&val.as_str()) {
            return Ok(val.clone());
        }
        print_invalid_prefill("encoder", val, ALL_ENCODERS);
    }
    let selection = Select::with_theme(theme)
        .with_prompt("Output encoding format")
        .items(options)
        .default(0)
        .interact()?;
    Ok(options[selection].to_string())
}

/// Prompt for sink type and any sink-specific fields.
///
/// Returns `(sink_type, endpoint, extra_fields)` where `extra_fields` carries
/// additional sink-specific configuration (e.g., kafka topic).
///
/// When `prefill.sink` is a valid sink name, skips the sink selection prompt.
/// When `prefill.endpoint` is set, skips the endpoint prompt for sinks that
/// require one.
fn prompt_sink(theme: &ColorfulTheme, prefill: &Prefill) -> Result<SinkPromptResult, io::Error> {
    // If prefill has a valid sink, use it directly — but handle sinks that
    // need extra fields by populating them from prefill or falling through to
    // interactive prompts for just those fields.
    if let Some(ref val) = prefill.sink {
        if ALL_SINKS.contains(&val.as_str()) {
            let sink = val.clone();
            let endpoint = prefill.endpoint.clone();
            let mut extra = BTreeMap::new();

            match sink.as_str() {
                "kafka" => {
                    let brokers = if let Some(ref b) = prefill.kafka_brokers {
                        b.clone()
                    } else {
                        Input::with_theme(theme)
                            .with_prompt("Kafka broker(s) (host:port)")
                            .default("localhost:9092".to_string())
                            .interact_text()?
                    };
                    let topic = if let Some(ref t) = prefill.kafka_topic {
                        t.clone()
                    } else {
                        Input::with_theme(theme)
                            .with_prompt("Kafka topic")
                            .default("sonda-events".to_string())
                            .interact_text()?
                    };
                    extra.insert("brokers".to_string(), brokers);
                    extra.insert("topic".to_string(), topic);
                }
                "otlp_grpc" => {
                    if let Some(ref st) = prefill.otlp_signal_type {
                        extra.insert("signal_type".to_string(), st.clone());
                    } else {
                        let signal_items = &["metrics", "logs"];
                        let signal_idx = Select::with_theme(theme)
                            .with_prompt("OTLP signal type")
                            .items(signal_items)
                            .default(0)
                            .interact()?;
                        extra.insert(
                            "signal_type".to_string(),
                            signal_items[signal_idx].to_string(),
                        );
                    }
                }
                _ => {}
            }

            return Ok((sink, endpoint, extra));
        }
        print_invalid_prefill("sink", val, ALL_SINKS);
    }

    let sink_idx = Select::with_theme(theme)
        .with_prompt("Where should output be sent?")
        .items(SINKS)
        .default(0)
        .interact()?;

    let selected = SINKS[sink_idx];

    // If user chose "Advanced...", show the second-tier menu.
    if selected == "Advanced..." {
        return prompt_advanced_sink(theme);
    }

    let sink = selected.to_string();
    let extra = BTreeMap::new();

    let endpoint = match sink.as_str() {
        "http_push" => {
            let url: String = Input::with_theme(theme)
                .with_prompt("Endpoint URL")
                .default("http://localhost:9090/api/v1/write".to_string())
                .interact_text()?;
            Some(url)
        }
        "file" => {
            let path: String = Input::with_theme(theme)
                .with_prompt("Output file path")
                .default("/tmp/sonda-output.txt".to_string())
                .interact_text()?;
            Some(path)
        }
        _ => None,
    };

    Ok((sink, endpoint, extra))
}

/// Prompt for an advanced sink from the second-tier menu.
///
/// Each advanced sink has its own endpoint/connection prompts appropriate
/// to the protocol.
fn prompt_advanced_sink(theme: &ColorfulTheme) -> Result<SinkPromptResult, io::Error> {
    eprintln!(
        "  {}",
        "Advanced sinks may require feature flags at compile time."
            .if_supports_color(Stderr, |t| t.dimmed()),
    );

    let adv_idx = Select::with_theme(theme)
        .with_prompt("Which advanced sink?")
        .items(ADVANCED_SINK_DESCRIPTIONS)
        .default(0)
        .interact()?;

    let sink = ADVANCED_SINKS[adv_idx].to_string();
    let mut extra = BTreeMap::new();

    let endpoint = match sink.as_str() {
        "remote_write" => {
            let url: String = Input::with_theme(theme)
                .with_prompt("Remote write endpoint URL")
                .default("http://localhost:8428/api/v1/write".to_string())
                .interact_text()?;
            Some(url)
        }
        "loki" => {
            let url: String = Input::with_theme(theme)
                .with_prompt("Loki base URL")
                .default("http://localhost:3100".to_string())
                .interact_text()?;
            Some(url)
        }
        "otlp_grpc" => {
            let endpoint_url: String = Input::with_theme(theme)
                .with_prompt("OTLP gRPC endpoint")
                .default("http://localhost:4317".to_string())
                .interact_text()?;
            let signal_items = &["metrics", "logs"];
            let signal_idx = Select::with_theme(theme)
                .with_prompt("OTLP signal type")
                .items(signal_items)
                .default(0)
                .interact()?;
            extra.insert(
                "signal_type".to_string(),
                signal_items[signal_idx].to_string(),
            );
            Some(endpoint_url)
        }
        "kafka" => {
            let brokers: String = Input::with_theme(theme)
                .with_prompt("Kafka broker(s) (host:port)")
                .default("localhost:9092".to_string())
                .interact_text()?;
            let topic: String = Input::with_theme(theme)
                .with_prompt("Kafka topic")
                .default("sonda-events".to_string())
                .interact_text()?;
            extra.insert("brokers".to_string(), brokers);
            extra.insert("topic".to_string(), topic);
            None
        }
        "tcp" => {
            let address: String = Input::with_theme(theme)
                .with_prompt("TCP address (host:port)")
                .default("127.0.0.1:9999".to_string())
                .interact_text()?;
            Some(address)
        }
        "udp" => {
            let address: String = Input::with_theme(theme)
                .with_prompt("UDP address (host:port)")
                .default("127.0.0.1:9999".to_string())
                .interact_text()?;
            Some(address)
        }
        _ => None,
    };

    Ok((sink, endpoint, extra))
}

/// Enforce encoder/sink pairing constraints.
///
/// Some sinks require a specific encoder (e.g., `remote_write` sink requires
/// the `remote_write` encoder, `otlp_grpc` requires `otlp`). When the user's
/// chosen encoder does not match the requirement, this function overrides it
/// and prints a dimmed note explaining the change.
///
/// Returns the (possibly overridden) encoder name.
fn enforce_encoder_for_sink(user_encoder: String, sink: &str) -> String {
    if let Some(required) = required_encoder_for_sink(sink) {
        if user_encoder != required {
            let note =
                format!("Encoder overridden to '{required}' (required by the {sink} sink).",);
            eprintln!("  {}", note.if_supports_color(Stderr, |t| t.dimmed()));
            return required.to_string();
        }
    }
    user_encoder
}

/// Prompt the user to run the scenario immediately after writing.
///
/// Returns `true` if the user wants to execute the scenario now.
pub fn prompt_run_now(theme: &ColorfulTheme) -> Result<bool, io::Error> {
    let run_now = Confirm::with_theme(theme)
        .with_prompt("Run it now?")
        .default(true)
        .interact()?;
    Ok(run_now)
}

/// Prompt for the output file path for the generated YAML.
pub fn prompt_output_path(theme: &ColorfulTheme, suggested: &str) -> Result<String, io::Error> {
    let default_path = format!("./scenarios/{suggested}");
    let path: String = Input::with_theme(theme)
        .with_prompt("Output file path")
        .default(default_path)
        .interact_text()?;
    Ok(path)
}

/// Print a dimmed warning when a prefill value is not in the allowed set.
///
/// Informs the user that the provided value was ignored and the interactive
/// prompt will be used instead. Lists the valid options for reference.
fn print_invalid_prefill(field: &str, value: &str, valid: &[&str]) {
    let warning = format!(
        "Invalid --{field} value '{value}', valid options: {}. Falling through to prompt.",
        valid.join(", ")
    );
    eprintln!("  {}", warning.if_supports_color(Stderr, |t| t.dimmed()));
}

#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------------
    // Constants: verify situation list matches aliases.rs
    // -----------------------------------------------------------------------

    #[test]
    fn situations_list_has_all_aliases() {
        // These must match the aliases in sonda-core/src/config/aliases.rs.
        assert!(SITUATIONS.contains(&"steady"));
        assert!(SITUATIONS.contains(&"spike_event"));
        assert!(SITUATIONS.contains(&"flap"));
        assert!(SITUATIONS.contains(&"leak"));
        assert!(SITUATIONS.contains(&"saturation"));
        assert!(SITUATIONS.contains(&"degradation"));
    }

    #[test]
    fn situations_and_descriptions_have_same_length() {
        assert_eq!(
            SITUATIONS.len(),
            SITUATION_DESCRIPTIONS.len(),
            "each situation must have a description"
        );
    }

    #[test]
    fn descriptions_contain_their_situation_name() {
        for (i, &situation) in SITUATIONS.iter().enumerate() {
            assert!(
                SITUATION_DESCRIPTIONS[i].contains(situation),
                "description for '{situation}' must contain the situation name"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Constants: encoder and sink options
    // -----------------------------------------------------------------------

    #[test]
    fn metric_encoders_include_prometheus_text() {
        assert!(METRIC_ENCODERS.contains(&"prometheus_text"));
    }

    #[test]
    fn log_encoders_include_json_lines() {
        assert!(LOG_ENCODERS.contains(&"json_lines"));
    }

    #[test]
    fn sinks_include_stdout() {
        assert!(SINKS.contains(&"stdout"));
    }

    #[test]
    fn domains_include_infrastructure() {
        assert!(DOMAINS.contains(&"infrastructure"));
    }

    // -----------------------------------------------------------------------
    // format_label_summary: accumulated label display
    // -----------------------------------------------------------------------

    #[test]
    fn format_label_summary_single_label() {
        let mut labels = BTreeMap::new();
        labels.insert("instance".to_string(), "web-01".to_string());
        assert_eq!(format_label_summary(&labels), "Labels: instance=web-01");
    }

    #[test]
    fn format_label_summary_multiple_labels_sorted() {
        let mut labels = BTreeMap::new();
        labels.insert("job".to_string(), "node_exporter".to_string());
        labels.insert("instance".to_string(), "web-01".to_string());
        // BTreeMap sorts by key, so instance comes before job.
        assert_eq!(
            format_label_summary(&labels),
            "Labels: instance=web-01, job=node_exporter"
        );
    }

    #[test]
    fn format_label_summary_empty() {
        let labels = BTreeMap::new();
        assert_eq!(format_label_summary(&labels), "Labels: ");
    }

    // -----------------------------------------------------------------------
    // Section header width constant
    // -----------------------------------------------------------------------

    #[test]
    fn section_width_is_reasonable() {
        assert!(
            SECTION_WIDTH >= 30,
            "section width must be wide enough for readable headers"
        );
    }

    // -----------------------------------------------------------------------
    // Constants: advanced sinks
    // -----------------------------------------------------------------------

    #[test]
    fn advanced_sinks_list_has_expected_entries() {
        assert!(ADVANCED_SINKS.contains(&"remote_write"));
        assert!(ADVANCED_SINKS.contains(&"loki"));
        assert!(ADVANCED_SINKS.contains(&"otlp_grpc"));
        assert!(ADVANCED_SINKS.contains(&"kafka"));
        assert!(ADVANCED_SINKS.contains(&"tcp"));
        assert!(ADVANCED_SINKS.contains(&"udp"));
    }

    #[test]
    fn advanced_sinks_and_descriptions_have_same_length() {
        assert_eq!(
            ADVANCED_SINKS.len(),
            ADVANCED_SINK_DESCRIPTIONS.len(),
            "each advanced sink must have a description"
        );
    }

    #[test]
    fn advanced_sink_descriptions_contain_their_name() {
        for (i, &sink) in ADVANCED_SINKS.iter().enumerate() {
            assert!(
                ADVANCED_SINK_DESCRIPTIONS[i].contains(sink),
                "description for '{sink}' must contain the sink name"
            );
        }
    }

    #[test]
    fn primary_sinks_include_advanced_option() {
        assert!(
            SINKS.contains(&"Advanced..."),
            "primary sink menu must include 'Advanced...' option"
        );
    }

    #[test]
    fn primary_sinks_preserve_original_entries() {
        assert!(SINKS.contains(&"stdout"));
        assert!(SINKS.contains(&"http_push"));
        assert!(SINKS.contains(&"file"));
    }

    #[test]
    fn advanced_sinks_do_not_overlap_with_primary() {
        let primary: Vec<&&str> = SINKS.iter().filter(|s| **s != "Advanced...").collect();
        for &adv in ADVANCED_SINKS {
            assert!(
                !primary.contains(&&adv),
                "advanced sink '{adv}' must not appear in primary menu"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Encoder/sink pairing enforcement
    // -----------------------------------------------------------------------

    #[test]
    fn enforce_encoder_overrides_for_remote_write_sink() {
        let result = enforce_encoder_for_sink("prometheus_text".to_string(), "remote_write");
        assert_eq!(result, "remote_write");
    }

    #[test]
    fn enforce_encoder_overrides_for_otlp_grpc_sink() {
        let result = enforce_encoder_for_sink("json_lines".to_string(), "otlp_grpc");
        assert_eq!(result, "otlp");
    }

    #[test]
    fn enforce_encoder_no_op_when_already_correct_remote_write() {
        let result = enforce_encoder_for_sink("remote_write".to_string(), "remote_write");
        assert_eq!(result, "remote_write");
    }

    #[test]
    fn enforce_encoder_no_op_when_already_correct_otlp() {
        let result = enforce_encoder_for_sink("otlp".to_string(), "otlp_grpc");
        assert_eq!(result, "otlp");
    }

    #[test]
    fn enforce_encoder_no_op_for_stdout_sink() {
        let result = enforce_encoder_for_sink("prometheus_text".to_string(), "stdout");
        assert_eq!(result, "prometheus_text");
    }

    #[test]
    fn enforce_encoder_no_op_for_http_push_sink() {
        let result = enforce_encoder_for_sink("influx_lp".to_string(), "http_push");
        assert_eq!(result, "influx_lp");
    }

    #[test]
    fn enforce_encoder_no_op_for_file_sink() {
        let result = enforce_encoder_for_sink("json_lines".to_string(), "file");
        assert_eq!(result, "json_lines");
    }

    #[test]
    fn enforce_encoder_no_op_for_tcp_sink() {
        let result = enforce_encoder_for_sink("prometheus_text".to_string(), "tcp");
        assert_eq!(result, "prometheus_text");
    }

    #[test]
    fn enforce_encoder_no_op_for_loki_sink() {
        let result = enforce_encoder_for_sink("json_lines".to_string(), "loki");
        assert_eq!(result, "json_lines");
    }

    #[test]
    fn enforce_encoder_no_op_for_kafka_sink() {
        let result = enforce_encoder_for_sink("json_lines".to_string(), "kafka");
        assert_eq!(result, "json_lines");
    }

    // -----------------------------------------------------------------------
    // Prefill struct: defaults
    // -----------------------------------------------------------------------

    #[test]
    fn prefill_default_has_all_none_fields() {
        let pf = Prefill::default();
        assert!(pf.signal_type.is_none());
        assert!(pf.domain.is_none());
        assert!(pf.situation.is_none());
        assert!(pf.metric.is_none());
        assert!(pf.pack.is_none());
        assert!(pf.rate.is_none());
        assert!(pf.duration.is_none());
        assert!(pf.encoder.is_none());
        assert!(pf.sink.is_none());
        assert!(pf.endpoint.is_none());
        assert!(pf.labels.is_empty());
        assert!(pf.message_template.is_none());
        assert!(pf.severity.is_none());
        assert!(pf.kafka_brokers.is_none());
        assert!(pf.kafka_topic.is_none());
        assert!(pf.otlp_signal_type.is_none());
    }

    #[test]
    fn prefill_clone_preserves_values() {
        let mut pf = Prefill::default();
        pf.signal_type = Some("metrics".to_string());
        pf.rate = Some(5.0);
        pf.labels.insert("env".to_string(), "staging".to_string());
        let clone = pf.clone();
        assert_eq!(clone.signal_type.as_deref(), Some("metrics"));
        assert_eq!(clone.rate, Some(5.0));
        assert_eq!(clone.labels.get("env").map(String::as_str), Some("staging"));
    }

    // -----------------------------------------------------------------------
    // Validation constants: ALL_SINKS and ALL_ENCODERS
    // -----------------------------------------------------------------------

    #[test]
    fn all_sinks_contains_primary_sinks() {
        for &s in SINKS {
            if s == "Advanced..." {
                continue;
            }
            assert!(
                ALL_SINKS.contains(&s),
                "primary sink '{s}' must be in ALL_SINKS"
            );
        }
    }

    #[test]
    fn all_sinks_contains_advanced_sinks() {
        for &s in ADVANCED_SINKS {
            assert!(
                ALL_SINKS.contains(&s),
                "advanced sink '{s}' must be in ALL_SINKS"
            );
        }
    }

    #[test]
    fn all_encoders_contains_metric_encoders() {
        for &e in METRIC_ENCODERS {
            assert!(
                ALL_ENCODERS.contains(&e),
                "metric encoder '{e}' must be in ALL_ENCODERS"
            );
        }
    }

    #[test]
    fn all_encoders_contains_log_encoders() {
        for &e in LOG_ENCODERS {
            assert!(
                ALL_ENCODERS.contains(&e),
                "log encoder '{e}' must be in ALL_ENCODERS"
            );
        }
    }

    // -----------------------------------------------------------------------
    // default_situation_params: returns correct defaults for each alias
    // -----------------------------------------------------------------------

    #[test]
    fn default_situation_params_steady_has_three_params() {
        let params = default_situation_params("steady");
        assert_eq!(params.len(), 3);
        assert_eq!(params[0].0, "center");
        assert_eq!(params[1].0, "amplitude");
        assert_eq!(params[2].0, "period");
    }

    #[test]
    fn default_situation_params_spike_event_has_four_params() {
        let params = default_situation_params("spike_event");
        assert_eq!(params.len(), 4);
        assert_eq!(params[0].0, "baseline");
        assert_eq!(params[1].0, "spike_height");
        assert_eq!(params[2].0, "spike_duration");
        assert_eq!(params[3].0, "spike_interval");
    }

    #[test]
    fn default_situation_params_flap_has_four_params() {
        let params = default_situation_params("flap");
        assert_eq!(params.len(), 4);
        assert_eq!(params[0].0, "up_value");
        assert_eq!(params[1].0, "down_value");
        assert_eq!(params[2].0, "up_duration");
        assert_eq!(params[3].0, "down_duration");
    }

    #[test]
    fn default_situation_params_leak_has_three_params() {
        let params = default_situation_params("leak");
        assert_eq!(params.len(), 3);
        assert_eq!(params[0].0, "baseline");
        assert_eq!(params[1].0, "ceiling");
        assert_eq!(params[2].0, "time_to_ceiling");
    }

    #[test]
    fn default_situation_params_saturation_has_three_params() {
        let params = default_situation_params("saturation");
        assert_eq!(params.len(), 3);
        assert_eq!(params[0].0, "baseline");
        assert_eq!(params[1].0, "ceiling");
        assert_eq!(params[2].0, "time_to_saturate");
    }

    #[test]
    fn default_situation_params_degradation_has_four_params() {
        let params = default_situation_params("degradation");
        assert_eq!(params.len(), 4);
        assert_eq!(params[0].0, "baseline");
        assert_eq!(params[1].0, "ceiling");
        assert_eq!(params[2].0, "time_to_degrade");
        assert_eq!(params[3].0, "noise");
    }

    #[test]
    fn default_situation_params_unknown_returns_empty() {
        let params = default_situation_params("nonexistent");
        assert!(params.is_empty());
    }

    #[test]
    fn default_situation_params_covers_all_situations() {
        // Every known situation must produce a non-empty params list.
        for &sit in SITUATIONS {
            let params = default_situation_params(sit);
            assert!(
                !params.is_empty(),
                "default_situation_params({sit}) must return non-empty"
            );
        }
    }

    // -----------------------------------------------------------------------
    // severity_preset_weights: preset name → weights mapping
    // -----------------------------------------------------------------------

    #[test]
    fn severity_preset_mostly_info_returns_three_weights() {
        let weights = severity_preset_weights("mostly_info").expect("should be valid");
        assert_eq!(weights.len(), 3);
        assert_eq!(weights[0].0, "info");
    }

    #[test]
    fn severity_preset_balanced_returns_four_weights() {
        let weights = severity_preset_weights("balanced").expect("should be valid");
        assert_eq!(weights.len(), 4);
    }

    #[test]
    fn severity_preset_error_heavy_returns_three_weights() {
        let weights = severity_preset_weights("error_heavy").expect("should be valid");
        assert_eq!(weights.len(), 3);
        assert_eq!(weights[0].0, "error");
    }

    #[test]
    fn severity_preset_invalid_returns_none() {
        assert!(severity_preset_weights("unknown_preset").is_none());
    }

    // -----------------------------------------------------------------------
    // Prefill: new fields default to None
    // -----------------------------------------------------------------------

    #[test]
    fn prefill_default_has_new_fields_none() {
        let pf = Prefill::default();
        assert!(pf.message_template.is_none());
        assert!(pf.severity.is_none());
        assert!(pf.kafka_brokers.is_none());
        assert!(pf.kafka_topic.is_none());
        assert!(pf.otlp_signal_type.is_none());
    }

    // -----------------------------------------------------------------------
    // prompt_labels: prefill and TTY guard
    // -----------------------------------------------------------------------

    #[test]
    fn prompt_labels_returns_prefilled_labels_immediately() {
        let theme = ColorfulTheme::default();
        let mut prefilled = BTreeMap::new();
        prefilled.insert("env".to_string(), "prod".to_string());
        prefilled.insert("region".to_string(), "us-west".to_string());

        let result = prompt_labels(&theme, &prefilled).expect("should succeed");
        assert_eq!(result.len(), 2);
        assert_eq!(result.get("env").map(String::as_str), Some("prod"));
        assert_eq!(result.get("region").map(String::as_str), Some("us-west"));
    }

    #[test]
    fn prompt_labels_with_empty_prefill_returns_empty_in_non_tty() {
        // In CI / test harness, stdin is not a TTY.
        // When prefilled labels are empty AND stdin is not a TTY,
        // prompt_labels must return an empty map without attempting
        // to read from the terminal.
        let theme = ColorfulTheme::default();
        let prefilled = BTreeMap::new();

        // This test only verifies behavior when stdin is NOT a TTY,
        // which is the case in test harnesses and CI environments.
        if !std::io::stdin().is_terminal() {
            let result = prompt_labels(&theme, &prefilled).expect("should succeed");
            assert!(
                result.is_empty(),
                "non-TTY stdin with no prefilled labels must return empty map"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Distribution model constants
    // -----------------------------------------------------------------------

    #[test]
    fn distribution_models_and_descriptions_have_same_length() {
        assert_eq!(
            DISTRIBUTION_MODELS.len(),
            DISTRIBUTION_MODEL_DESCRIPTIONS.len(),
            "each distribution model must have a description"
        );
    }

    #[test]
    fn distribution_model_descriptions_contain_their_name() {
        for (i, &model) in DISTRIBUTION_MODELS.iter().enumerate() {
            assert!(
                DISTRIBUTION_MODEL_DESCRIPTIONS[i].contains(model),
                "description for '{model}' must contain the model name"
            );
        }
    }

    #[test]
    fn distribution_models_include_expected_entries() {
        assert!(DISTRIBUTION_MODELS.contains(&"normal"));
        assert!(DISTRIBUTION_MODELS.contains(&"exponential"));
        assert!(DISTRIBUTION_MODELS.contains(&"uniform"));
    }

    // -----------------------------------------------------------------------
    // default_distribution_params
    // -----------------------------------------------------------------------

    #[test]
    fn default_distribution_params_normal_has_mean_and_stddev() {
        let params = default_distribution_params("normal");
        assert_eq!(params.len(), 2, "normal distribution has two parameters");
        assert_eq!(params[0].0, "mean");
        assert_eq!(params[0].1, ParamValue::Float(0.1));
        assert_eq!(params[1].0, "stddev");
        assert_eq!(params[1].1, ParamValue::Float(0.03));
    }

    #[test]
    fn default_distribution_params_exponential_has_rate() {
        let params = default_distribution_params("exponential");
        assert_eq!(
            params.len(),
            1,
            "exponential distribution has one parameter"
        );
        assert_eq!(params[0].0, "rate");
        assert_eq!(params[0].1, ParamValue::Float(10.0));
    }

    #[test]
    fn default_distribution_params_uniform_has_min_and_max() {
        let params = default_distribution_params("uniform");
        assert_eq!(params.len(), 2, "uniform distribution has two parameters");
        assert_eq!(params[0].0, "min");
        assert_eq!(params[0].1, ParamValue::Float(0.0));
        assert_eq!(params[1].0, "max");
        assert_eq!(params[1].1, ParamValue::Float(1.0));
    }

    #[test]
    fn default_distribution_params_unknown_returns_empty() {
        let params = default_distribution_params("unknown_model");
        assert!(
            params.is_empty(),
            "unknown distribution model returns no parameters"
        );
    }

    #[test]
    fn default_distribution_params_covers_all_models() {
        for &model in DISTRIBUTION_MODELS {
            let params = default_distribution_params(model);
            assert!(
                !params.is_empty(),
                "distribution model '{model}' must have default parameters"
            );
        }
    }
}