sonda 1.7.0

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
2141
2142
//! CLI argument definitions for the `sonda` binary.
//!
//! All argument structs use the clap derive API. No business logic lives here —
//! parsing is separated from config loading in [`crate::config`].

use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};

/// Sonda — synthetic telemetry generator.
///
/// Generate realistic observability signals (metrics, logs, traces) for
/// testing pipelines, validating ingest paths, and simulating failure scenarios.
#[derive(Debug, Parser)]
#[command(name = "sonda", version, about = "Synthetic telemetry generator", styles = clap_styles())]
pub struct Cli {
    /// Suppress all status output (errors are still printed).
    #[arg(short, long, global = true, conflicts_with = "verbose")]
    pub quiet: bool,

    /// Show the resolved configuration at startup, then run normally.
    ///
    /// Mutually exclusive with `--quiet`. Prints the full resolved scenario
    /// config to stderr before starting the event loop.
    #[arg(short, long, global = true, conflicts_with = "quiet")]
    pub verbose: bool,

    /// Parse and validate the scenario config, print it, then exit without
    /// emitting any events.
    ///
    /// Useful for checking that a YAML file is valid and seeing the resolved
    /// configuration. Works with all subcommands. Orthogonal to `--quiet` and
    /// `--verbose` — always prints the resolved config.
    #[arg(long, global = true)]
    pub dry_run: bool,

    /// Directory containing metric pack YAML files.
    ///
    /// When provided, this is the **sole** search path for packs — the
    /// `SONDA_PACK_PATH` env var and default directories (`./packs/`,
    /// `~/.sonda/packs/`) are not consulted. Useful for one-off testing
    /// with a custom pack collection.
    #[arg(long, global = true)]
    pub pack_path: Option<PathBuf>,

    /// Directory containing scenario YAML files.
    ///
    /// When provided, this is the **sole** search path for scenarios — the
    /// `SONDA_SCENARIO_PATH` env var and default directories (`./scenarios/`,
    /// `~/.sonda/scenarios/`) are not consulted. Useful for one-off testing
    /// with a custom scenario collection.
    #[arg(long, global = true)]
    pub scenario_path: Option<PathBuf>,

    /// Output format for `--dry-run` on v2 scenario files: `text` (default)
    /// or `json`.
    ///
    /// Only consulted in combination with `--dry-run` on v2 files. Text
    /// output goes to stderr (spec §5 pretty format); JSON output goes to
    /// stdout with a stable DTO shape.
    #[arg(long, global = true, value_name = "FORMAT")]
    pub format: Option<String>,

    /// The operation to perform.
    #[command(subcommand)]
    pub command: Commands,
}

/// Verbosity level derived from `--quiet` / `--verbose` flags.
///
/// `--quiet` and `--verbose` are mutually exclusive (enforced by clap's
/// `conflicts_with`). The default is [`Verbosity::Normal`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verbosity {
    /// Suppress all banners and status output.
    Quiet,
    /// Default: show start and stop banners.
    Normal,
    /// Show resolved config at startup, then start and stop banners.
    Verbose,
}

impl Verbosity {
    /// Construct a [`Verbosity`] from the `--quiet` and `--verbose` booleans.
    ///
    /// Clap enforces mutual exclusivity, so at most one of `quiet` and
    /// `verbose` is true.
    pub fn from_flags(quiet: bool, verbose: bool) -> Self {
        if quiet {
            Verbosity::Quiet
        } else if verbose {
            Verbosity::Verbose
        } else {
            Verbosity::Normal
        }
    }
}

/// Top-level subcommands.
#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Generate synthetic metrics and write them to the configured sink.
    Metrics(MetricsArgs),
    /// Generate synthetic log events and write them to the configured sink.
    Logs(LogsArgs),
    /// Generate synthetic histogram metrics (bucket, count, sum series).
    ///
    /// Produces Prometheus-style histogram data with cumulative bucket counts.
    /// Requires a `--scenario` file with histogram-specific configuration
    /// (distribution model, bucket boundaries, observations per tick).
    Histogram(HistogramArgs),
    /// Generate synthetic summary metrics (quantile, count, sum series).
    ///
    /// Produces Prometheus-style summary data with pre-computed quantile values.
    /// Requires a `--scenario` file with summary-specific configuration
    /// (distribution model, quantile targets, observations per tick).
    Summary(SummaryArgs),
    /// Run multiple scenarios concurrently from a v2 scenario YAML file.
    ///
    /// The scenario file must declare `version: 2` at the top level and
    /// carry a `scenarios:` list. Each entry specifies a `signal_type` of
    /// `metrics`, `logs`, `histogram`, or `summary` plus the scenario-specific
    /// configuration fields. Pack references (`pack: <name>`) resolve against
    /// the `--pack-path` / `SONDA_PACK_PATH` catalog and expand to one runtime
    /// entry per pack metric. v1 YAML shapes are rejected with a migration hint.
    Run(RunArgs),
    /// Browse, inspect, and run scenarios and metric packs from the
    /// filesystem search paths.
    ///
    /// Unified replacement for `sonda scenarios` + `sonda packs`. Use
    /// `list` to discover entries (filter with `--type scenario|pack` or
    /// `--category`), `show <name>` to dump YAML with a metadata header,
    /// and `run <name>` to execute a v2 scenario or expand a pack with
    /// `--label key=value` overrides.
    Catalog(CatalogArgs),
    /// (Hidden) Legacy scenario subcommand. Use `sonda catalog` instead.
    #[command(hide = true)]
    Scenarios(ScenariosArgs),
    /// (Hidden) Legacy pack subcommand. Use `sonda catalog` instead.
    #[command(hide = true)]
    Packs(PacksArgs),
    /// Import a CSV file: detect time-series patterns and generate a scenario.
    ///
    /// Analyzes numeric columns in a CSV file, detects dominant patterns
    /// (steady, spike, climb, flap, sawtooth, step), and generates a portable
    /// scenario YAML that uses sonda generators instead of `csv_replay`.
    ///
    /// Use `--analyze` for read-only pattern analysis, `-o` to write a
    /// scenario file, or `--run` to generate and immediately execute.
    Import(ImportArgs),
    /// Interactively create a new scenario YAML file.
    ///
    /// Walks through a guided prompt flow asking domain-relevant questions
    /// (signal type, situation, rate, etc.) and generates a valid, runnable
    /// scenario YAML. Uses operational language — "What situation?" not
    /// "Which generator type?".
    ///
    /// The generated YAML can be immediately run with `sonda run --scenario`.
    Init(InitArgs),
}

/// Arguments for the `histogram` subcommand.
///
/// Requires a `--scenario` file — histogram scenarios are too complex for
/// inline CLI flags alone.
#[derive(Debug, Args)]
pub struct HistogramArgs {
    /// Path to a YAML histogram scenario file.
    ///
    /// The file must contain a histogram scenario configuration with a
    /// `distribution` field specifying the observation model.
    #[arg(long)]
    pub scenario: PathBuf,

    /// Behavior when a sink write fails mid-run: `warn` (default) or `fail`.
    #[arg(long, value_parser = parse_on_sink_error)]
    pub on_sink_error: Option<sonda_core::OnSinkError>,
}

/// Arguments for the `summary` subcommand.
///
/// Requires a `--scenario` file — summary scenarios are too complex for
/// inline CLI flags alone.
#[derive(Debug, Args)]
pub struct SummaryArgs {
    /// Path to a YAML summary scenario file.
    ///
    /// The file must contain a summary scenario configuration with a
    /// `distribution` field specifying the observation model.
    #[arg(long)]
    pub scenario: PathBuf,

    /// Behavior when a sink write fails mid-run: `warn` (default) or `fail`.
    #[arg(long, value_parser = parse_on_sink_error)]
    pub on_sink_error: Option<sonda_core::OnSinkError>,
}

/// Arguments for the `metrics` subcommand.
///
/// All flags are optional when a `--scenario` file is provided. CLI flags take
/// precedence over any value in the scenario file.
#[derive(Debug, Args)]
pub struct MetricsArgs {
    /// Path to a YAML scenario file.
    ///
    /// When provided, the file is loaded and deserialized first. Any CLI flag
    /// that is also present overrides the corresponding value in the file.
    #[arg(long)]
    pub scenario: Option<PathBuf>,

    /// Metric name emitted by this scenario.
    ///
    /// Must be a valid Prometheus metric name: `[a-zA-Z_:][a-zA-Z0-9_:]*`.
    /// Required when no `--scenario` file is provided.
    #[arg(long)]
    pub name: Option<String>,

    /// Target event rate in events per second.
    ///
    /// Must be strictly positive. Fractional values are supported for
    /// sub-Hz rates (e.g. `0.5` for one event every two seconds).
    /// Required when no `--scenario` file is provided.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Total run duration (e.g. `"30s"`, `"5m"`, `"1h"`, `"100ms"`).
    ///
    /// When absent the scenario runs indefinitely until Ctrl+C.
    #[arg(long)]
    pub duration: Option<String>,

    /// Value generator mode.
    ///
    /// Accepted values: `constant`, `uniform`, `sine`, `sawtooth`.
    /// Defaults to `constant` when no scenario file is provided and this
    /// flag is omitted.
    #[arg(long, help_heading = "Generator")]
    pub value_mode: Option<String>,

    /// Sine wave amplitude (half the peak-to-peak swing).
    ///
    /// Used when `--value-mode sine`. Default: `1.0`.
    #[arg(long, help_heading = "Generator")]
    pub amplitude: Option<f64>,

    /// Sine wave or sawtooth period in seconds.
    ///
    /// Used when `--value-mode sine` or `--value-mode sawtooth`. Default: `60.0`.
    #[arg(long, help_heading = "Generator")]
    pub period_secs: Option<f64>,

    /// Fixed value emitted by the `constant` generator.
    ///
    /// Only valid when `--value-mode` is `constant` (the default).
    #[arg(long, help_heading = "Generator")]
    pub value: Option<f64>,

    /// Sine wave vertical offset.
    ///
    /// Sets the midpoint around which the wave oscillates. Used when
    /// `--value-mode sine`. Default: `0.0`.
    #[arg(long, help_heading = "Generator")]
    pub offset: Option<f64>,

    /// Minimum value for the `uniform` generator.
    ///
    /// Used when `--value-mode uniform`. Default: `0.0`.
    #[arg(long, help_heading = "Generator")]
    pub min: Option<f64>,

    /// Maximum value for the `uniform` generator.
    ///
    /// Used when `--value-mode uniform`. Default: `1.0`.
    #[arg(long, help_heading = "Generator")]
    pub max: Option<f64>,

    /// RNG seed for the `uniform` generator (enables deterministic replay).
    ///
    /// When absent a seed of `0` is used.
    #[arg(long, help_heading = "Generator")]
    pub seed: Option<u64>,

    /// Gap recurrence interval (e.g. `"2m"`).
    ///
    /// Together with `--gap-for`, this defines a recurring silent period:
    /// no events are emitted for `--gap-for` out of every `--gap-every` cycle.
    /// Both `--gap-every` and `--gap-for` must be provided together.
    #[arg(long, help_heading = "Schedule")]
    pub gap_every: Option<String>,

    /// Gap duration within each cycle (e.g. `"20s"`).
    ///
    /// Must be strictly less than `--gap-every`.
    #[arg(long, help_heading = "Schedule")]
    pub gap_for: Option<String>,

    /// Burst recurrence interval (e.g. `"10s"`).
    ///
    /// Together with `--burst-for` and `--burst-multiplier`, this defines a
    /// recurring high-rate period: events are emitted at `rate * multiplier`
    /// for `--burst-for` out of every `--burst-every` cycle.
    /// All three `--burst-*` flags must be provided together.
    #[arg(long, help_heading = "Schedule")]
    pub burst_every: Option<String>,

    /// Burst duration within each cycle (e.g. `"1s"`).
    ///
    /// Must be strictly less than `--burst-every`.
    #[arg(long, help_heading = "Schedule")]
    pub burst_for: Option<String>,

    /// Rate multiplier during each burst (must be strictly positive, e.g. `10.0`).
    ///
    /// Effective rate during burst = base rate × multiplier.
    #[arg(long, help_heading = "Schedule")]
    pub burst_multiplier: Option<f64>,

    /// Label key for a cardinality spike (e.g. `"pod_name"`).
    ///
    /// Together with `--spike-every`, `--spike-for`, and `--spike-cardinality`,
    /// defines a recurring window that injects dynamic label values to simulate
    /// cardinality explosions. All four `--spike-*` flags must be provided together.
    #[arg(long, help_heading = "Schedule")]
    pub spike_label: Option<String>,

    /// Spike recurrence interval (e.g. `"2m"`).
    #[arg(long, help_heading = "Schedule")]
    pub spike_every: Option<String>,

    /// Spike duration within each cycle (e.g. `"30s"`).
    ///
    /// Must be strictly less than `--spike-every`.
    #[arg(long, help_heading = "Schedule")]
    pub spike_for: Option<String>,

    /// Number of unique label values during the spike.
    #[arg(long, help_heading = "Schedule")]
    pub spike_cardinality: Option<u64>,

    /// Spike strategy: `counter` or `random`. Default: `counter`.
    #[arg(long, help_heading = "Schedule")]
    pub spike_strategy: Option<String>,

    /// Prefix for generated spike label values.
    ///
    /// Defaults to `"{spike_label}_"` when not specified.
    #[arg(long, help_heading = "Schedule")]
    pub spike_prefix: Option<String>,

    /// RNG seed for the `random` spike strategy.
    #[arg(long, help_heading = "Schedule")]
    pub spike_seed: Option<u64>,

    /// Optional jitter amplitude. Adds uniform noise in `[-jitter, +jitter]` to
    /// every generated value for more realistic output.
    #[arg(long, help_heading = "Schedule")]
    pub jitter: Option<f64>,

    /// Optional seed for jitter noise. Defaults to `0` when absent.
    #[arg(long, help_heading = "Schedule")]
    pub jitter_seed: Option<u64>,

    /// Behavior when a sink write fails mid-run: `warn` (default) or `fail`.
    #[arg(long, value_parser = parse_on_sink_error, help_heading = "Schedule")]
    pub on_sink_error: Option<sonda_core::OnSinkError>,

    /// Static label attached to every emitted event (repeatable).
    ///
    /// Format: `key=value`. Keys must match `[a-zA-Z_][a-zA-Z0-9_]*`.
    /// Example: `--label hostname=t0-a1 --label zone=eu1`
    #[arg(long = "label", value_parser = parse_label)]
    pub labels: Vec<(String, String)>,

    /// Output encoder format.
    ///
    /// Accepted values: `prometheus_text`, `influx_lp`, `json_lines`. Default: `prometheus_text`.
    /// When omitted, the YAML scenario file's `encoder` field is used; when
    /// neither is set, `prometheus_text` is the default.
    #[arg(long, help_heading = "Encoder")]
    pub encoder: Option<String>,

    /// Decimal precision for metric values (0--17).
    ///
    /// Limits the number of decimal places in formatted metric values.
    /// When absent, full f64 precision is used. Applies to text-based
    /// encoders (`prometheus_text`, `influx_lp`, `json_lines`).
    #[arg(long, help_heading = "Encoder")]
    pub precision: Option<u8>,

    /// Write output to a file at this path instead of stdout.
    ///
    /// Shorthand for `sink: file` in a YAML scenario. Parent directories are
    /// created automatically if they do not exist. Takes precedence over any
    /// sink configured in the scenario file.
    #[arg(long, conflicts_with = "sink", help_heading = "Sink")]
    pub output: Option<PathBuf>,

    /// Sink type for delivering encoded events.
    ///
    /// Accepted values: `http_push`, `remote_write`, `loki`, `otlp_grpc`, `kafka`.
    /// Mutually exclusive with `--output`. For OTLP, Kafka, and remote write sinks,
    /// the corresponding Cargo feature must be compiled in.
    #[arg(long, conflicts_with = "output", help_heading = "Sink")]
    pub sink: Option<String>,

    /// Endpoint URL for the selected sink.
    ///
    /// Required for `--sink http_push`, `--sink remote_write`, `--sink loki`,
    /// and `--sink otlp_grpc`.
    #[arg(long, help_heading = "Sink")]
    pub endpoint: Option<String>,

    /// OTLP signal type: `metrics` or `logs`.
    ///
    /// Required for `--sink otlp_grpc` in the metrics subcommand (where the
    /// signal type is ambiguous). In the logs subcommand this defaults to `logs`.
    #[arg(long, help_heading = "Sink")]
    pub signal_type: Option<String>,

    /// Batch size for batching sinks (number of entries or bytes, depending on sink).
    ///
    /// Optional for `http_push`, `remote_write`, `loki`, and `otlp_grpc`.
    #[arg(long, help_heading = "Sink")]
    pub batch_size: Option<usize>,

    /// Content-Type header for the `http_push` sink.
    ///
    /// Optional; defaults to `application/octet-stream` when not specified.
    #[arg(long, help_heading = "Sink")]
    pub content_type: Option<String>,

    /// Comma-separated Kafka broker addresses (e.g. `127.0.0.1:9092`).
    ///
    /// Required for `--sink kafka`.
    #[arg(long, help_heading = "Sink")]
    pub brokers: Option<String>,

    /// Kafka topic name.
    ///
    /// Required for `--sink kafka`.
    #[arg(long, help_heading = "Sink")]
    pub topic: Option<String>,

    /// Maximum retry attempts after initial failure.
    ///
    /// Together with `--retry-backoff` and `--retry-max-backoff`, configures
    /// exponential backoff retry for network sinks. All three flags must be
    /// provided together.
    #[arg(long, help_heading = "Sink")]
    pub retry_max_attempts: Option<u32>,

    /// Initial backoff duration for retries (e.g. `"100ms"`, `"1s"`).
    ///
    /// Must be provided together with `--retry-max-attempts` and
    /// `--retry-max-backoff`.
    #[arg(long, help_heading = "Sink")]
    pub retry_backoff: Option<String>,

    /// Maximum backoff cap for retries (e.g. `"5s"`, `"30s"`).
    ///
    /// Must be >= `--retry-backoff`. Must be provided together with
    /// `--retry-max-attempts` and `--retry-backoff`.
    #[arg(long, help_heading = "Sink")]
    pub retry_max_backoff: Option<String>,
}

/// Arguments for the `logs` subcommand.
///
/// All flags are optional when a `--scenario` file is provided. CLI flags take
/// precedence over any value in the scenario file.
#[derive(Debug, Args)]
pub struct LogsArgs {
    /// Path to a YAML log scenario file.
    ///
    /// When provided, the file is loaded and deserialized first. Any CLI flag
    /// that is also present overrides the corresponding value in the file.
    #[arg(long)]
    pub scenario: Option<PathBuf>,

    /// Log generator mode.
    ///
    /// Accepted values: `template`, `replay`.
    /// Required when no `--scenario` file is provided.
    #[arg(long, help_heading = "Generator")]
    pub mode: Option<String>,

    /// Path to a log file for use with `--mode replay`.
    ///
    /// Lines from this file are replayed in order, cycling back to the start
    /// when exhausted. `--replay-file` is accepted as an alias for this flag.
    #[arg(long, alias = "replay-file", help_heading = "Generator")]
    pub file: Option<String>,

    /// Target event rate in events per second.
    ///
    /// Must be strictly positive. Defaults to `10.0` when no scenario file
    /// is provided and this flag is omitted.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Total run duration (e.g. `"30s"`, `"5m"`, `"1h"`, `"100ms"`).
    ///
    /// When absent the scenario runs indefinitely until Ctrl+C.
    #[arg(long)]
    pub duration: Option<String>,

    /// Output encoder format.
    ///
    /// Accepted values: `json_lines`, `syslog`. Default: `json_lines`.
    #[arg(long, help_heading = "Encoder")]
    pub encoder: Option<String>,

    /// Decimal precision for numeric values in log fields (0--17).
    ///
    /// Limits the number of decimal places when the encoder formats
    /// numeric values. When absent, full f64 precision is used.
    /// Only applies to `json_lines`; ignored for `syslog`.
    #[arg(long, help_heading = "Encoder")]
    pub precision: Option<u8>,

    /// Static label attached to every emitted event (repeatable).
    ///
    /// Format: `key=value`. Keys must match `[a-zA-Z_][a-zA-Z0-9_]*`.
    /// Example: `--label hostname=t0-a1 --label zone=eu1`
    #[arg(long = "label", value_parser = parse_label)]
    pub labels: Vec<(String, String)>,

    /// Gap recurrence interval (e.g. `"2m"`).
    ///
    /// Together with `--gap-for`, this defines a recurring silent period.
    #[arg(long, help_heading = "Schedule")]
    pub gap_every: Option<String>,

    /// Gap duration within each cycle (e.g. `"20s"`).
    ///
    /// Must be strictly less than `--gap-every`.
    #[arg(long, help_heading = "Schedule")]
    pub gap_for: Option<String>,

    /// Burst recurrence interval (e.g. `"5s"`).
    ///
    /// Together with `--burst-for` and `--burst-multiplier`, this defines a
    /// recurring high-rate period.
    #[arg(long, help_heading = "Schedule")]
    pub burst_every: Option<String>,

    /// Burst duration within each cycle (e.g. `"1s"`).
    ///
    /// Must be strictly less than `--burst-every`.
    #[arg(long, help_heading = "Schedule")]
    pub burst_for: Option<String>,

    /// Rate multiplier during burst periods (e.g. `10.0` for 10× the base rate).
    #[arg(long, help_heading = "Schedule")]
    pub burst_multiplier: Option<f64>,

    /// Label key for a cardinality spike (e.g. `"pod_name"`).
    ///
    /// Together with `--spike-every`, `--spike-for`, and `--spike-cardinality`,
    /// defines a recurring window that injects dynamic label values.
    #[arg(long, help_heading = "Schedule")]
    pub spike_label: Option<String>,

    /// Spike recurrence interval (e.g. `"2m"`).
    #[arg(long, help_heading = "Schedule")]
    pub spike_every: Option<String>,

    /// Spike duration within each cycle (e.g. `"30s"`).
    #[arg(long, help_heading = "Schedule")]
    pub spike_for: Option<String>,

    /// Number of unique label values during the spike.
    #[arg(long, help_heading = "Schedule")]
    pub spike_cardinality: Option<u64>,

    /// Spike strategy: `counter` or `random`. Default: `counter`.
    #[arg(long, help_heading = "Schedule")]
    pub spike_strategy: Option<String>,

    /// Prefix for generated spike label values.
    #[arg(long, help_heading = "Schedule")]
    pub spike_prefix: Option<String>,

    /// RNG seed for the `random` spike strategy.
    #[arg(long, help_heading = "Schedule")]
    pub spike_seed: Option<u64>,

    /// Optional jitter amplitude. Adds uniform noise in `[-jitter, +jitter]` to
    /// every generated value for more realistic output.
    #[arg(long, help_heading = "Schedule")]
    pub jitter: Option<f64>,

    /// Optional seed for jitter noise. Defaults to `0` when absent.
    #[arg(long, help_heading = "Schedule")]
    pub jitter_seed: Option<u64>,

    /// Behavior when a sink write fails mid-run: `warn` (default) or `fail`.
    #[arg(long, value_parser = parse_on_sink_error, help_heading = "Schedule")]
    pub on_sink_error: Option<sonda_core::OnSinkError>,

    /// Write output to a file at this path instead of stdout.
    ///
    /// Shorthand for `sink: file` in a YAML scenario. Takes precedence over
    /// any sink configured in the scenario file.
    #[arg(long, conflicts_with = "sink", help_heading = "Sink")]
    pub output: Option<PathBuf>,

    /// Sink type for delivering encoded events.
    ///
    /// Accepted values: `http_push`, `remote_write`, `loki`, `otlp_grpc`, `kafka`.
    /// Mutually exclusive with `--output`. For OTLP, Kafka, and remote write sinks,
    /// the corresponding Cargo feature must be compiled in.
    #[arg(long, conflicts_with = "output", help_heading = "Sink")]
    pub sink: Option<String>,

    /// Endpoint URL for the selected sink.
    ///
    /// Required for `--sink http_push`, `--sink remote_write`, `--sink loki`,
    /// and `--sink otlp_grpc`.
    #[arg(long, help_heading = "Sink")]
    pub endpoint: Option<String>,

    /// OTLP signal type: `metrics` or `logs`.
    ///
    /// For the logs subcommand this defaults to `logs` when `--sink otlp_grpc`
    /// is used, so typically you do not need to specify it.
    #[arg(long, help_heading = "Sink")]
    pub signal_type: Option<String>,

    /// Batch size for batching sinks (number of entries or bytes, depending on sink).
    ///
    /// Optional for `http_push`, `remote_write`, `loki`, and `otlp_grpc`.
    #[arg(long, help_heading = "Sink")]
    pub batch_size: Option<usize>,

    /// Content-Type header for the `http_push` sink.
    ///
    /// Optional; defaults to `application/octet-stream` when not specified.
    #[arg(long, help_heading = "Sink")]
    pub content_type: Option<String>,

    /// Comma-separated Kafka broker addresses (e.g. `127.0.0.1:9092`).
    ///
    /// Required for `--sink kafka`.
    #[arg(long, help_heading = "Sink")]
    pub brokers: Option<String>,

    /// Kafka topic name.
    ///
    /// Required for `--sink kafka`.
    #[arg(long, help_heading = "Sink")]
    pub topic: Option<String>,

    /// A single static message template for use with `--mode template`.
    ///
    /// Overrides any templates defined in the scenario file. The message string
    /// may contain `{placeholder}` tokens, but no field pools are configured
    /// from the CLI, so placeholders remain as-is unless a scenario file
    /// supplies them.
    #[arg(long, help_heading = "Generator")]
    pub message: Option<String>,

    /// Comma-separated severity weight pairs for `--mode template`.
    ///
    /// Format: `info=0.7,warn=0.2,error=0.1`. Weights are relative — they do
    /// not need to sum to 1.0. Valid severity names: `trace`, `debug`, `info`,
    /// `warn`, `error`, `fatal`.
    #[arg(long = "severity-weights", help_heading = "Generator")]
    pub severity_weights: Option<String>,

    /// RNG seed for deterministic template resolution.
    ///
    /// Used with `--mode template`. When absent a seed of `0` is used.
    #[arg(long, help_heading = "Generator")]
    pub seed: Option<u64>,

    /// Maximum retry attempts after initial failure.
    ///
    /// Together with `--retry-backoff` and `--retry-max-backoff`, configures
    /// exponential backoff retry for network sinks. All three flags must be
    /// provided together.
    #[arg(long, help_heading = "Sink")]
    pub retry_max_attempts: Option<u32>,

    /// Initial backoff duration for retries (e.g. `"100ms"`, `"1s"`).
    ///
    /// Must be provided together with `--retry-max-attempts` and
    /// `--retry-max-backoff`.
    #[arg(long, help_heading = "Sink")]
    pub retry_backoff: Option<String>,

    /// Maximum backoff cap for retries (e.g. `"5s"`, `"30s"`).
    ///
    /// Must be >= `--retry-backoff`. Must be provided together with
    /// `--retry-max-attempts` and `--retry-backoff`.
    #[arg(long, help_heading = "Sink")]
    pub retry_max_backoff: Option<String>,
}

/// Arguments for the `run` subcommand (multi-scenario / v2).
///
/// Accepts any scenario YAML file — v1 single-scenario, v1 multi-scenario,
/// v1 `pack:` shorthand, or v2 (`version: 2`). Dispatch is based on the
/// top-level `version:` field detected at the top of the YAML.
#[derive(Debug, Args)]
pub struct RunArgs {
    /// Path or `@name` reference to a scenario YAML file.
    ///
    /// v2 files are compiled via the full v2 pipeline (defaults →
    /// pack expansion → `after:` resolution → prepare). v1 files go
    /// through the legacy multi-scenario loader. Both produce the same
    /// runtime shape.
    #[arg(long)]
    pub scenario: PathBuf,

    /// Override the scenario duration (e.g. `"10s"`, `"2m"`).
    ///
    /// Applied after compile/expand at the entry level.
    #[arg(long)]
    pub duration: Option<String>,

    /// Override the event rate in events per second.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Override the sink type (e.g. `stdout`, `file`, `tcp`).
    #[arg(long, help_heading = "Sink")]
    pub sink: Option<String>,

    /// Override the sink endpoint (URL, file path, host:port).
    #[arg(long, help_heading = "Sink")]
    pub endpoint: Option<String>,

    /// Override the encoder format.
    #[arg(long, help_heading = "Encoder")]
    pub encoder: Option<String>,

    /// Write output to a file (shorthand for `--sink file --endpoint <path>`).
    ///
    /// Mutually exclusive with `--sink`.
    #[arg(short = 'o', long, conflicts_with = "sink", help_heading = "Sink")]
    pub output: Option<PathBuf>,

    /// Additional labels merged into every entry (format: `key=value`).
    #[arg(long = "label", value_parser = parse_label, help_heading = "Scenario")]
    pub labels: Vec<(String, String)>,

    /// Behavior when a sink write fails mid-run: `warn` (default) or `fail`.
    #[arg(long, value_parser = parse_on_sink_error, help_heading = "Scenario")]
    pub on_sink_error: Option<sonda_core::OnSinkError>,
}

/// Arguments for the `scenarios` subcommand.
///
/// Provides access to scenario files discovered from the filesystem.
#[derive(Debug, Args)]
pub struct ScenariosArgs {
    /// The scenarios action to perform.
    #[command(subcommand)]
    pub action: ScenariosAction,
}

/// Actions available under `sonda scenarios`.
#[derive(Debug, Subcommand)]
pub enum ScenariosAction {
    /// List all available scenarios.
    ///
    /// Prints a formatted table with NAME, CATEGORY, SIGNAL, and DESCRIPTION
    /// columns. Use `--category` to filter by category.
    List(ScenariosListArgs),
    /// Show the raw YAML for a scenario.
    ///
    /// Prints the full YAML content to stdout, suitable for piping to a file
    /// for customization.
    Show(ScenariosShowArgs),
    /// Run a scenario with optional overrides.
    ///
    /// Executes the scenario directly. Use `--duration`, `--rate`, `--sink`,
    /// `--endpoint`, and `--encoder` to override values in the scenario YAML.
    Run(ScenariosRunArgs),
}

/// Arguments for `sonda scenarios list`.
#[derive(Debug, Args)]
pub struct ScenariosListArgs {
    /// Filter scenarios by category (e.g. `infrastructure`, `network`,
    /// `application`, `observability`).
    #[arg(long)]
    pub category: Option<String>,

    /// Output the scenario list as a JSON array instead of a table.
    ///
    /// Each element contains `name`, `category`, `signal_type`,
    /// `description`, and `source` fields.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `sonda scenarios show`.
#[derive(Debug, Args)]
pub struct ScenariosShowArgs {
    /// The kebab-case name of the scenario (e.g. `cpu-spike`).
    pub name: String,
}

/// Arguments for `sonda scenarios run`.
#[derive(Debug, Args)]
pub struct ScenariosRunArgs {
    /// The kebab-case name of the scenario (e.g. `cpu-spike`).
    pub name: String,

    /// Override the scenario duration (e.g. `"10s"`, `"2m"`).
    #[arg(long)]
    pub duration: Option<String>,

    /// Override the event rate in events per second.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Override the sink type (e.g. `stdout`, `file`).
    #[arg(long, help_heading = "Sink")]
    pub sink: Option<String>,

    /// Override the sink endpoint (required for network sinks).
    #[arg(long, help_heading = "Sink")]
    pub endpoint: Option<String>,

    /// Override the encoder format (e.g. `prometheus_text`, `json_lines`).
    #[arg(long, help_heading = "Encoder")]
    pub encoder: Option<String>,
}

/// Arguments for the `packs` subcommand.
///
/// Provides access to metric packs discovered from the filesystem search path.
#[derive(Debug, Args)]
pub struct PacksArgs {
    /// The packs action to perform.
    #[command(subcommand)]
    pub action: PacksAction,
}

/// Actions available under `sonda packs`.
#[derive(Debug, Subcommand)]
pub enum PacksAction {
    /// List all available metric packs found on the search path.
    ///
    /// Prints a formatted table with NAME, CATEGORY, METRICS, DESCRIPTION,
    /// and SOURCE columns. Use `--category` to filter by category.
    List(PacksListArgs),
    /// Show the raw YAML definition for a metric pack.
    ///
    /// Prints the full YAML content to stdout, suitable for piping to a file
    /// for customization.
    Show(PacksShowArgs),
    /// Run a metric pack with the given schedule and delivery options.
    ///
    /// Expands the pack into one metric scenario per metric in the pack, then
    /// runs them all concurrently.
    Run(PacksRunArgs),
}

/// Arguments for `sonda packs list`.
#[derive(Debug, Args)]
pub struct PacksListArgs {
    /// Filter packs by category (e.g. `infrastructure`, `network`).
    #[arg(long)]
    pub category: Option<String>,

    /// Output the pack list as a JSON array instead of a table.
    ///
    /// Each element contains `name`, `category`, `metric_count`,
    /// `description`, and `source` fields.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `sonda packs show`.
#[derive(Debug, Args)]
pub struct PacksShowArgs {
    /// The snake_case name of the pack (e.g. `telegraf_snmp_interface`).
    pub name: String,
}

/// Arguments for `sonda packs run`.
#[derive(Debug, Args)]
pub struct PacksRunArgs {
    /// The snake_case name of the pack (e.g. `telegraf_snmp_interface`).
    pub name: String,

    /// Override the scenario duration (e.g. `"10s"`, `"2m"`).
    #[arg(long)]
    pub duration: Option<String>,

    /// Override the event rate in events per second.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Override the sink type (e.g. `stdout`, `file`).
    #[arg(long, help_heading = "Sink")]
    pub sink: Option<String>,

    /// Override the sink endpoint (required for network sinks).
    #[arg(long, help_heading = "Sink")]
    pub endpoint: Option<String>,

    /// Override the encoder format (e.g. `prometheus_text`, `json_lines`).
    #[arg(long, help_heading = "Encoder")]
    pub encoder: Option<String>,

    /// Write output to a file (shorthand for `--sink file --endpoint <path>`).
    ///
    /// Mutually exclusive with `--sink`. Matches the shape of
    /// [`RunArgs::output`] so `sonda catalog run <pack> -o <path>` and
    /// `sonda packs run <pack> -o <path>` share a single code path.
    #[arg(short = 'o', long, conflicts_with = "sink", help_heading = "Sink")]
    pub output: Option<PathBuf>,

    /// Add or override a label (format: `key=value`). Can be specified
    /// multiple times to set multiple labels.
    #[arg(long = "label", value_parser = parse_label)]
    pub labels: Vec<(String, String)>,
}

/// Arguments for the `import` subcommand.
///
/// Analyzes a CSV file, detects time-series patterns, and generates a
/// portable scenario YAML. Exactly one of `--analyze`, `-o`, or `--run`
/// must be specified (enforced at runtime).
#[derive(Debug, Args)]
pub struct ImportArgs {
    /// Path to the CSV file to import.
    ///
    /// Supports Grafana "Series joined by time" CSV exports and plain CSV
    /// files with a header row. Column 0 is treated as the timestamp.
    pub file: PathBuf,

    /// Print a read-only analysis of detected patterns (no file output).
    ///
    /// For each numeric column, shows the metric name, detected pattern,
    /// and key parameters. Does not generate any YAML.
    #[arg(long, conflicts_with_all = &["output", "run"])]
    pub analyze: bool,

    /// Write the generated scenario YAML to this path.
    ///
    /// Produces a valid, runnable scenario YAML using generators instead of
    /// csv_replay. Use `sonda run --scenario <output>` to execute it.
    #[arg(short, long, conflicts_with_all = &["analyze", "run"])]
    pub output: Option<PathBuf>,

    /// Generate the scenario and immediately execute it (no file output).
    ///
    /// Equivalent to generating with `-o` and then running with
    /// `sonda run --scenario`, but without writing a file.
    #[arg(long, conflicts_with_all = &["analyze", "output"])]
    pub run: bool,

    /// Select specific columns by index (e.g., `1,3,5`).
    ///
    /// Column indices are zero-based. Column 0 is typically the timestamp
    /// and is excluded by default. Without this flag, all non-timestamp
    /// columns are processed.
    #[arg(long)]
    pub columns: Option<String>,

    /// Target event rate in events per second for the generated scenario.
    ///
    /// Used when generating YAML (`-o` or `--run`). Defaults to 1.0.
    #[arg(long, default_value = "1.0")]
    pub rate: f64,

    /// Scenario duration for the generated scenario (e.g., `"60s"`, `"5m"`).
    ///
    /// Used when generating YAML (`-o` or `--run`). Defaults to `"60s"`.
    #[arg(long, default_value = "60s")]
    pub duration: String,
}

/// Arguments for the `init` subcommand.
///
/// All flags are optional. When a flag is provided its value is used directly,
/// skipping the corresponding interactive prompt. When ALL required fields are
/// supplied via flags (signal type, domain, metric/pack, situation, rate,
/// duration, encoder, sink, and output path), `sonda init` runs fully
/// non-interactively — no terminal interaction needed.
///
/// The `--from` flag pre-fills values from a built-in scenario (`@name`) or a
/// CSV file (`path.csv`). Explicit flags override `--from` values.
///
/// For advanced sinks in non-interactive mode, supply the sink-specific flags
/// (`--kafka-brokers`, `--kafka-topic`, `--otlp-signal-type`) alongside
/// `--sink`.
#[derive(Debug, Args)]
pub struct InitArgs {
    /// Start from a built-in scenario (@name) or CSV file (path.csv).
    #[arg(long)]
    pub from: Option<String>,

    /// Signal type: metrics, logs, histogram, or summary.
    #[arg(long)]
    pub signal_type: Option<String>,

    /// Domain category (infrastructure, network, application, custom).
    #[arg(long)]
    pub domain: Option<String>,

    /// Operational situation/pattern (steady, spike_event, flap, leak, saturation, degradation).
    #[arg(long)]
    pub situation: Option<String>,

    /// Metric name.
    #[arg(long)]
    pub metric: Option<String>,

    /// Use a metric pack instead of single metric.
    #[arg(long)]
    pub pack: Option<String>,

    /// Events per second.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Duration (e.g., 60s, 5m).
    #[arg(long)]
    pub duration: Option<String>,

    /// Encoder format (prometheus_text, influx_lp, json_lines, syslog).
    #[arg(long)]
    pub encoder: Option<String>,

    /// Sink type (stdout, http_push, file, remote_write, loki, otlp_grpc, kafka, tcp, udp).
    #[arg(long)]
    pub sink: Option<String>,

    /// Sink endpoint (URL, file path, or host:port).
    #[arg(long)]
    pub endpoint: Option<String>,

    /// Output file path for the generated YAML.
    #[arg(short, long)]
    pub output: Option<String>,

    /// Static labels (key=value), can be repeated.
    #[arg(long = "label", value_name = "KEY=VALUE")]
    pub labels: Vec<String>,

    /// Run the generated scenario immediately after writing (skip the prompt).
    ///
    /// When absent and stdin is a TTY, prompts the user. When absent and stdin
    /// is not a TTY, defaults to `false`.
    #[arg(long)]
    pub run_now: bool,

    /// Log message template (for `--signal-type logs`).
    ///
    /// Uses `{field}` placeholders. Example:
    /// `"Request to {endpoint} completed with status {status}"`.
    #[arg(long, help_heading = "Logs")]
    pub message_template: Option<String>,

    /// Severity distribution preset (for `--signal-type logs`).
    ///
    /// Accepted values: `mostly_info`, `balanced`, `error_heavy`.
    #[arg(long, help_heading = "Logs")]
    pub severity: Option<String>,

    /// Kafka broker(s) for `--sink kafka` (e.g. `localhost:9092`).
    #[arg(long, help_heading = "Sink")]
    pub kafka_brokers: Option<String>,

    /// Kafka topic for `--sink kafka`.
    #[arg(long, help_heading = "Sink")]
    pub kafka_topic: Option<String>,

    /// OTLP signal type for `--sink otlp_grpc`: `metrics` or `logs`.
    #[arg(long, help_heading = "Sink")]
    pub otlp_signal_type: Option<String>,
}

/// Arguments for the unified `catalog` subcommand (spec §6.3).
///
/// Replaces `sonda scenarios` + `sonda packs` with a single tree that
/// lists, shows, and runs either kind.
#[derive(Debug, Args)]
pub struct CatalogArgs {
    /// Which catalog action to perform.
    #[command(subcommand)]
    pub action: CatalogAction,
}

/// Actions available under `sonda catalog`.
#[derive(Debug, Subcommand)]
pub enum CatalogAction {
    /// List available scenarios and packs from the search path.
    List(CatalogListArgs),
    /// Show the raw YAML for a scenario or pack by name.
    Show(CatalogShowArgs),
    /// Run a scenario or pack by name.
    Run(CatalogRunArgs),
}

/// Arguments for `sonda catalog list`.
#[derive(Debug, Args)]
pub struct CatalogListArgs {
    /// Filter by category (case-sensitive). Example:
    /// `--category infrastructure`.
    #[arg(long)]
    pub category: Option<String>,

    /// Restrict output to a single kind: `scenario` or `pack`.
    #[arg(long = "type", value_name = "KIND")]
    pub kind: Option<String>,

    /// Emit the list as a stable JSON array on stdout.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `sonda catalog show`.
#[derive(Debug, Args)]
pub struct CatalogShowArgs {
    /// Name of the scenario or pack to show.
    pub name: String,
}

/// Arguments for `sonda catalog run`.
///
/// Dispatches internally: scenarios route through the v1/v2 loader
/// pipeline; packs route through the existing pack-expansion path with
/// CLI overrides applied.
#[derive(Debug, Args)]
pub struct CatalogRunArgs {
    /// Name of the scenario or pack to run.
    pub name: String,

    /// Override the duration (e.g. `"10s"`, `"2m"`).
    #[arg(long)]
    pub duration: Option<String>,

    /// Override the event rate in events per second.
    #[arg(long)]
    pub rate: Option<f64>,

    /// Override the sink type (e.g. `stdout`, `file`).
    #[arg(long, help_heading = "Sink")]
    pub sink: Option<String>,

    /// Override the sink endpoint (URL, file path, host:port).
    #[arg(long, help_heading = "Sink")]
    pub endpoint: Option<String>,

    /// Override the encoder format.
    #[arg(long, help_heading = "Encoder")]
    pub encoder: Option<String>,

    /// Write output to a file (shorthand for `--sink file --endpoint <path>`).
    #[arg(short = 'o', long, conflicts_with = "sink", help_heading = "Sink")]
    pub output: Option<PathBuf>,

    /// Additional labels (format: `key=value`). Required for pack runs.
    #[arg(long = "label", value_parser = parse_label)]
    pub labels: Vec<(String, String)>,
}

/// Build clap help styling for the CLI.
///
/// Returns a [`clap::builder::styling::Styles`] with colored headers, usage
/// patterns, flag names, and placeholders that match the conventions of modern
/// Rust CLIs like `cargo`.
fn clap_styles() -> clap::builder::styling::Styles {
    use clap::builder::styling::{AnsiColor, Style, Styles};

    Styles::styled()
        .header(Style::new().bold().underline())
        .usage(Style::new().bold())
        .literal(Style::new().fg_color(Some(AnsiColor::Cyan.into())).bold())
        .placeholder(Style::new().fg_color(Some(AnsiColor::Green.into())))
        .valid(Style::new().fg_color(Some(AnsiColor::Green.into())))
        .invalid(Style::new().fg_color(Some(AnsiColor::Red.into())))
}

/// Parse `--on-sink-error` flag values into the typed enum.
pub fn parse_on_sink_error(s: &str) -> Result<sonda_core::OnSinkError, String> {
    match s {
        "warn" => Ok(sonda_core::OnSinkError::Warn),
        "fail" => Ok(sonda_core::OnSinkError::Fail),
        other => Err(format!(
            "invalid --on-sink-error {other:?}: expected 'warn' or 'fail'"
        )),
    }
}

/// Parse a `key=value` label string into a `(String, String)` pair.
///
/// Returns an error if the string does not contain an `=` character.
pub fn parse_label(s: &str) -> Result<(String, String), String> {
    match s.find('=') {
        Some(pos) => {
            let key = s[..pos].to_string();
            let value = s[pos + 1..].to_string();
            if key.is_empty() {
                return Err(format!("label key must not be empty in {:?}", s));
            }
            Ok((key, value))
        }
        None => Err(format!(
            "label {:?} must be in key=value format (no '=' found)",
            s
        )),
    }
}

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

    // ---- parse_label happy path -----------------------------------------------

    #[test]
    fn parse_label_simple_key_value() {
        let result = parse_label("hostname=t0-a1").expect("should parse");
        assert_eq!(result, ("hostname".to_string(), "t0-a1".to_string()));
    }

    #[test]
    fn parse_label_value_with_equals_sign() {
        // Only the first '=' splits the key — remainder goes into the value.
        let result = parse_label("key=a=b").expect("should parse");
        assert_eq!(result, ("key".to_string(), "a=b".to_string()));
    }

    #[test]
    fn parse_label_empty_value_is_allowed() {
        let result = parse_label("key=").expect("should parse empty value");
        assert_eq!(result, ("key".to_string(), String::new()));
    }

    #[test]
    fn parse_label_zone_label() {
        let result = parse_label("zone=eu1").expect("should parse zone label");
        assert_eq!(result, ("zone".to_string(), "eu1".to_string()));
    }

    // ---- parse_label error cases ----------------------------------------------

    #[test]
    fn parse_label_no_equals_sign_returns_error() {
        let err = parse_label("bad").expect_err("should fail without '='");
        assert!(
            err.contains("key=value"),
            "error should mention key=value format, got: {err}"
        );
    }

    #[test]
    fn parse_label_empty_string_returns_error() {
        let err = parse_label("").expect_err("empty string should fail");
        // No '=' present — should get the no-equals error.
        assert!(
            err.contains("key=value") || err.contains("'='"),
            "error should mention format, got: {err}"
        );
    }

    #[test]
    fn parse_label_empty_key_returns_error() {
        let err = parse_label("=value").expect_err("empty key should fail");
        assert!(
            err.contains("empty"),
            "error should mention empty key, got: {err}"
        );
    }

    // ---- Verbosity::from_flags ---------------------------------------------------

    #[test]
    fn verbosity_default_is_normal() {
        assert_eq!(Verbosity::from_flags(false, false), Verbosity::Normal);
    }

    #[test]
    fn verbosity_quiet_flag() {
        assert_eq!(Verbosity::from_flags(true, false), Verbosity::Quiet);
    }

    #[test]
    fn verbosity_verbose_flag() {
        assert_eq!(Verbosity::from_flags(false, true), Verbosity::Verbose);
    }

    // ---- CLI parsing: --dry-run and --verbose flags ----------------------------

    #[test]
    fn cli_dry_run_flag_is_parsed() {
        let cli = Cli::try_parse_from([
            "sonda",
            "--dry-run",
            "metrics",
            "--name",
            "test",
            "--rate",
            "1",
        ])
        .expect("--dry-run should parse");
        assert!(cli.dry_run);
    }

    #[test]
    fn cli_verbose_flag_is_parsed() {
        let cli = Cli::try_parse_from([
            "sonda",
            "--verbose",
            "metrics",
            "--name",
            "test",
            "--rate",
            "1",
        ])
        .expect("--verbose should parse");
        assert!(cli.verbose);
    }

    #[test]
    fn cli_quiet_and_verbose_conflict() {
        let result = Cli::try_parse_from([
            "sonda",
            "--quiet",
            "--verbose",
            "metrics",
            "--name",
            "test",
            "--rate",
            "1",
        ]);
        assert!(result.is_err(), "--quiet and --verbose must conflict");
    }

    #[test]
    fn cli_dry_run_orthogonal_to_quiet() {
        let cli = Cli::try_parse_from([
            "sonda",
            "--dry-run",
            "--quiet",
            "metrics",
            "--name",
            "test",
            "--rate",
            "1",
        ])
        .expect("--dry-run + --quiet should parse");
        assert!(cli.dry_run);
        assert!(cli.quiet);
    }

    #[test]
    fn cli_dry_run_orthogonal_to_verbose() {
        let cli = Cli::try_parse_from([
            "sonda",
            "--dry-run",
            "--verbose",
            "metrics",
            "--name",
            "test",
            "--rate",
            "1",
        ])
        .expect("--dry-run + --verbose should parse");
        assert!(cli.dry_run);
        assert!(cli.verbose);
    }

    // ---- --value flag: parsing and validation --------------------------------

    #[test]
    fn cli_value_flag_is_parsed() {
        let cli = Cli::try_parse_from([
            "sonda", "metrics", "--name", "up", "--rate", "1", "--value", "42",
        ])
        .expect("--value should parse");
        match cli.command {
            Commands::Metrics(args) => {
                assert_eq!(args.value, Some(42.0));
            }
            _ => panic!("expected Metrics command"),
        }
    }

    #[test]
    fn cli_value_flag_without_value_mode_is_accepted() {
        let cli = Cli::try_parse_from([
            "sonda", "metrics", "--name", "up", "--rate", "1", "--value", "1",
        ])
        .expect("--value without --value-mode should be accepted (defaults to constant)");
        match cli.command {
            Commands::Metrics(args) => {
                assert_eq!(args.value, Some(1.0));
                assert!(args.value_mode.is_none());
            }
            _ => panic!("expected Metrics command"),
        }
    }

    // ---- scenarios subcommand parsing -------------------------------------------

    #[test]
    fn cli_scenarios_list_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "scenarios", "list"])
            .expect("scenarios list should parse");
        match cli.command {
            Commands::Scenarios(args) => {
                assert!(matches!(args.action, ScenariosAction::List(_)));
            }
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_list_with_category_filter() {
        let cli =
            Cli::try_parse_from(["sonda", "scenarios", "list", "--category", "infrastructure"])
                .expect("scenarios list --category should parse");
        match cli.command {
            Commands::Scenarios(args) => match args.action {
                ScenariosAction::List(list_args) => {
                    assert_eq!(list_args.category.as_deref(), Some("infrastructure"));
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_show_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "scenarios", "show", "cpu-spike"])
            .expect("scenarios show should parse");
        match cli.command {
            Commands::Scenarios(args) => match args.action {
                ScenariosAction::Show(show_args) => {
                    assert_eq!(show_args.name, "cpu-spike");
                }
                _ => panic!("expected Show action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_run_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "scenarios", "run", "cpu-spike"])
            .expect("scenarios run should parse");
        match cli.command {
            Commands::Scenarios(args) => match args.action {
                ScenariosAction::Run(run_args) => {
                    assert_eq!(run_args.name, "cpu-spike");
                    assert!(run_args.duration.is_none());
                    assert!(run_args.rate.is_none());
                    assert!(run_args.sink.is_none());
                    assert!(run_args.endpoint.is_none());
                    assert!(run_args.encoder.is_none());
                }
                _ => panic!("expected Run action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_run_with_overrides() {
        let cli = Cli::try_parse_from([
            "sonda",
            "scenarios",
            "run",
            "cpu-spike",
            "--duration",
            "5s",
            "--rate",
            "2",
            "--sink",
            "file",
            "--endpoint",
            "/tmp/out.txt",
            "--encoder",
            "json_lines",
        ])
        .expect("scenarios run with overrides should parse");
        match cli.command {
            Commands::Scenarios(args) => match args.action {
                ScenariosAction::Run(run_args) => {
                    assert_eq!(run_args.duration.as_deref(), Some("5s"));
                    assert_eq!(run_args.rate, Some(2.0));
                    assert_eq!(run_args.sink.as_deref(), Some("file"));
                    assert_eq!(run_args.endpoint.as_deref(), Some("/tmp/out.txt"));
                    assert_eq!(run_args.encoder.as_deref(), Some("json_lines"));
                }
                _ => panic!("expected Run action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_show_requires_name() {
        let result = Cli::try_parse_from(["sonda", "scenarios", "show"]);
        assert!(result.is_err(), "show without name must fail");
    }

    #[test]
    fn cli_scenarios_run_requires_name() {
        let result = Cli::try_parse_from(["sonda", "scenarios", "run"]);
        assert!(result.is_err(), "run without name must fail");
    }

    #[test]
    fn cli_scenarios_requires_action() {
        let result = Cli::try_parse_from(["sonda", "scenarios"]);
        assert!(result.is_err(), "scenarios without action must fail");
    }

    // ---- clap_styles: returns valid styles ------------------------------------

    #[test]
    fn clap_styles_returns_valid_styles() {
        // The function must return without panicking and produce a Styles
        // instance that can be used with clap.
        let _styles = clap_styles();
    }

    // ---- --json flag on scenarios list ----------------------------------------

    #[test]
    fn cli_scenarios_list_json_flag_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "scenarios", "list", "--json"])
            .expect("--json flag should parse");
        match cli.command {
            Commands::Scenarios(ref args) => match args.action {
                ScenariosAction::List(ref list_args) => {
                    assert!(list_args.json, "--json must be true");
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_list_json_flag_defaults_to_false() {
        let cli = Cli::try_parse_from(["sonda", "scenarios", "list"])
            .expect("list without --json should parse");
        match cli.command {
            Commands::Scenarios(ref args) => match args.action {
                ScenariosAction::List(ref list_args) => {
                    assert!(!list_args.json, "--json must default to false");
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    #[test]
    fn cli_scenarios_list_json_and_category_combined() {
        let cli = Cli::try_parse_from([
            "sonda",
            "scenarios",
            "list",
            "--json",
            "--category",
            "infrastructure",
        ])
        .expect("--json + --category should parse together");
        match cli.command {
            Commands::Scenarios(ref args) => match args.action {
                ScenariosAction::List(ref list_args) => {
                    assert!(list_args.json);
                    assert_eq!(list_args.category.as_deref(), Some("infrastructure"));
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Scenarios command"),
        }
    }

    // ---- Packs subcommand parsing -----------------------------------------------

    #[test]
    fn cli_packs_list_parses() {
        let cli = Cli::try_parse_from(["sonda", "packs", "list"]).expect("packs list must parse");
        assert!(matches!(cli.command, Commands::Packs(_)));
        match cli.command {
            Commands::Packs(ref args) => {
                assert!(matches!(args.action, PacksAction::List(_)));
            }
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_list_with_category() {
        let cli = Cli::try_parse_from(["sonda", "packs", "list", "--category", "network"])
            .expect("packs list --category must parse");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::List(ref list_args) => {
                    assert_eq!(list_args.category.as_deref(), Some("network"));
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_list_with_json() {
        let cli = Cli::try_parse_from(["sonda", "packs", "list", "--json"])
            .expect("packs list --json must parse");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::List(ref list_args) => {
                    assert!(list_args.json);
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_show_parses() {
        let cli = Cli::try_parse_from(["sonda", "packs", "show", "telegraf_snmp_interface"])
            .expect("packs show must parse");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::Show(ref show_args) => {
                    assert_eq!(show_args.name, "telegraf_snmp_interface");
                }
                _ => panic!("expected Show action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_run_parses() {
        let cli = Cli::try_parse_from([
            "sonda",
            "packs",
            "run",
            "telegraf_snmp_interface",
            "--rate",
            "2",
            "--duration",
            "10s",
        ])
        .expect("packs run must parse");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::Run(ref run_args) => {
                    assert_eq!(run_args.name, "telegraf_snmp_interface");
                    assert_eq!(run_args.rate, Some(2.0));
                    assert_eq!(run_args.duration.as_deref(), Some("10s"));
                }
                _ => panic!("expected Run action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_run_with_label() {
        let cli = Cli::try_parse_from([
            "sonda",
            "packs",
            "run",
            "telegraf_snmp_interface",
            "--label",
            "device=rtr-01",
            "--label",
            "ifName=eth0",
        ])
        .expect("packs run --label must parse");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::Run(ref run_args) => {
                    assert_eq!(run_args.labels.len(), 2);
                    assert_eq!(
                        run_args.labels[0],
                        ("device".to_string(), "rtr-01".to_string())
                    );
                    assert_eq!(
                        run_args.labels[1],
                        ("ifName".to_string(), "eth0".to_string())
                    );
                }
                _ => panic!("expected Run action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_run_with_sink_and_encoder() {
        let cli = Cli::try_parse_from([
            "sonda",
            "packs",
            "run",
            "node_exporter_cpu",
            "--sink",
            "file",
            "--endpoint",
            "/tmp/out.txt",
            "--encoder",
            "json_lines",
        ])
        .expect("packs run --sink --encoder must parse");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::Run(ref run_args) => {
                    assert_eq!(run_args.sink.as_deref(), Some("file"));
                    assert_eq!(run_args.endpoint.as_deref(), Some("/tmp/out.txt"));
                    assert_eq!(run_args.encoder.as_deref(), Some("json_lines"));
                }
                _ => panic!("expected Run action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    #[test]
    fn cli_packs_list_json_and_category_combined() {
        let cli = Cli::try_parse_from([
            "sonda",
            "packs",
            "list",
            "--json",
            "--category",
            "infrastructure",
        ])
        .expect("--json + --category should parse together");
        match cli.command {
            Commands::Packs(ref args) => match args.action {
                PacksAction::List(ref list_args) => {
                    assert!(list_args.json);
                    assert_eq!(list_args.category.as_deref(), Some("infrastructure"));
                }
                _ => panic!("expected List action"),
            },
            _ => panic!("expected Packs command"),
        }
    }

    // ---- Import subcommand parsing -----------------------------------------------

    #[test]
    fn cli_import_analyze_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "import", "foo.csv", "--analyze"])
            .expect("import --analyze should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert_eq!(args.file, PathBuf::from("foo.csv"));
                assert!(args.analyze);
                assert!(args.output.is_none());
                assert!(!args.run);
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_default_rate_and_duration() {
        let cli = Cli::try_parse_from(["sonda", "import", "data.csv", "--analyze"])
            .expect("import with defaults should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert_eq!(args.rate, 1.0, "default rate must be 1.0");
                assert_eq!(args.duration, "60s", "default duration must be 60s");
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_columns_flag_is_parsed() {
        let cli = Cli::try_parse_from([
            "sonda",
            "import",
            "data.csv",
            "--analyze",
            "--columns",
            "1,3,5",
        ])
        .expect("import --columns should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert_eq!(args.columns.as_deref(), Some("1,3,5"));
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_output_flag_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "import", "data.csv", "-o", "out.yaml"])
            .expect("import -o should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert_eq!(args.output, Some(PathBuf::from("out.yaml")));
                assert!(!args.analyze);
                assert!(!args.run);
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_run_flag_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "import", "data.csv", "--run"])
            .expect("import --run should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert!(args.run);
                assert!(!args.analyze);
                assert!(args.output.is_none());
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_rate_and_duration_overrides() {
        let cli = Cli::try_parse_from([
            "sonda",
            "import",
            "data.csv",
            "--run",
            "--rate",
            "5",
            "--duration",
            "2m",
        ])
        .expect("import with rate and duration overrides should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert_eq!(args.rate, 5.0);
                assert_eq!(args.duration, "2m");
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_analyze_conflicts_with_output() {
        let result =
            Cli::try_parse_from(["sonda", "import", "data.csv", "--analyze", "-o", "out.yaml"]);
        assert!(result.is_err(), "--analyze and -o must conflict");
    }

    #[test]
    fn cli_import_analyze_conflicts_with_run() {
        let result = Cli::try_parse_from(["sonda", "import", "data.csv", "--analyze", "--run"]);
        assert!(result.is_err(), "--analyze and --run must conflict");
    }

    #[test]
    fn cli_import_output_conflicts_with_run() {
        let result =
            Cli::try_parse_from(["sonda", "import", "data.csv", "-o", "out.yaml", "--run"]);
        assert!(result.is_err(), "-o and --run must conflict");
    }

    #[test]
    fn cli_import_requires_file_argument() {
        let result = Cli::try_parse_from(["sonda", "import", "--analyze"]);
        assert!(result.is_err(), "import without file must fail");
    }

    #[test]
    fn cli_import_run_with_columns() {
        let cli = Cli::try_parse_from([
            "sonda",
            "import",
            "data.csv",
            "--run",
            "--columns",
            "2,4",
            "--rate",
            "10",
            "--duration",
            "5m",
        ])
        .expect("import --run with all options should parse");
        match cli.command {
            Commands::Import(ref args) => {
                assert!(args.run);
                assert_eq!(args.columns.as_deref(), Some("2,4"));
                assert_eq!(args.rate, 10.0);
                assert_eq!(args.duration, "5m");
            }
            _ => panic!("expected Import command"),
        }
    }

    #[test]
    fn cli_import_verbose_flag_with_run() {
        let cli = Cli::try_parse_from(["sonda", "--verbose", "import", "data.csv", "--run"])
            .expect("import with --verbose should parse");
        assert!(cli.verbose);
        assert!(matches!(cli.command, Commands::Import(_)));
    }

    // ---- Init subcommand parsing -----------------------------------------------

    #[test]
    fn cli_init_is_parsed() {
        let cli = Cli::try_parse_from(["sonda", "init"]).expect("init should parse");
        assert!(matches!(cli.command, Commands::Init(_)));
    }

    #[test]
    fn cli_init_with_quiet_flag() {
        let cli = Cli::try_parse_from(["sonda", "--quiet", "init"])
            .expect("init with --quiet should parse");
        assert!(cli.quiet);
        assert!(matches!(cli.command, Commands::Init(_)));
    }

    #[test]
    fn cli_init_with_pack_path() {
        let cli = Cli::try_parse_from(["sonda", "--pack-path", "/custom/packs", "init"])
            .expect("init with --pack-path should parse");
        assert_eq!(
            cli.pack_path,
            Some(std::path::PathBuf::from("/custom/packs"))
        );
        assert!(matches!(cli.command, Commands::Init(_)));
    }

    #[test]
    fn cli_init_from_builtin_scenario() {
        let cli =
            Cli::try_parse_from(["sonda", "init", "--from", "@cpu-spike"]).expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.from.as_deref(), Some("@cpu-spike"));
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_from_csv_file() {
        let cli =
            Cli::try_parse_from(["sonda", "init", "--from", "data.csv"]).expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.from.as_deref(), Some("data.csv"));
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_all_flags() {
        let cli = Cli::try_parse_from([
            "sonda",
            "init",
            "--signal-type",
            "metrics",
            "--domain",
            "network",
            "--situation",
            "flap",
            "--metric",
            "bgp_state",
            "--rate",
            "2.5",
            "--duration",
            "5m",
            "--encoder",
            "prometheus_text",
            "--sink",
            "stdout",
            "--endpoint",
            "http://localhost:9090",
            "-o",
            "output.yaml",
            "--label",
            "env=prod",
            "--label",
            "dc=us-east",
        ])
        .expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.signal_type.as_deref(), Some("metrics"));
            assert_eq!(args.domain.as_deref(), Some("network"));
            assert_eq!(args.situation.as_deref(), Some("flap"));
            assert_eq!(args.metric.as_deref(), Some("bgp_state"));
            assert_eq!(args.rate, Some(2.5));
            assert_eq!(args.duration.as_deref(), Some("5m"));
            assert_eq!(args.encoder.as_deref(), Some("prometheus_text"));
            assert_eq!(args.sink.as_deref(), Some("stdout"));
            assert_eq!(args.endpoint.as_deref(), Some("http://localhost:9090"));
            assert_eq!(args.output.as_deref(), Some("output.yaml"));
            assert_eq!(args.labels, vec!["env=prod", "dc=us-east"]);
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_pack_flag() {
        let cli = Cli::try_parse_from(["sonda", "init", "--pack", "telegraf_snmp"])
            .expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.pack.as_deref(), Some("telegraf_snmp"));
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_no_flags_defaults_to_none() {
        let cli = Cli::try_parse_from(["sonda", "init"]).expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert!(args.from.is_none());
            assert!(args.signal_type.is_none());
            assert!(args.domain.is_none());
            assert!(args.situation.is_none());
            assert!(args.metric.is_none());
            assert!(args.pack.is_none());
            assert!(args.rate.is_none());
            assert!(args.duration.is_none());
            assert!(args.encoder.is_none());
            assert!(args.sink.is_none());
            assert!(args.endpoint.is_none());
            assert!(args.output.is_none());
            assert!(args.labels.is_empty());
            assert!(!args.run_now);
            assert!(args.message_template.is_none());
            assert!(args.severity.is_none());
            assert!(args.kafka_brokers.is_none());
            assert!(args.kafka_topic.is_none());
            assert!(args.otlp_signal_type.is_none());
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_output_short_flag() {
        let cli =
            Cli::try_parse_from(["sonda", "init", "-o", "my-scenario.yaml"]).expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.output.as_deref(), Some("my-scenario.yaml"));
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_run_now_flag() {
        let cli = Cli::try_parse_from(["sonda", "init", "--run-now"]).expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert!(args.run_now);
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_message_template_flag() {
        let cli = Cli::try_parse_from([
            "sonda",
            "init",
            "--message-template",
            "Connection from {ip} failed",
        ])
        .expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(
                args.message_template.as_deref(),
                Some("Connection from {ip} failed")
            );
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_severity_flag() {
        let cli =
            Cli::try_parse_from(["sonda", "init", "--severity", "balanced"]).expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.severity.as_deref(), Some("balanced"));
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_kafka_flags() {
        let cli = Cli::try_parse_from([
            "sonda",
            "init",
            "--sink",
            "kafka",
            "--kafka-brokers",
            "broker1:9092,broker2:9092",
            "--kafka-topic",
            "my-topic",
        ])
        .expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.sink.as_deref(), Some("kafka"));
            assert_eq!(
                args.kafka_brokers.as_deref(),
                Some("broker1:9092,broker2:9092")
            );
            assert_eq!(args.kafka_topic.as_deref(), Some("my-topic"));
        } else {
            panic!("expected Init command");
        }
    }

    #[test]
    fn cli_init_otlp_signal_type_flag() {
        let cli = Cli::try_parse_from([
            "sonda",
            "init",
            "--sink",
            "otlp_grpc",
            "--otlp-signal-type",
            "metrics",
        ])
        .expect("should parse");
        if let Commands::Init(ref args) = cli.command {
            assert_eq!(args.sink.as_deref(), Some("otlp_grpc"));
            assert_eq!(args.otlp_signal_type.as_deref(), Some("metrics"));
        } else {
            panic!("expected Init command");
        }
    }
}