rsigma-parser 0.28.0

Parser for Sigma detection rules, correlations, and filters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
//! Emit a parsed Sigma rule back to canonical Sigma YAML.
//!
//! This is the inverse of [`parse_sigma_yaml`](crate::parse_sigma_yaml): it
//! turns a [`SigmaRule`] (or a [`SigmaCollection`] of detection rules) back
//! into standard Sigma YAML. Parsing then emitting then parsing again yields an
//! equal AST for the detection-rule shapes the parser produces (field matching
//! with modifiers, value lists, keyword blocks, `field[any]`/`field[all]` array
//! blocks, boolean and quantified conditions, and all standard metadata).
//!
//! The emitter is deterministic: mapping-shaped collections (named detections,
//! logsource custom fields, custom attributes) are emitted in sorted key order,
//! so the same rule always produces byte-identical YAML. Detection value order
//! and condition order are preserved as-is.
//!
//! Value scalars are rendered in Sigma's canonical quoting: a string stays
//! plain only when YAML would read it back as exactly that string, and literal
//! `*`, `?`, and `\` are escaped so a re-parse reproduces the same
//! [`SigmaString`] wildcard structure.

use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;

use crate::ast::{
    ArrayQuantifier, ConditionExpr, ConditionOperator, CorrelationCondition, CorrelationRule,
    Detection, DetectionItem, Detections, FieldAlias, FilterRule, FilterRuleTarget, LogSource,
    Modifier, Related, RelationType, SigmaCollection, SigmaRule, Status, WindowMode,
};
use crate::style::{KeyCtx, Lead, RSIGMA_ORDER, STEP, ScalarCtx, encode_key, push_scalar};
use crate::value::{SigmaString, SigmaValue, SpecialChar, StringPart};

/// Emit a single detection [`SigmaRule`] as canonical Sigma YAML.
///
/// The output always ends with a trailing newline and re-parses to an equal
/// [`SigmaRule`].
pub fn emit_rule_yaml(rule: &SigmaRule) -> String {
    let mut out = String::new();

    push_scalar(
        &mut out,
        "",
        Lead::Key("title"),
        &rule.title,
        ScalarCtx::Prose,
    );
    if let Some(id) = &rule.id {
        push_scalar(&mut out, "", Lead::Key("id"), id, ScalarCtx::Value);
    }
    if let Some(name) = &rule.name {
        push_scalar(&mut out, "", Lead::Key("name"), name, ScalarCtx::Value);
    }
    if let Some(status) = &rule.status {
        push_line(&mut out, "status", status_str(*status));
    }
    if let Some(description) = &rule.description {
        push_scalar(
            &mut out,
            "",
            Lead::Key("description"),
            description,
            ScalarCtx::Prose,
        );
    }
    emit_string_list(&mut out, "references", &rule.references, ScalarCtx::Prose);
    if let Some(author) = &rule.author {
        push_scalar(&mut out, "", Lead::Key("author"), author, ScalarCtx::Prose);
    }
    if let Some(date) = &rule.date {
        push_scalar(&mut out, "", Lead::Key("date"), date, ScalarCtx::Value);
    }
    if let Some(modified) = &rule.modified {
        push_scalar(
            &mut out,
            "",
            Lead::Key("modified"),
            modified,
            ScalarCtx::Value,
        );
    }
    emit_related(&mut out, &rule.related);
    emit_string_list(&mut out, "tags", &rule.tags, ScalarCtx::Prose);
    if let Some(version) = rule.sigma_version {
        push_line(&mut out, "sigma-version", &version.to_string());
    }
    emit_logsource(&mut out, &rule.logsource);
    emit_detection(&mut out, &rule.detection);
    emit_string_list(&mut out, "fields", &rule.fields, ScalarCtx::Prose);
    emit_string_list(
        &mut out,
        "falsepositives",
        &rule.falsepositives,
        ScalarCtx::Prose,
    );
    if let Some(level) = &rule.level {
        push_line(&mut out, "level", level.as_str());
    }
    emit_string_list(&mut out, "scope", &rule.scope, ScalarCtx::Prose);
    if let Some(license) = &rule.license {
        push_scalar(
            &mut out,
            "",
            Lead::Key("license"),
            license,
            ScalarCtx::Prose,
        );
    }
    if let Some(taxonomy) = &rule.taxonomy {
        push_scalar(
            &mut out,
            "",
            Lead::Key("taxonomy"),
            taxonomy,
            ScalarCtx::Value,
        );
    }
    emit_custom_attributes(&mut out, &rule.custom_attributes);

    out
}

/// Emit a single [`CorrelationRule`] as canonical Sigma YAML.
///
/// The output always ends with a trailing newline and re-parses to an equal
/// [`CorrelationRule`]. Correlation bodies are emitted in the key order the
/// parser accepts, `window` only when it is not the default sliding mode, and
/// `generate` only when true.
///
/// ```rust
/// use rsigma_parser::{emit_correlation_yaml, parse_sigma_yaml};
///
/// let yaml = r#"
/// title: Burst of failed logins
/// correlation:
///     type: event_count
///     rules:
///         - failed_login
///     group-by:
///         - User
///     timespan: 5m
///     condition:
///         gte: 10
/// "#;
/// let collection = parse_sigma_yaml(yaml).unwrap();
/// let emitted = emit_correlation_yaml(&collection.correlations[0]);
/// assert!(emitted.contains("type: event_count"));
/// assert!(emitted.contains("gte: 10"));
/// ```
pub fn emit_correlation_yaml(rule: &CorrelationRule) -> String {
    let mut out = String::new();

    push_scalar(
        &mut out,
        "",
        Lead::Key("title"),
        &rule.title,
        ScalarCtx::Prose,
    );
    if let Some(id) = &rule.id {
        push_scalar(&mut out, "", Lead::Key("id"), id, ScalarCtx::Value);
    }
    if let Some(name) = &rule.name {
        push_scalar(&mut out, "", Lead::Key("name"), name, ScalarCtx::Value);
    }
    if let Some(status) = &rule.status {
        push_line(&mut out, "status", status_str(*status));
    }
    if let Some(description) = &rule.description {
        push_scalar(
            &mut out,
            "",
            Lead::Key("description"),
            description,
            ScalarCtx::Prose,
        );
    }
    emit_string_list(&mut out, "references", &rule.references, ScalarCtx::Prose);
    if let Some(author) = &rule.author {
        push_scalar(&mut out, "", Lead::Key("author"), author, ScalarCtx::Prose);
    }
    if let Some(date) = &rule.date {
        push_scalar(&mut out, "", Lead::Key("date"), date, ScalarCtx::Value);
    }
    if let Some(modified) = &rule.modified {
        push_scalar(
            &mut out,
            "",
            Lead::Key("modified"),
            modified,
            ScalarCtx::Value,
        );
    }
    emit_related(&mut out, &rule.related);
    emit_string_list(&mut out, "tags", &rule.tags, ScalarCtx::Prose);
    if let Some(version) = rule.sigma_version {
        push_line(&mut out, "sigma-version", &version.to_string());
    }

    let _ = writeln!(out, "correlation:");
    push_line(&mut out, "    type", rule.correlation_type.as_str());
    emit_string_list_at(&mut out, "    rules", &rule.rules, ScalarCtx::Value);
    emit_string_list_at(&mut out, "    group-by", &rule.group_by, ScalarCtx::Value);
    push_line(&mut out, "    timespan", &rule.timespan.to_string());
    if rule.window != WindowMode::Sliding {
        push_line(&mut out, "    window", rule.window.as_str());
    }
    if let Some(gap) = &rule.gap {
        push_line(&mut out, "    gap", &gap.to_string());
    }
    emit_correlation_condition(&mut out, "    ", &rule.condition);
    emit_correlation_aliases(&mut out, &rule.aliases);
    if rule.generate {
        push_line(&mut out, "    generate", "true");
    }

    emit_string_list(&mut out, "fields", &rule.fields, ScalarCtx::Prose);
    emit_string_list(
        &mut out,
        "falsepositives",
        &rule.falsepositives,
        ScalarCtx::Prose,
    );
    if let Some(level) = &rule.level {
        push_line(&mut out, "level", level.as_str());
    }
    emit_string_list(&mut out, "scope", &rule.scope, ScalarCtx::Prose);
    if let Some(license) = &rule.license {
        push_scalar(
            &mut out,
            "",
            Lead::Key("license"),
            license,
            ScalarCtx::Prose,
        );
    }
    if let Some(taxonomy) = &rule.taxonomy {
        push_scalar(
            &mut out,
            "",
            Lead::Key("taxonomy"),
            taxonomy,
            ScalarCtx::Value,
        );
    }
    emit_custom_attributes(&mut out, &rule.custom_attributes);

    out
}

/// Emit a single [`FilterRule`] as canonical Sigma YAML.
///
/// The output always ends with a trailing newline and re-parses to an equal
/// [`FilterRule`]. The `filter:` block carries the detection items and
/// condition; `rules` is omitted when the filter applies to every rule.
///
/// ```rust
/// use rsigma_parser::{emit_filter_yaml, parse_sigma_yaml};
///
/// let yaml = r#"
/// title: Drop system accounts
/// logsource:
///     product: windows
/// filter:
///     rules:
///         - failed_login
///     selection:
///         User|endswith: '$'
///     condition: selection
/// "#;
/// let collection = parse_sigma_yaml(yaml).unwrap();
/// let emitted = emit_filter_yaml(&collection.filters[0]);
/// assert!(emitted.contains("filter:"));
/// assert!(emitted.contains("User|endswith"));
/// ```
pub fn emit_filter_yaml(rule: &FilterRule) -> String {
    let mut out = String::new();

    push_scalar(
        &mut out,
        "",
        Lead::Key("title"),
        &rule.title,
        ScalarCtx::Prose,
    );
    if let Some(id) = &rule.id {
        push_scalar(&mut out, "", Lead::Key("id"), id, ScalarCtx::Value);
    }
    if let Some(name) = &rule.name {
        push_scalar(&mut out, "", Lead::Key("name"), name, ScalarCtx::Value);
    }
    if let Some(status) = &rule.status {
        push_line(&mut out, "status", status_str(*status));
    }
    if let Some(description) = &rule.description {
        push_scalar(
            &mut out,
            "",
            Lead::Key("description"),
            description,
            ScalarCtx::Prose,
        );
    }
    emit_string_list(&mut out, "references", &rule.references, ScalarCtx::Prose);
    if let Some(author) = &rule.author {
        push_scalar(&mut out, "", Lead::Key("author"), author, ScalarCtx::Prose);
    }
    if let Some(date) = &rule.date {
        push_scalar(&mut out, "", Lead::Key("date"), date, ScalarCtx::Value);
    }
    if let Some(modified) = &rule.modified {
        push_scalar(
            &mut out,
            "",
            Lead::Key("modified"),
            modified,
            ScalarCtx::Value,
        );
    }
    emit_related(&mut out, &rule.related);
    emit_string_list(&mut out, "tags", &rule.tags, ScalarCtx::Prose);
    if let Some(version) = rule.sigma_version {
        push_line(&mut out, "sigma-version", &version.to_string());
    }
    match &rule.logsource {
        Some(logsource) => emit_logsource(&mut out, logsource),
        None => {
            let _ = writeln!(out, "logsource: {{}}");
        }
    }

    let _ = writeln!(out, "filter:");
    if let FilterRuleTarget::Specific(targets) = &rule.rules {
        emit_string_list_at(&mut out, "    rules", targets, ScalarCtx::Value);
    }
    for (name, det) in sorted_named(&rule.detection.named) {
        emit_named_detection(&mut out, name, det, "    ");
    }
    emit_timeframe(&mut out, "    ", &rule.detection);
    emit_condition_at(&mut out, "    ", &rule.detection.conditions);

    emit_string_list(&mut out, "fields", &rule.fields, ScalarCtx::Prose);
    emit_string_list(
        &mut out,
        "falsepositives",
        &rule.falsepositives,
        ScalarCtx::Prose,
    );
    if let Some(level) = &rule.level {
        push_line(&mut out, "level", level.as_str());
    }
    emit_string_list(&mut out, "scope", &rule.scope, ScalarCtx::Prose);
    if let Some(license) = &rule.license {
        push_scalar(
            &mut out,
            "",
            Lead::Key("license"),
            license,
            ScalarCtx::Prose,
        );
    }
    if let Some(taxonomy) = &rule.taxonomy {
        push_scalar(
            &mut out,
            "",
            Lead::Key("taxonomy"),
            taxonomy,
            ScalarCtx::Value,
        );
    }
    emit_custom_attributes(&mut out, &rule.custom_attributes);

    out
}

/// Emit every detection rule in a collection, separated by `---` documents.
///
/// Correlation and filter documents are not part of the reverse-conversion
/// surface and are skipped; only [`SigmaCollection::rules`] are emitted.
pub fn emit_collection_yaml(collection: &SigmaCollection) -> String {
    collection
        .rules
        .iter()
        .map(emit_rule_yaml)
        .collect::<Vec<_>>()
        .join("---\n")
}

// =============================================================================
// Metadata sections
// =============================================================================

fn push_line(out: &mut String, key: &str, value: &str) {
    let _ = writeln!(out, "{key}: {value}");
}

fn emit_string_list(out: &mut String, key: &str, items: &[String], ctx: ScalarCtx) {
    emit_string_list_at(out, key, items, ctx);
}

/// Emit a list whose key may carry leading indentation (for nested blocks).
fn emit_string_list_at(out: &mut String, key: &str, items: &[String], ctx: ScalarCtx) {
    if items.is_empty() {
        return;
    }
    let _ = writeln!(out, "{key}:");
    let indent = format!("{}{STEP}", leading_whitespace(key));
    for item in items {
        push_scalar(out, &indent, Lead::Dash, item, ctx);
    }
}

fn leading_whitespace(s: &str) -> &str {
    &s[..s.len() - s.trim_start().len()]
}

fn emit_related(out: &mut String, related: &[Related]) {
    if related.is_empty() {
        return;
    }
    let _ = writeln!(out, "related:");
    for entry in related {
        push_scalar(
            out,
            &format!("{STEP}- "),
            Lead::Key("id"),
            &entry.id,
            ScalarCtx::Value,
        );
        let _ = writeln!(out, "{STEP}  type: {}", relation_str(entry.relation_type));
    }
}

fn emit_logsource(out: &mut String, logsource: &LogSource) {
    // An empty `logsource:` key parses as null, which the parser reports as
    // not being a mapping; an explicit empty mapping gets the clearer error
    // that no log source field is set.
    if logsource.category.is_none()
        && logsource.product.is_none()
        && logsource.service.is_none()
        && logsource.definition.is_none()
        && logsource.custom.is_empty()
    {
        let _ = writeln!(out, "logsource: {{}}");
        return;
    }
    let _ = writeln!(out, "logsource:");
    if let Some(category) = &logsource.category {
        push_scalar(out, STEP, Lead::Key("category"), category, ScalarCtx::Value);
    }
    if let Some(product) = &logsource.product {
        push_scalar(out, STEP, Lead::Key("product"), product, ScalarCtx::Value);
    }
    if let Some(service) = &logsource.service {
        push_scalar(out, STEP, Lead::Key("service"), service, ScalarCtx::Value);
    }
    if let Some(definition) = &logsource.definition {
        push_scalar(
            out,
            STEP,
            Lead::Key("definition"),
            definition,
            ScalarCtx::Prose,
        );
    }
    for (key, value) in sorted(&logsource.custom) {
        push_scalar(
            out,
            STEP,
            Lead::Key(&encode_key(key, KeyCtx::Key)),
            value,
            ScalarCtx::Value,
        );
    }
}

fn emit_custom_attributes(out: &mut String, attrs: &HashMap<String, yaml_serde::Value>) {
    let mut keys: Vec<&str> = attrs.keys().map(String::as_str).collect();
    let mut ordered: Vec<&str> = RSIGMA_ORDER
        .iter()
        .copied()
        .filter(|key| attrs.contains_key(*key))
        .collect();
    keys.sort_unstable();
    ordered.extend(keys.into_iter().filter(|key| !RSIGMA_ORDER.contains(key)));
    for key in ordered {
        let value = &attrs[key];
        emit_yaml_value(out, &encode_key(key, KeyCtx::Key), value, "");
    }
}

// =============================================================================
// Detection section
// =============================================================================

fn emit_detection(out: &mut String, detection: &Detections) {
    let _ = writeln!(out, "detection:");
    for (name, det) in sorted_named(&detection.named) {
        emit_named_detection(out, name, det, STEP);
    }
    emit_timeframe(out, STEP, detection);
    emit_condition(out, &detection.conditions);
}

fn emit_timeframe(out: &mut String, indent: &str, detection: &Detections) {
    if let Some(timeframe) = &detection.timeframe {
        push_scalar(
            out,
            indent,
            Lead::Key("timeframe"),
            timeframe,
            ScalarCtx::Value,
        );
    }
}

fn emit_condition(out: &mut String, conditions: &[ConditionExpr]) {
    emit_condition_at(out, STEP, conditions);
}

fn emit_condition_at(out: &mut String, indent: &str, conditions: &[ConditionExpr]) {
    match conditions {
        [] => {}
        [single] => {
            push_scalar(
                out,
                indent,
                Lead::Key("condition"),
                &condition_source(single),
                ScalarCtx::Condition,
            );
        }
        many => {
            let _ = writeln!(out, "{indent}condition:");
            let nested = deeper(indent);
            for cond in many {
                push_scalar(
                    out,
                    &nested,
                    Lead::Dash,
                    &condition_source(cond),
                    ScalarCtx::Condition,
                );
            }
        }
    }
}

/// Render a condition expression as a Sigma condition string, without the
/// redundant outer parentheses [`ConditionExpr`]'s `Display` adds around a
/// top-level `and`/`or`.
fn condition_source(expr: &ConditionExpr) -> String {
    match expr {
        ConditionExpr::And(parts) => parts
            .iter()
            .map(|p| p.to_string())
            .collect::<Vec<_>>()
            .join(" and "),
        ConditionExpr::Or(parts) => parts
            .iter()
            .map(|p| p.to_string())
            .collect::<Vec<_>>()
            .join(" or "),
        other => other.to_string(),
    }
}

/// Emit a correlation `condition:` block at `indent` (including the key).
fn emit_correlation_condition(out: &mut String, indent: &str, condition: &CorrelationCondition) {
    match condition {
        CorrelationCondition::Threshold {
            predicates,
            field,
            percentile,
        } => {
            let _ = writeln!(out, "{indent}condition:");
            let nested = deeper(indent);
            let mut ordered: Vec<&(ConditionOperator, u64)> = predicates.iter().collect();
            ordered.sort_by_key(|(op, _)| operator_rank(*op));
            for (op, value) in ordered {
                push_line(
                    out,
                    &format!("{nested}{}", operator_str(*op)),
                    &value.to_string(),
                );
            }
            if let Some(field) = field {
                match field.as_slice() {
                    [single] => {
                        push_scalar(out, &nested, Lead::Key("field"), single, ScalarCtx::Value)
                    }
                    many => {
                        emit_string_list_at(out, &format!("{nested}field"), many, ScalarCtx::Value)
                    }
                }
            }
            if let Some(percentile) = percentile {
                push_line(out, &format!("{nested}percentile"), &percentile.to_string());
            }
        }
        CorrelationCondition::Extended(expr) => {
            push_scalar(
                out,
                indent,
                Lead::Key("condition"),
                &condition_source(expr),
                ScalarCtx::Condition,
            );
        }
    }
}

/// Emit the `aliases:` mapping of a correlation, with sorted per-rule keys.
fn emit_correlation_aliases(out: &mut String, aliases: &[FieldAlias]) {
    if aliases.is_empty() {
        return;
    }
    let _ = writeln!(out, "{STEP}aliases:");
    for alias in aliases {
        let _ = writeln!(
            out,
            "{STEP}{STEP}{}:",
            encode_key(&alias.alias, KeyCtx::Key)
        );
        let mut mapping: Vec<(&String, &String)> = alias.mapping.iter().collect();
        mapping.sort_by(|a, b| a.0.cmp(b.0));
        for (rule, field) in mapping {
            push_scalar(
                out,
                &format!("{STEP}{STEP}{STEP}"),
                Lead::Key(&encode_key(rule, KeyCtx::Key)),
                field,
                ScalarCtx::Value,
            );
        }
    }
}

fn emit_named_detection(out: &mut String, name: &str, det: &Detection, indent: &str) {
    let _ = writeln!(out, "{indent}{}:", encode_key(name, KeyCtx::Key));
    emit_detection_value(out, det, &deeper(indent));
}

/// Emit the body of a detection at `indent` (a mapping of items, a YAML list,
/// or a keyword list depending on the detection shape).
fn emit_detection_value(out: &mut String, det: &Detection, indent: &str) {
    match det {
        Detection::AnyOf(subs) => {
            for sub in subs {
                emit_list_item(out, sub, indent);
            }
        }
        Detection::Keywords(values) => {
            for value in values {
                push_value(out, indent, Lead::Dash, value, false, false);
            }
        }
        map_shaped => emit_map_entries(out, map_shaped, indent),
    }
}

/// Emit the `key: value` entries of a mapping-shaped detection.
fn emit_map_entries(out: &mut String, det: &Detection, indent: &str) {
    match det {
        Detection::AllOf(items) => {
            for item in items {
                emit_item(out, item, indent);
            }
        }
        Detection::And(subs) => {
            for sub in subs {
                emit_map_entries(out, sub, indent);
            }
        }
        Detection::ArrayMatch {
            field,
            quantifier,
            body,
        } => {
            let key = format!("{}[{}]", field, array_str(*quantifier));
            let _ = writeln!(out, "{indent}{}:", encode_key(&key, KeyCtx::FieldKey));
            emit_detection_value(out, body, &deeper(indent));
        }
        Detection::Conditional { named, condition } => {
            for (name, sub) in sorted_named(named) {
                emit_named_detection(out, name, sub, indent);
            }
            push_scalar(
                out,
                indent,
                Lead::Key("condition"),
                &condition_source(condition),
                ScalarCtx::Condition,
            );
        }
        // List-shaped detections cannot appear as bare map entries; render them
        // under a synthetic block so nothing is silently dropped.
        Detection::AnyOf(_) | Detection::Keywords(_) => {
            emit_detection_value(out, det, indent);
        }
    }
}

/// Emit one YAML list item (`- ...`) for an `AnyOf` sub-detection.
fn emit_list_item(out: &mut String, det: &Detection, indent: &str) {
    let mut buf = String::new();
    emit_detection_value(&mut buf, det, "");
    for (i, line) in buf.lines().enumerate() {
        if i == 0 {
            let _ = writeln!(out, "{indent}- {line}");
        } else {
            let _ = writeln!(out, "{indent}  {line}");
        }
    }
}

/// Emit a single detection item (`field|mods: value` or a value list).
fn emit_item(out: &mut String, item: &DetectionItem, indent: &str) {
    let base = item.field.name.as_deref().unwrap_or(".");
    let key = field_key(base, &item.field.modifiers);
    // `re`, `cidr`, and `fieldref` values are raw strings (the parser reads them
    // without wildcard interpretation), so they must be emitted verbatim rather
    // than wildcard-escaped, or a regex like `ab.*c` would gain a stray `\`.
    let raw = item
        .field
        .modifiers
        .iter()
        .any(|m| matches!(m, Modifier::Re | Modifier::Cidr | Modifier::FieldRef));
    let expand = item.field.modifiers.contains(&Modifier::Expand);
    match item.values.as_slice() {
        [single] => {
            push_value(out, indent, Lead::Key(&key), single, raw, expand);
        }
        values => {
            let _ = writeln!(out, "{indent}{key}:");
            for value in values {
                push_value(out, &deeper(indent), Lead::Dash, value, raw, expand);
            }
        }
    }
}

/// Write a [`SigmaValue`]: strings go through [`push_scalar`] in the value
/// context, while non-string scalars are copied verbatim.
fn push_value(
    out: &mut String,
    indent: &str,
    lead: Lead<'_>,
    value: &SigmaValue,
    raw: bool,
    expand: bool,
) {
    match value {
        SigmaValue::String(s) => {
            let source = if expand {
                s.original.clone()
            } else if raw {
                s.as_plain().unwrap_or_else(|| s.original.clone())
            } else {
                sigma_string_source(s)
            };
            push_scalar(out, indent, lead, &source, ScalarCtx::Value);
        }
        other => {
            let token = match other {
                SigmaValue::Integer(n) => n.to_string(),
                SigmaValue::Float(f) => float_token(*f),
                SigmaValue::Bool(b) => b.to_string(),
                SigmaValue::Null => "null".to_string(),
                SigmaValue::String(_) => unreachable!("string handled above"),
            };
            let prefix = match lead {
                Lead::Key(key) => format!("{indent}{key}:"),
                Lead::Dash => format!("{indent}-"),
            };
            let _ = writeln!(out, "{prefix} {token}");
        }
    }
}

// =============================================================================
// yaml_serde value emission (custom attributes)
// =============================================================================

fn emit_yaml_value(out: &mut String, key: &str, value: &yaml_serde::Value, indent: &str) {
    match value {
        yaml_serde::Value::Mapping(map) if !map.is_empty() => {
            let _ = writeln!(out, "{indent}{key}:");
            for (k, v) in map {
                let child_key = yaml_key(k);
                emit_yaml_value(out, &child_key, v, &deeper(indent));
            }
        }
        yaml_serde::Value::Mapping(_) => {
            let _ = writeln!(out, "{indent}{key}: {{}}");
        }
        yaml_serde::Value::Sequence(seq) if !seq.is_empty() => {
            let _ = writeln!(out, "{indent}{key}:");
            for v in seq {
                emit_yaml_seq_item(out, v, &deeper(indent));
            }
        }
        yaml_serde::Value::Sequence(_) => {
            let _ = writeln!(out, "{indent}{key}: []");
        }
        yaml_serde::Value::String(s) => {
            push_scalar(out, indent, Lead::Key(key), s, ScalarCtx::Value);
        }
        scalar => {
            let _ = writeln!(out, "{indent}{key}: {}", yaml_scalar(scalar));
        }
    }
}

/// Emit one YAML sequence item, including nested mappings and sequences.
fn emit_yaml_seq_item(out: &mut String, value: &yaml_serde::Value, indent: &str) {
    match value {
        yaml_serde::Value::Mapping(map) if !map.is_empty() => {
            let mut buf = String::new();
            for (k, v) in map {
                let child_key = yaml_key(k);
                emit_yaml_value(&mut buf, &child_key, v, "");
            }
            for (i, line) in buf.lines().enumerate() {
                if i == 0 {
                    let _ = writeln!(out, "{indent}- {line}");
                } else {
                    let _ = writeln!(out, "{indent}  {line}");
                }
            }
        }
        yaml_serde::Value::Mapping(_) => {
            let _ = writeln!(out, "{indent}- {{}}");
        }
        yaml_serde::Value::Sequence(seq) if !seq.is_empty() => {
            let _ = writeln!(out, "{indent}-");
            for v in seq {
                emit_yaml_seq_item(out, v, &deeper(indent));
            }
        }
        yaml_serde::Value::Sequence(_) => {
            let _ = writeln!(out, "{indent}- []");
        }
        yaml_serde::Value::String(s) => {
            push_scalar(out, indent, Lead::Dash, s, ScalarCtx::Value);
        }
        scalar => {
            let _ = writeln!(out, "{indent}- {}", yaml_scalar(scalar));
        }
    }
}

fn yaml_key(value: &yaml_serde::Value) -> String {
    match value {
        yaml_serde::Value::String(s) => encode_key(s, KeyCtx::Key),
        other => yaml_scalar(other),
    }
}

fn yaml_scalar(value: &yaml_serde::Value) -> String {
    match value {
        yaml_serde::Value::Null => "null".to_string(),
        yaml_serde::Value::Bool(b) => b.to_string(),
        yaml_serde::Value::Number(n) if n.is_f64() => float_token(n.as_f64().unwrap_or_default()),
        yaml_serde::Value::Number(n) => n.to_string(),
        yaml_serde::Value::String(s) => encode_key(s, KeyCtx::Key),
        // Nested collections are handled by emit_yaml_value; an inline fallback
        // keeps the emitter total for unexpected placements.
        other => format!("{other:?}"),
    }
}

// =============================================================================
// Scalars, keys, and value tokens
// =============================================================================

/// Format a float so it re-parses as a float (never collapses `3.0` to `3`).
fn float_token(f: f64) -> String {
    if f.is_nan() {
        return ".nan".to_string();
    }
    if f == f64::INFINITY {
        return ".inf".to_string();
    }
    if f == f64::NEG_INFINITY {
        return "-.inf".to_string();
    }
    let s = f.to_string();
    if s.contains(['.', 'e', 'E']) {
        s
    } else {
        format!("{s}.0")
    }
}

/// Reconstruct the Sigma source text of a [`SigmaString`], escaping literal
/// wildcard and backslash characters so the value round-trips through the
/// parser unchanged.
fn sigma_string_source(value: &SigmaString) -> String {
    let mut out = String::with_capacity(value.original.len());
    for part in &value.parts {
        match part {
            StringPart::Plain(text) => push_escaped_literal(&mut out, text),
            StringPart::Special(SpecialChar::WildcardMulti) => out.push('*'),
            StringPart::Special(SpecialChar::WildcardSingle) => out.push('?'),
        }
    }
    out
}

/// Escape a literal segment: `*`/`?` always gain a backslash; a run of
/// backslashes is doubled only when it would otherwise bind to a following
/// wildcard or end the value (keeping plain Windows paths readable).
fn push_escaped_literal(out: &mut String, text: &str) {
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        match chars[i] {
            '*' => out.push_str("\\*"),
            '?' => out.push_str("\\?"),
            '\\' => {
                let mut j = i;
                while j < chars.len() && chars[j] == '\\' {
                    j += 1;
                }
                let run = j - i;
                let next = chars.get(j);
                let must_escape = run > 1 || matches!(next, Some('*') | Some('?') | None);
                for _ in 0..run {
                    out.push_str(if must_escape { "\\\\" } else { "\\" });
                }
                i = j;
                continue;
            }
            other => out.push(other),
        }
        i += 1;
    }
}

/// Build a detection key from a field name and its ordered modifiers.
fn field_key(field: &str, modifiers: &[Modifier]) -> String {
    let mut key = String::new();
    key.push_str(field);
    for modifier in modifiers {
        key.push('|');
        key.push_str(modifier_str(*modifier));
    }
    encode_key(&key, KeyCtx::FieldKey)
}

pub(crate) fn modifier_str(modifier: Modifier) -> &'static str {
    match modifier {
        Modifier::Contains => "contains",
        Modifier::StartsWith => "startswith",
        Modifier::EndsWith => "endswith",
        Modifier::All => "all",
        Modifier::Base64 => "base64",
        Modifier::Base64Offset => "base64offset",
        Modifier::Wide => "wide",
        Modifier::Utf16be => "utf16be",
        Modifier::Utf16 => "utf16",
        Modifier::WindAsh => "windash",
        Modifier::Re => "re",
        Modifier::Cidr => "cidr",
        Modifier::Cased => "cased",
        Modifier::Exists => "exists",
        Modifier::Expand => "expand",
        Modifier::FieldRef => "fieldref",
        Modifier::Gt => "gt",
        Modifier::Gte => "gte",
        Modifier::Lt => "lt",
        Modifier::Lte => "lte",
        Modifier::Neq => "neq",
        Modifier::IgnoreCase => "i",
        Modifier::Multiline => "m",
        Modifier::DotAll => "s",
        Modifier::Minute => "minute",
        Modifier::Hour => "hour",
        Modifier::Day => "day",
        Modifier::Week => "week",
        Modifier::Month => "month",
        Modifier::Year => "year",
    }
}

fn status_str(status: Status) -> &'static str {
    match status {
        Status::Stable => "stable",
        Status::Test => "test",
        Status::Experimental => "experimental",
        Status::Deprecated => "deprecated",
        Status::Unsupported => "unsupported",
    }
}

fn operator_str(op: ConditionOperator) -> &'static str {
    match op {
        ConditionOperator::Lt => "lt",
        ConditionOperator::Lte => "lte",
        ConditionOperator::Gt => "gt",
        ConditionOperator::Gte => "gte",
        ConditionOperator::Eq => "eq",
        ConditionOperator::Neq => "neq",
    }
}

fn operator_rank(op: ConditionOperator) -> u8 {
    match op {
        ConditionOperator::Lt => 0,
        ConditionOperator::Lte => 1,
        ConditionOperator::Gt => 2,
        ConditionOperator::Gte => 3,
        ConditionOperator::Eq => 4,
        ConditionOperator::Neq => 5,
    }
}

fn relation_str(relation: RelationType) -> &'static str {
    match relation {
        RelationType::Correlation => "correlation",
        RelationType::Derived => "derived",
        RelationType::Obsolete => "obsolete",
        RelationType::Merged => "merged",
        RelationType::Renamed => "renamed",
        RelationType::Similar => "similar",
    }
}

fn array_str(quantifier: ArrayQuantifier) -> &'static str {
    match quantifier {
        ArrayQuantifier::Any => "any",
        ArrayQuantifier::All => "all",
        ArrayQuantifier::AllOrEmpty => "all_or_empty",
        ArrayQuantifier::None => "none",
    }
}

// =============================================================================
// Small helpers
// =============================================================================

fn deeper(indent: &str) -> String {
    format!("{indent}{STEP}")
}

fn sorted(map: &std::collections::HashMap<String, String>) -> Vec<(&str, &str)> {
    let mut entries: Vec<(&str, &str)> =
        map.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));
    entries
}

fn sorted_named(map: &std::collections::HashMap<String, Detection>) -> Vec<(&str, &Detection)> {
    let mut entries: BTreeMap<&str, &Detection> = BTreeMap::new();
    for (k, v) in map {
        entries.insert(k.as_str(), v);
    }
    entries.into_iter().collect()
}

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

    /// Assert the emitter is a stable canonical form: `emit(parse(x))` re-parses
    /// to one rule and re-emits to a byte-identical string. This is the correct
    /// round-trip criterion; it does not depend on the raw source spelling a
    /// [`SigmaString`] preserves in its `original` field.
    fn assert_round_trips(yaml: &str) -> String {
        let first = parse_sigma_yaml(yaml).expect("input parses");
        assert_eq!(first.rules.len(), 1, "expected one input rule");
        let emitted = emit_rule_yaml(&first.rules[0]);

        let reparsed = parse_sigma_yaml(&emitted)
            .unwrap_or_else(|e| panic!("emitted YAML must re-parse: {e}\n---\n{emitted}"));
        assert_eq!(
            reparsed.rules.len(),
            1,
            "expected one rule, got:\n{emitted}"
        );

        let reemitted = emit_rule_yaml(&reparsed.rules[0]);
        assert_eq!(emitted, reemitted, "emit is not idempotent:\n{emitted}");
        emitted
    }

    #[test]
    fn round_trips_minimal_rule() {
        assert_round_trips(
            "title: Whoami\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection:\n        CommandLine|contains: whoami\n    condition: selection\nlevel: medium\n",
        );
    }

    #[test]
    fn round_trips_modifiers_and_value_lists() {
        assert_round_trips(
            "title: Modifiers\nlogsource:\n    product: windows\ndetection:\n    selection:\n        Image|endswith:\n            - '\\\\cmd.exe'\n            - '\\\\powershell.exe'\n        CommandLine|contains|all:\n            - foo\n            - bar\n        Field|re: 'ab.*c'\n        Port|gt: 1024\n        User|cased: Admin\n    filter:\n        Image|startswith: 'C:\\\\Windows\\\\'\n    condition: selection and not filter\nlevel: high\n",
        );
    }

    #[test]
    fn round_trips_keywords_and_anyof() {
        assert_round_trips(
            "title: Keywords\nlogsource:\n    product: linux\ndetection:\n    keywords:\n        - mimikatz\n        - sekurlsa\n    selection:\n        - EventID: 1\n        - EventID: 4688\n    condition: keywords and selection\n",
        );
    }

    #[test]
    fn round_trips_metadata_and_selector_condition() {
        assert_round_trips(
            "title: Full Metadata\nid: 11111111-2222-3333-4444-555555555555\nstatus: experimental\ndescription: A single line description.\nreferences:\n    - https://example.com/a\nauthor: Jane Doe\ndate: 2026-01-01\ntags:\n    - attack.execution\n    - attack.t1059\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection_a:\n        Image|endswith: '\\\\a.exe'\n    selection_b:\n        Image|endswith: '\\\\b.exe'\n    condition: 1 of selection_*\nfalsepositives:\n    - Legitimate admin use\nlevel: low\n",
        );
    }

    #[test]
    fn escapes_wildcards_in_literal_values() {
        // A literal asterisk in the value must survive as a literal, not a wildcard.
        let yaml = "title: Escapes\nlogsource:\n    product: test\ndetection:\n    selection:\n        Field: 'a\\*b'\n    condition: selection\n";
        let emitted = assert_round_trips(yaml);
        assert!(
            emitted.contains(r"a\*b"),
            "expected escaped glob, got:\n{emitted}"
        );
    }

    #[test]
    fn empty_logsource_emits_a_mapping_the_parser_rejects() {
        let mut rule = parse_sigma_yaml(
            "title: No Logsource\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n",
        )
        .unwrap()
        .rules
        .remove(0);
        rule.logsource = LogSource::default();
        let emitted = emit_rule_yaml(&rule);
        assert!(emitted.contains("logsource: {}"), "{emitted}");
        let errors = parse_sigma_yaml(&emitted).unwrap().diagnostics;
        assert!(
            errors[0]
                .message
                .contains("at least one of category, product, or service"),
            "{errors:?}"
        );
    }

    #[test]
    fn round_trips_detection_exemplars() {
        let emitted = assert_round_trips(
            "title: Whoami\nid: 11111111-2222-3333-4444-555555555555\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection:\n        CommandLine|contains: whoami\n    condition: selection\ncustom_attributes:\n    rsigma.exemplars:\n        - name: whoami fires\n          expect: match\n          event:\n              CommandLine: whoami /all\n        - name: benign hostname\n          expect: no-match\n          event:\n              CommandLine: hostname\n",
        );
        assert!(
            emitted.contains("rsigma.exemplars:"),
            "expected exemplars in emit:\n{emitted}"
        );
        assert!(
            emitted.contains("whoami fires"),
            "expected exemplar name:\n{emitted}"
        );
        let reparsed = parse_sigma_yaml(&emitted).unwrap();
        let attrs = &reparsed.rules[0].custom_attributes;
        let list = crate::exemplar::exemplars_from_attrs(
            attrs,
            crate::exemplar::ExemplarRuleKind::Detection,
        )
        .expect("emitted exemplars re-parse");
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].expect, crate::exemplar::Expect::Match);
        assert_eq!(list[1].expect, crate::exemplar::Expect::NoMatch);
    }

    #[test]
    fn emit_preserves_correlation_shaped_exemplar_sequence() {
        let emitted = assert_round_trips(
            "title: Burst host\nlogsource:\n    category: auth\ndetection:\n    selection:\n        EventType: login\n    condition: selection\ncustom_attributes:\n    rsigma.exemplars:\n        - name: burst\n          expect: match\n          event:\n              EventType: login\n              User: alice\n",
        );
        assert!(emitted.contains("User:"), "{emitted}");
    }

    #[test]
    fn round_trips_array_object_scope_block() {
        assert_round_trips(
            "title: Array\nsigma-version: 3\nlogsource:\n    category: test\ndetection:\n    selection:\n        connections[any]:\n            protocol: TCP\n            port: 445\n    condition: selection\n",
        );
    }

    #[test]
    fn quotes_strings_that_yaml_would_read_as_another_type() {
        assert_round_trips(
            "title: 'True'\nid: '123'\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: '0x1F'\n        Other: '1_000'\n        Third: '1:30'\n    condition: selection\n",
        );
    }

    #[test]
    fn emits_reference_urls_plain() {
        let emitted = assert_round_trips(
            "title: URL\nreferences:\n    - https://example.com/a?b=c\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n",
        );
        assert!(
            emitted.contains("- https://example.com/a?b=c\n"),
            "expected a plain URL:\n{emitted}"
        );
    }

    #[test]
    fn emits_multi_line_values_as_literal_blocks() {
        let emitted = assert_round_trips(
            "title: Multiline\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: |-\n            first line\n            second line\n    condition: selection\n",
        );
        assert!(emitted.contains("Field: |-"), "{emitted}");
    }

    #[test]
    fn quotes_a_field_name_with_a_space_as_one_key() {
        let emitted = assert_round_trips(
            "title: Space\nlogsource:\n    category: test\ndetection:\n    selection:\n        'Product Name|contains': thing\n    condition: selection\n",
        );
        assert!(
            emitted.contains("'Product Name|contains': thing"),
            "{emitted}"
        );
    }

    #[test]
    fn emits_empty_custom_attribute_collections() {
        let emitted = assert_round_trips(
            "title: Empty\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\nempty_map: {}\nempty_seq: []\n",
        );
        assert!(emitted.contains("empty_map: {}"), "{emitted}");
        assert!(emitted.contains("empty_seq: []"), "{emitted}");
    }

    #[test]
    fn quotes_a_condition_that_would_read_as_another_type() {
        let emitted = assert_round_trips(
            "title: Condition\nlogsource:\n    category: test\ndetection:\n    '1e3':\n        Field: value\n    condition: '1e3'\n",
        );
        assert!(emitted.contains("condition: '1e3'"), "{emitted}");
    }

    #[test]
    fn emits_root_keys_in_canonical_order() {
        let yaml = "\
zzz: last
title: Order
aaa: first
id: 11111111-2222-3333-4444-555555555555
name: order
status: experimental
description: Order test.
references:
    - https://example.com
author: Jane Doe
date: 2026-01-01
modified: 2026-02-01
related:
    - id: 22222222-3333-4444-5555-666666666666
      type: derived
tags:
    - attack.execution
sigma-version: 3
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        Field: value
    condition: selection
fields:
    - Field
falsepositives:
    - None known
level: medium
scope:
    - endpoint
license: MIT
taxonomy: attack
rsigma.exemplars:
    - name: example
      expect: match
      event:
          Field: value
rsigma.suppress:
    - reason: noisy
";
        let rule = parse_sigma_yaml(yaml)
            .expect("input parses")
            .rules
            .remove(0);
        let emitted = emit_rule_yaml(&rule);
        let root_keys: Vec<&str> = emitted
            .lines()
            .filter(|line| !line.starts_with(' ') && line.contains(':'))
            .map(|line| line.split(':').next().unwrap_or_default())
            .collect();
        let expected = [
            "title",
            "id",
            "name",
            "status",
            "description",
            "references",
            "author",
            "date",
            "modified",
            "related",
            "tags",
            "sigma-version",
            "logsource",
            "detection",
            "fields",
            "falsepositives",
            "level",
            "scope",
            "license",
            "taxonomy",
            "rsigma.suppress",
            "rsigma.exemplars",
            "aaa",
            "zzz",
        ];
        assert_eq!(root_keys, expected, "{emitted}");
    }

    fn assert_correlation_round_trips(yaml: &str) -> String {
        let first = parse_sigma_yaml(yaml).expect("input parses");
        assert_eq!(first.correlations.len(), 1, "expected one correlation");
        let emitted = emit_correlation_yaml(&first.correlations[0]);
        let reparsed = parse_sigma_yaml(&emitted)
            .unwrap_or_else(|e| panic!("emitted YAML must re-parse: {e}\n---\n{emitted}"));
        assert_eq!(reparsed.correlations.len(), 1, "{emitted}");
        assert_eq!(first.correlations[0], reparsed.correlations[0]);
        assert_eq!(emitted, emit_correlation_yaml(&reparsed.correlations[0]));
        emitted
    }

    fn assert_filter_round_trips(yaml: &str) -> String {
        let first = parse_sigma_yaml(yaml).expect("input parses");
        assert_eq!(first.filters.len(), 1, "expected one filter");
        let emitted = emit_filter_yaml(&first.filters[0]);
        let reparsed = parse_sigma_yaml(&emitted)
            .unwrap_or_else(|e| panic!("emitted YAML must re-parse: {e}\n---\n{emitted}"));
        assert_eq!(reparsed.filters.len(), 1, "{emitted}");
        assert_eq!(first.filters[0], reparsed.filters[0]);
        assert_eq!(emitted, emit_filter_yaml(&reparsed.filters[0]));
        emitted
    }

    #[test]
    fn round_trips_event_count_session_gap_aliases() {
        let emitted = assert_correlation_round_trips(
            "title: Session burst\nid: 11111111-2222-3333-4444-555555555555\ndescription: Too many logins.\ntags:\n    - attack.credential_access\ncorrelation:\n    type: event_count\n    rules:\n        - failed_login\n        - failed_ssh\n    group-by:\n        - User\n    timespan: 1h\n    window: session\n    gap: 5m\n    condition:\n        gte: 10\n    aliases:\n        user:\n            failed_login: User\n            failed_ssh: Username\n    generate: true\nlevel: high\n",
        );
        assert!(emitted.contains("window: session"), "{emitted}");
        assert!(emitted.contains("gap: 5m"), "{emitted}");
        assert!(emitted.contains("generate: true"), "{emitted}");
        assert!(emitted.contains("failed_login: User"), "{emitted}");
    }

    #[test]
    fn round_trips_value_count_range_and_field() {
        let emitted = assert_correlation_round_trips(
            "title: Port scan\ncorrelation:\n    type: value_count\n    rules:\n        - connection\n    group-by:\n        - SourceIp\n    timespan: 5m\n    condition:\n        gt: 100\n        lte: 200\n        field:\n            - DestPort\n",
        );
        assert!(emitted.contains("gt: 100"), "{emitted}");
        assert!(emitted.contains("lte: 200"), "{emitted}");
        assert!(emitted.contains("DestPort"), "{emitted}");
    }

    #[test]
    fn round_trips_value_percentile() {
        assert_correlation_round_trips(
            "title: Slow tail\ncorrelation:\n    type: value_percentile\n    rules:\n        - latency\n    group-by:\n        - Service\n    timespan: 10m\n    condition:\n        gte: 95\n        field: LatencyMs\n        percentile: 99\n",
        );
    }

    #[test]
    fn round_trips_value_sum_avg_median() {
        assert_correlation_round_trips(
            "title: Sum\ncorrelation:\n    type: value_sum\n    rules:\n        - transfer\n    group-by:\n        - User\n    timespan: 1h\n    condition:\n        gte: 1000\n        field: Bytes\n",
        );
        assert_correlation_round_trips(
            "title: Avg\ncorrelation:\n    type: value_avg\n    rules:\n        - transfer\n    group-by:\n        - User\n    timespan: 1h\n    condition:\n        gte: 1000\n        field: Bytes\n",
        );
        assert_correlation_round_trips(
            "title: Median\ncorrelation:\n    type: value_median\n    rules:\n        - transfer\n    group-by:\n        - User\n    timespan: 1h\n    condition:\n        gte: 1000\n        field: Bytes\n",
        );
    }

    #[test]
    fn round_trips_temporal_extended_and_ordered() {
        assert_correlation_round_trips(
            "title: Login then process\ncorrelation:\n    type: temporal\n    rules:\n        - login\n        - process_start\n    group-by:\n        - User\n    timespan: 10m\n    condition: login and process_start\n",
        );
        assert_correlation_round_trips(
            "title: Ordered\ncorrelation:\n    type: temporal_ordered\n    rules:\n        - login\n        - process_start\n    group-by:\n        - User\n    timespan: 10m\n    condition: login and process_start\n",
        );
    }

    #[test]
    fn round_trips_tumbling_window() {
        assert_correlation_round_trips(
            "title: Tumbling\ncorrelation:\n    type: event_count\n    rules:\n        - login\n    group-by:\n        - User\n    timespan: 1h\n    window: tumbling\n    condition:\n        gte: 5\n",
        );
    }

    #[test]
    fn round_trips_filter_any() {
        let emitted = assert_filter_round_trips(
            "title: Drop system accounts\nlogsource:\n    product: windows\n    category: process_creation\nfilter:\n    selection:\n        User|endswith: '$'\n    condition: selection\n",
        );
        assert!(!emitted.contains("rules:"), "{emitted}");
    }

    #[test]
    fn round_trips_filter_specific_logsource() {
        let emitted = assert_filter_round_trips(
            "title: Drop admin whoami\nid: 22222222-3333-4444-5555-666666666666\nlogsource:\n    product: windows\n    service: security\nfilter:\n    rules:\n        - 11111111-2222-3333-4444-555555555555\n        - whoami_rule\n    selection:\n        Image|endswith: '\\whoami.exe'\n    filter_main_system:\n        User: SYSTEM\n    condition: selection and not filter_main_system\n",
        );
        assert!(emitted.contains("rules:"), "{emitted}");
        assert!(emitted.contains("whoami_rule"), "{emitted}");
        assert!(emitted.contains("filter_main_system"), "{emitted}");
    }

    #[test]
    fn round_trips_a_detection_timeframe() {
        let emitted = assert_round_trips(
            "title: Burst\nlogsource:\n    product: windows\ndetection:\n    selection:\n        EventID: 4625\n    condition: selection\n    timeframe: 5m\n",
        );
        assert!(emitted.contains("    timeframe: 5m\n"), "{emitted}");
    }

    #[test]
    fn round_trips_a_filter_timeframe() {
        let emitted = assert_filter_round_trips(
            "title: Drop bursts\nlogsource:\n    product: windows\nfilter:\n    selection:\n        User: SYSTEM\n    condition: selection\n    timeframe: 5m\n",
        );
        assert!(emitted.contains("    timeframe: 5m\n"), "{emitted}");
    }
}