rsigma-eval 0.24.0

Evaluator for Sigma detection and correlation rules — match rules against events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
use std::collections::HashMap;

use regex::Regex;

use rsigma_parser::{
    ConditionExpr, Detection, DetectionItem, FieldSpec, LogSource, Modifier, SigmaRule,
    SigmaString, SigmaValue, SpecialChar, StringPart,
};

use super::super::conditions::{ConditionSet, DetectionItemCondition, FieldNameCondition};
use super::super::state::PipelineState;
use crate::error::{EvalError, Result};

// =============================================================================
// Field name transformation helper
// =============================================================================

/// Max branches a single one-to-many field-name expansion can produce inside
/// one `AllOf`.
///
/// The Cartesian product of per-item alternative lists grows fast
/// (e.g. 10 items * 5 alternatives each = ~9.7M branches). pySigma
/// materializes expanded rules once for query generation, but rsigma
/// evaluates rules against live events, so a blown-up detection tree stays
/// in the hot path permanently. We reject expansions above this threshold at
/// load time instead of silently ballooning memory and CPU.
const MAX_FIELD_MAPPING_COMBINATIONS: usize = 4096;

/// Apply a field-name-rewriting closure to every detection in `rule`.
///
/// The closure returns `None` to leave a name untouched, `Some(vec)` to
/// rewrite it. A single-element `Some` renames the item in place. Multiple
/// alternatives expand the matched item into an OR over the alternatives;
/// the surrounding `AllOf` becomes an `AnyOf` of `AllOf`s via Cartesian
/// expansion (see `transform_detection_fields`).
///
/// The rule's `fields` list is renamed too. Renames of `fields` entries and
/// field reference targets are recorded for field-name
/// `processing_item_applied` conditions, as pySigma does.
pub(super) fn apply_field_name_transform<F>(
    rule: &mut SigmaRule,
    state: &mut PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    transform_fn: F,
) -> Result<()>
where
    F: Fn(&str) -> Option<Vec<String>>,
{
    let mut renames = Vec::new();
    rule.fields = rename_field_list(
        std::mem::take(&mut rule.fields),
        state,
        field_name_conditions,
        &transform_fn,
        &mut renames,
    );
    let rule_title = rule.title.clone();
    for detection in rule.detection.named.values_mut() {
        transform_detection_fields(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            &transform_fn,
            &rule_title,
            &mut renames,
        )?;
    }
    state.track_field_renames(renames);
    Ok(())
}

/// A field renamed from the first name to the second list.
pub(in crate::pipeline) type FieldRename = (String, Vec<String>);

/// Rename the entries of a rule's `fields` list that pass the field-name
/// conditions, expanding one-to-many mappings.
pub(in crate::pipeline) fn rename_field_list<F>(
    fields: Vec<String>,
    state: &PipelineState,
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    transform_fn: &F,
    renames: &mut Vec<FieldRename>,
) -> Vec<String>
where
    F: Fn(&str) -> Option<Vec<String>>,
{
    let mut renamed = Vec::with_capacity(fields.len());
    for field in fields {
        match transform_fn(&field) {
            Some(names)
                if !names.is_empty()
                    && field_conditions_match(&field, state, field_name_conditions) =>
            {
                renamed.extend(names.iter().cloned());
                renames.push((field, names));
            }
            _ => renamed.push(field),
        }
    }
    renamed
}

fn transform_detection_fields<F>(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    transform_fn: &F,
    rule_title: &str,
    renames: &mut Vec<FieldRename>,
) -> Result<()>
where
    F: Fn(&str) -> Option<Vec<String>>,
{
    match detection {
        Detection::AllOf(items) => {
            let detection_matches: Vec<bool> = items
                .iter()
                .map(|item| {
                    item_conditions_match(item, state, detection_conditions, field_name_conditions)
                })
                .collect();
            for (item, matches) in items.iter_mut().zip(&detection_matches) {
                if *matches {
                    transform_field_reference_values(
                        item,
                        state,
                        field_name_conditions,
                        transform_fn,
                        rule_title,
                        renames,
                    )?;
                }
            }

            // First pass (read-only): resolve each item's mapping result.
            // Store either a single rename or a multi-alternative expansion.
            enum Resolved {
                Unchanged,
                Renamed(String),
                Expanded(Vec<String>),
            }
            let resolved: Vec<Resolved> = items
                .iter()
                .zip(detection_matches)
                .map(
                    |(item, detection_matches)| match item.field.name.as_deref() {
                        Some(name)
                            if detection_matches
                                && field_conditions_match(name, state, field_name_conditions) =>
                        {
                            match transform_fn(name) {
                                Some(new_names) if new_names.len() > 1 => {
                                    Resolved::Expanded(new_names)
                                }
                                Some(mut new_names) if new_names.len() == 1 => {
                                    Resolved::Renamed(new_names.pop().unwrap())
                                }
                                _ => Resolved::Unchanged,
                            }
                        }
                        _ => Resolved::Unchanged,
                    },
                )
                .collect();

            let needs_expansion = resolved.iter().any(|r| matches!(r, Resolved::Expanded(_)));

            if !needs_expansion {
                // Fast path: apply 1:1 renames in-place, no cloning.
                for (item, res) in items.iter_mut().zip(resolved) {
                    if let Resolved::Renamed(new_name) = res {
                        item.field.name = Some(new_name);
                    }
                }
            } else {
                // Build per-item alternative lists for the Cartesian product.
                let alternatives: Vec<Vec<DetectionItem>> = items
                    .iter()
                    .zip(resolved)
                    .map(|(item, res)| match res {
                        Resolved::Expanded(names) => names
                            .into_iter()
                            .map(|new_name| {
                                let mut clone = item.clone();
                                clone.field.name = Some(new_name);
                                clone
                            })
                            .collect(),
                        Resolved::Renamed(name) => {
                            let mut clone = item.clone();
                            clone.field.name = Some(name);
                            vec![clone]
                        }
                        Resolved::Unchanged => vec![item.clone()],
                    })
                    .collect();

                let total = alternatives
                    .iter()
                    .map(Vec::len)
                    .fold(1usize, |acc, n| acc.saturating_mul(n));
                if total > MAX_FIELD_MAPPING_COMBINATIONS {
                    let sizes: Vec<usize> = alternatives.iter().map(Vec::len).collect();
                    return Err(EvalError::InvalidModifiers(format!(
                        "field name mapping cartesian expansion would produce {total} \
                         branches, exceeding the limit of {MAX_FIELD_MAPPING_COMBINATIONS} \
                         (rule: {rule_title}, per-item alternative counts: {sizes:?}); \
                         reduce the number of one-to-many alternatives or split the AllOf"
                    )));
                }
                let combinations = cartesian_product(alternatives);
                *detection =
                    Detection::AnyOf(combinations.into_iter().map(Detection::AllOf).collect());
            }
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                transform_detection_fields(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    transform_fn,
                    rule_title,
                    renames,
                )?;
            }
        }
        Detection::ArrayMatch { body, .. } => {
            transform_detection_fields(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                transform_fn,
                rule_title,
                renames,
            )?;
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                transform_detection_fields(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    transform_fn,
                    rule_title,
                    renames,
                )?;
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                transform_detection_fields(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    transform_fn,
                    rule_title,
                    renames,
                )?;
            }
        }
        Detection::Keywords(_) => {}
    }
    Ok(())
}

fn transform_field_reference_values<F>(
    item: &mut DetectionItem,
    state: &PipelineState,
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    transform_fn: &F,
    rule_title: &str,
    renames: &mut Vec<FieldRename>,
) -> Result<()>
where
    F: Fn(&str) -> Option<Vec<String>>,
{
    if !item.field.modifiers.contains(&Modifier::FieldRef) {
        return Ok(());
    }

    let mut mapped_values = Vec::new();
    for value in item.values.drain(..) {
        let SigmaValue::String(field_ref) = &value else {
            mapped_values.push(value);
            continue;
        };
        let Some(field_name) = field_ref.as_plain() else {
            mapped_values.push(value);
            continue;
        };
        if !field_conditions_match(&field_name, state, field_name_conditions) {
            mapped_values.push(value);
            continue;
        }

        match transform_fn(&field_name) {
            Some(names) if !names.is_empty() => {
                if mapped_values.len().saturating_add(names.len()) > MAX_FIELD_MAPPING_COMBINATIONS
                {
                    return Err(EvalError::InvalidModifiers(format!(
                        "field reference mapping would produce more than \
                         {MAX_FIELD_MAPPING_COMBINATIONS} values (rule: {rule_title})"
                    )));
                }
                mapped_values.extend(
                    names
                        .iter()
                        .map(|name| SigmaValue::String(SigmaString::new(name))),
                );
                renames.push((field_name, names));
            }
            _ => mapped_values.push(value),
        }
    }
    item.values = mapped_values;
    Ok(())
}

/// Build the Cartesian product of a sequence of alternative lists.
///
/// `[[a, b], [c]]` → `[[a, c], [b, c]]`.
/// Empty input yields a single empty combination so callers handle the edge
/// case uniformly.
fn cartesian_product<T: Clone>(input: Vec<Vec<T>>) -> Vec<Vec<T>> {
    let mut result: Vec<Vec<T>> = vec![Vec::new()];
    for group in input {
        let mut next = Vec::with_capacity(result.len() * group.len().max(1));
        for prefix in &result {
            for elem in &group {
                let mut combo = prefix.clone();
                combo.push(elem.clone());
                next.push(combo);
            }
        }
        result = next;
    }
    result
}

fn field_conditions_match(
    field_name: &str,
    state: &PipelineState,
    condition_sets: &[&ConditionSet<FieldNameCondition>],
) -> bool {
    condition_sets
        .iter()
        .all(|set| set.matches(|condition| condition.matches_field_name(field_name, state)))
}

// =============================================================================
// Drop detection items
// =============================================================================

pub(super) fn drop_detection_items(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
) {
    for detection in rule.detection.named.values_mut() {
        drop_from_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
        );
    }
}

fn drop_from_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
) {
    match detection {
        Detection::AllOf(items) => {
            items.retain(|item| {
                !item_conditions_match(item, state, detection_conditions, field_name_conditions)
            });
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                drop_from_detection(sub, state, detection_conditions, field_name_conditions);
            }
        }
        Detection::ArrayMatch { body, .. } => {
            drop_from_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
            );
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                drop_from_detection(sub, state, detection_conditions, field_name_conditions);
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                drop_from_detection(sub, state, detection_conditions, field_name_conditions);
            }
        }
        Detection::Keywords(_) => {}
    }
}

fn detection_conditions_match(
    item: &DetectionItem,
    state: &PipelineState,
    condition_sets: &[&ConditionSet<DetectionItemCondition>],
) -> bool {
    condition_sets
        .iter()
        .all(|set| set.matches(|condition| condition.matches_item(item, state)))
}

// =============================================================================
// Add conditions
// =============================================================================

/// Parameters of an `add_condition` transformation.
pub(super) struct AddedCondition<'a> {
    pub(super) conditions: &'a HashMap<String, Vec<SigmaValue>>,
    pub(super) field_refs: &'a HashMap<String, String>,
    pub(super) negated: bool,
    pub(super) prepend: bool,
    pub(super) name: Option<&'a str>,
    pub(super) template: bool,
}

pub(super) fn add_conditions(rule: &mut SigmaRule, added: &AddedCondition<'_>) -> Result<()> {
    let logsource = rule.logsource.clone();
    let mut items: Vec<DetectionItem> = added
        .conditions
        .iter()
        .map(|(field, values)| DetectionItem {
            field: FieldSpec::new(Some(field.clone()), Vec::new()),
            values: if added.template {
                values
                    .iter()
                    .map(|value| match value {
                        SigmaValue::String(s) => SigmaValue::String(SigmaString::new(
                            &substitute_logsource_template(&s.original, &logsource),
                        )),
                        other => other.clone(),
                    })
                    .collect()
            } else {
                values.clone()
            },
        })
        .collect();

    // Field-to-field equalities lower through the `fieldref` modifier so the
    // value is treated as another field name (`field = other_field`), not a
    // string literal.
    items.extend(
        added
            .field_refs
            .iter()
            .map(|(field, target)| DetectionItem {
                field: FieldSpec::new(Some(field.clone()), vec![Modifier::FieldRef]),
                values: vec![SigmaValue::String(SigmaString::new(target))],
            }),
    );

    let det_name = match added.name {
        Some(name) if rule.detection.named.contains_key(name) => {
            return Err(EvalError::InvalidModifiers(format!(
                "add_condition name '{name}' collides with an existing detection (rule: {})",
                rule.title
            )));
        }
        Some(name) => name.to_string(),
        None => format!("__pipeline_cond_{}", rule.detection.named.len()),
    };
    rule.detection
        .named
        .insert(det_name.clone(), Detection::AllOf(items));

    // Add to existing conditions: AND (or AND NOT if negated)
    let cond_ref = ConditionExpr::Identifier(det_name);
    let cond_expr = if added.negated {
        ConditionExpr::Not(Box::new(cond_ref))
    } else {
        cond_ref
    };

    rule.detection.conditions = rule
        .detection
        .conditions
        .iter()
        .map(|existing| {
            // `prepend` puts the added condition first (`new AND
            // existing`) so left-to-right short-circuiting engines
            // evaluate the cheap discriminator before the rule body;
            // the default appends (`existing AND new`).
            let parts = if added.prepend {
                vec![cond_expr.clone(), existing.clone()]
            } else {
                vec![existing.clone(), cond_expr.clone()]
            };
            ConditionExpr::And(parts)
        })
        .collect();
    Ok(())
}

/// Substitute `$category`, `$product`, and `$service` (or the `${name}`
/// form) with the logsource values, following Python's
/// `string.Template.safe_substitute`: `$$` is a literal `$`, and unknown
/// names, unset logsource values, and a bare `$` are left as written.
fn substitute_logsource_template(text: &str, logsource: &LogSource) -> String {
    fn is_ident_start(c: char) -> bool {
        c == '_' || c.is_ascii_alphabetic()
    }
    fn is_ident_continue(c: char) -> bool {
        c == '_' || c.is_ascii_alphanumeric()
    }
    let lookup = |name: &str| match name {
        "category" => logsource.category.as_deref(),
        "product" => logsource.product.as_deref(),
        "service" => logsource.service.as_deref(),
        _ => None,
    };

    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(pos) = rest.find('$') {
        out.push_str(&rest[..pos]);
        let after = &rest[pos + 1..];
        if let Some(stripped) = after.strip_prefix('$') {
            out.push('$');
            rest = stripped;
            continue;
        }
        let (name, consumed) = if let Some(braced) = after.strip_prefix('{') {
            match braced.find('}') {
                Some(end)
                    if braced[..end].starts_with(is_ident_start)
                        && braced[..end].chars().all(is_ident_continue) =>
                {
                    (&braced[..end], end + 2)
                }
                _ => ("", 0),
            }
        } else if after.starts_with(is_ident_start) {
            let end = after
                .find(|c: char| !is_ident_continue(c))
                .unwrap_or(after.len());
            (&after[..end], end)
        } else {
            ("", 0)
        };
        match lookup(name) {
            Some(value) if consumed > 0 => {
                out.push_str(value);
                rest = &after[consumed..];
            }
            _ => {
                out.push('$');
                rest = after;
            }
        }
    }
    out.push_str(rest);
    out
}

// =============================================================================
// Replace strings
// =============================================================================

/// Parameters of a `replace_string` transformation.
pub(super) struct StringReplace<'a> {
    pub(super) replacement: &'a str,
    pub(super) skip_special: bool,
    pub(super) interpret_special: bool,
}

pub(super) fn replace_strings_in_rule(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    re: &Regex,
    replace: &StringReplace<'_>,
) {
    for detection in rule.detection.named.values_mut() {
        replace_strings_in_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            re,
            replace,
        );
    }
}

fn replace_strings_in_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    re: &Regex,
    replace: &StringReplace<'_>,
) {
    match detection {
        Detection::AllOf(items) => {
            for item in items.iter_mut() {
                if item_conditions_match(item, state, detection_conditions, field_name_conditions) {
                    replace_strings_in_values(&mut item.values, re, replace);
                }
            }
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                replace_strings_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    re,
                    replace,
                );
            }
        }
        Detection::ArrayMatch { body, .. } => {
            replace_strings_in_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                re,
                replace,
            );
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                replace_strings_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    re,
                    replace,
                );
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                replace_strings_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    re,
                    replace,
                );
            }
        }
        Detection::Keywords(values) => {
            replace_strings_in_values(values, re, replace);
        }
    }
}

fn replace_strings_in_values(values: &mut [SigmaValue], re: &Regex, replace: &StringReplace<'_>) {
    for value in values.iter_mut() {
        if let SigmaValue::String(s) = value {
            if replace.skip_special {
                // Replace only in plain segments, preserving wildcards. With
                // `interpret_special`, wildcards produced by the replacement
                // become wildcards; otherwise they stay literal characters.
                let new_parts: Vec<StringPart> = s
                    .parts
                    .iter()
                    .flat_map(|part| match part {
                        StringPart::Plain(text) => {
                            let replaced = re.replace_all(text, replace.replacement);
                            if replace.interpret_special {
                                SigmaString::new(&replaced).parts
                            } else {
                                vec![StringPart::Plain(replaced.into_owned())]
                            }
                        }
                        special => vec![special.clone()],
                    })
                    .collect();
                let new_parts = merge_plain_parts(new_parts);
                if new_parts != s.parts {
                    let new_original = parts_to_original(&new_parts);
                    s.parts = new_parts;
                    s.original = new_original;
                }
            } else {
                let replaced = re.replace_all(&s.original, replace.replacement);
                if replaced != s.original {
                    *s = SigmaString::new(&replaced);
                }
            }
        }
    }
}

/// Join adjacent plain parts so a rebuilt string has the canonical shape.
fn merge_plain_parts(parts: Vec<StringPart>) -> Vec<StringPart> {
    let mut merged: Vec<StringPart> = Vec::with_capacity(parts.len());
    for part in parts {
        match (merged.last_mut(), part) {
            (Some(StringPart::Plain(last)), StringPart::Plain(text)) => last.push_str(&text),
            (_, StringPart::Plain(text)) if text.is_empty() => {}
            (_, part) => merged.push(part),
        }
    }
    merged
}

/// Reconstruct the `original` string from parts, re-escaping wildcards.
fn parts_to_original(parts: &[StringPart]) -> String {
    let mut out = String::new();
    for part in parts {
        match part {
            StringPart::Plain(text) => {
                for c in text.chars() {
                    if c == '*' || c == '?' || c == '\\' {
                        out.push('\\');
                    }
                    out.push(c);
                }
            }
            StringPart::Special(SpecialChar::WildcardMulti) => out.push('*'),
            StringPart::Special(SpecialChar::WildcardSingle) => out.push('?'),
        }
    }
    out
}

// =============================================================================
// Placeholder expansion
// =============================================================================

/// How a placeholder transformation resolves `%name%` placeholders.
pub(super) struct PlaceholderExpansion<'a> {
    pub(super) state: &'a PipelineState,
    /// Replace every handled placeholder with `*` instead of its variable.
    pub(super) wildcard: bool,
    /// Leave placeholders without a variable for runtime substitution.
    pub(super) allow_unresolved: bool,
    pub(super) include: Option<&'a [String]>,
    pub(super) exclude: Option<&'a [String]>,
}

impl PlaceholderExpansion<'_> {
    fn handles(&self, name: &str) -> bool {
        self.include
            .is_none_or(|names| names.iter().any(|n| n == name))
            && self
                .exclude
                .is_none_or(|names| !names.iter().any(|n| n == name))
            && (self.wildcard || !self.allow_unresolved || self.state.vars.contains_key(name))
    }
}

pub(super) fn expand_placeholders_in_rule(
    rule: &mut SigmaRule,
    expansion: &PlaceholderExpansion<'_>,
) -> Result<()> {
    let rule_title = rule.title.clone();
    for detection in rule.detection.named.values_mut() {
        expand_placeholders_in_detection(detection, expansion, &rule_title)?;
    }
    Ok(())
}

fn expand_placeholders_in_detection(
    detection: &mut Detection,
    expansion: &PlaceholderExpansion<'_>,
    rule_title: &str,
) -> Result<()> {
    match detection {
        Detection::AllOf(items) => {
            for item in items.iter_mut() {
                if item.field.modifiers.contains(&Modifier::Expand) {
                    expand_placeholders_in_values(&mut item.values, expansion, rule_title)?;
                }
            }
        }
        Detection::AnyOf(subs) | Detection::And(subs) => {
            for sub in subs.iter_mut() {
                expand_placeholders_in_detection(sub, expansion, rule_title)?;
            }
        }
        Detection::ArrayMatch { body, .. } => {
            expand_placeholders_in_detection(body.as_mut(), expansion, rule_title)?;
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                expand_placeholders_in_detection(sub, expansion, rule_title)?;
            }
        }
        Detection::Keywords(_) => {}
    }
    Ok(())
}

fn expand_placeholders_in_values(
    values: &mut Vec<SigmaValue>,
    expansion: &PlaceholderExpansion<'_>,
    rule_title: &str,
) -> Result<()> {
    let mut expanded_values = Vec::new();
    for value in values.drain(..) {
        if let SigmaValue::String(ref s) = value
            && s.original.contains('%')
        {
            expanded_values.extend(expand_placeholder_string(
                &s.original,
                expansion,
                rule_title,
            )?);
            continue;
        }
        expanded_values.push(value);
    }
    *values = expanded_values;
    Ok(())
}

/// A piece of raw Sigma source text: literal text or a `%name%` placeholder.
enum Segment<'a> {
    Literal(&'a str),
    Placeholder(&'a str),
}

/// Split raw Sigma source text into literal text and placeholders.
///
/// A backslash escapes `*`, `?`, `%`, and itself, as in the `expand` modifier:
/// `\%` is a literal percent and `\\%name%` is a backslash followed by a
/// placeholder. A placeholder name is non-empty and has no `*`, `?`, or
/// backslash.
fn placeholder_segments(s: &str) -> Vec<Segment<'_>> {
    let mut segments = Vec::new();
    let mut literal_start = 0;
    let mut chars = s.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        match c {
            '\\' if chars
                .peek()
                .is_some_and(|&(_, next)| matches!(next, '*' | '?' | '%' | '\\')) =>
            {
                chars.next();
            }
            '%' => {
                let rest = &s[i + 1..];
                if let Some(len) = rest.find(['%', '*', '?', '\\'])
                    && len > 0
                    && rest[len..].starts_with('%')
                {
                    if literal_start < i {
                        segments.push(Segment::Literal(&s[literal_start..i]));
                    }
                    segments.push(Segment::Placeholder(&rest[..len]));
                    literal_start = i + len + 2;
                    while chars.peek().is_some_and(|&(j, _)| j < literal_start) {
                        chars.next();
                    }
                }
            }
            _ => {}
        }
    }
    if literal_start < s.len() {
        segments.push(Segment::Literal(&s[literal_start..]));
    }
    segments
}

/// Escape every `%` in literal Sigma source text that is not already escaped,
/// so the `expand` modifier never reads it as a placeholder.
fn escape_bare_percent(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                out.push('\\');
                if let Some(&next) = chars.peek()
                    && matches!(next, '*' | '?' | '%' | '\\')
                {
                    out.push(next);
                    chars.next();
                }
            }
            '%' => out.push_str("\\%"),
            _ => out.push(c),
        }
    }
    out
}

const MAX_PLACEHOLDER_COMBINATIONS: usize = 4096;

/// Substitute the placeholders in the raw source text `s` that `expansion`
/// handles, producing the Cartesian product of multi-value variables.
///
/// Substituted text is never scanned for further placeholders, and literal
/// text keeps its escapes: every `%` that is not part of a placeholder, in the
/// literal text or in a variable value, is written as `\%`.
fn expand_placeholder_string(
    s: &str,
    expansion: &PlaceholderExpansion<'_>,
    rule_title: &str,
) -> Result<Vec<SigmaValue>> {
    let segments = placeholder_segments(s);

    let mut combinations = vec![String::new()];
    for segment in &segments {
        let replacements: Vec<String> = match segment {
            Segment::Literal(text) => {
                let text = escape_bare_percent(text);
                for combination in &mut combinations {
                    combination.push_str(&text);
                }
                continue;
            }
            Segment::Placeholder(name) if !expansion.handles(name) => {
                for combination in &mut combinations {
                    combination.push('%');
                    combination.push_str(name);
                    combination.push('%');
                }
                continue;
            }
            Segment::Placeholder(_) if expansion.wildcard => vec!["*".to_string()],
            Segment::Placeholder(name) => match expansion.state.vars.get(*name) {
                Some(values) => values.iter().map(|v| v.replace('%', "\\%")).collect(),
                None => {
                    return Err(EvalError::InvalidModifiers(format!(
                        "placeholder replacement variable '{name}' is not defined \
                         (rule: {rule_title})"
                    )));
                }
            },
        };

        let total = combinations.len().saturating_mul(replacements.len());
        if total > MAX_PLACEHOLDER_COMBINATIONS {
            return Err(EvalError::InvalidModifiers(format!(
                "placeholder expansion would produce {total} values, exceeding the limit of \
                 {MAX_PLACEHOLDER_COMBINATIONS} (rule: {rule_title})"
            )));
        }
        combinations = combinations
            .iter()
            .flat_map(|prefix| {
                replacements
                    .iter()
                    .map(move |replacement| format!("{prefix}{replacement}"))
            })
            .collect();
    }

    Ok(combinations
        .into_iter()
        .map(|value| SigmaValue::String(SigmaString::new(&value)))
        .collect())
}

// =============================================================================
// Named string function helper (for FieldNameTransform)
// =============================================================================

pub(in crate::pipeline) fn apply_named_string_fn(func: &str, s: &str) -> String {
    match func {
        "lower" | "lowercase" => s.to_lowercase(),
        "upper" | "uppercase" => s.to_uppercase(),
        "title" => s
            .split(|c: char| !c.is_alphanumeric())
            .filter(|w| !w.is_empty())
            .map(|w| {
                let mut c = w.chars();
                match c.next() {
                    None => String::new(),
                    Some(f) => f.to_uppercase().collect::<String>() + &c.as_str().to_lowercase(),
                }
            })
            .collect::<Vec<_>>()
            .join("_"),
        "snake_case" => {
            let mut out = String::new();
            for (i, ch) in s.chars().enumerate() {
                if ch.is_uppercase() && i > 0 {
                    out.push('_');
                }
                out.push(ch.to_lowercase().next().unwrap_or(ch));
            }
            out
        }
        _ => s.to_string(),
    }
}

// =============================================================================
// Hashes field decomposition
// =============================================================================

/// Parameters of a `hashes_fields` transformation.
pub(super) struct HashesFields<'a> {
    pub(super) valid_hash_algos: &'a [String],
    pub(super) field_prefix: &'a str,
    pub(super) drop_algo_prefix: bool,
    pub(super) field_to_parse: &'a [String],
}

/// Replace each detection item on a `field_to_parse` field whose values are
/// all strings with an OR over per-algorithm fields, as pySigma's
/// `HashesFieldsDetectionItemTransformation` does. A value is `ALGO=hash`,
/// `ALGO|hash`, or a bare hash whose algorithm is inferred from its length.
pub(super) fn decompose_hashes_field(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    hashes: &HashesFields<'_>,
) -> Result<()> {
    let rule_title = rule.title.clone();
    for detection in rule.detection.named.values_mut() {
        decompose_hashes_in_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            hashes,
            &rule_title,
        )?;
    }
    Ok(())
}

fn decompose_hashes_in_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    hashes: &HashesFields<'_>,
    rule_title: &str,
) -> Result<()> {
    match detection {
        Detection::AllOf(items) => {
            let mut kept = Vec::with_capacity(items.len());
            let mut groups = Vec::new();
            for item in items.drain(..) {
                let parses = item
                    .field
                    .name
                    .as_ref()
                    .is_some_and(|name| hashes.field_to_parse.contains(name))
                    && item
                        .values
                        .iter()
                        .all(|v| matches!(v, SigmaValue::String(_)))
                    && !item.field.modifiers.contains(&Modifier::FieldRef)
                    && item_conditions_match(
                        &item,
                        state,
                        detection_conditions,
                        field_name_conditions,
                    );
                if parses {
                    groups.push(hash_value_group(&item, hashes, rule_title)?);
                } else {
                    kept.push(item);
                }
            }
            if groups.is_empty() {
                *items = kept;
            } else {
                let mut parts = Vec::with_capacity(groups.len() + 1);
                if !kept.is_empty() {
                    parts.push(Detection::AllOf(kept));
                }
                parts.extend(groups);
                *detection = match parts.len() {
                    1 => parts.pop().expect("one part"),
                    _ => Detection::And(parts),
                };
            }
        }
        Detection::AnyOf(subs) | Detection::And(subs) => {
            for sub in subs.iter_mut() {
                decompose_hashes_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    hashes,
                    rule_title,
                )?;
            }
        }
        Detection::ArrayMatch { body, .. } => {
            decompose_hashes_in_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                hashes,
                rule_title,
            )?;
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                decompose_hashes_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    hashes,
                    rule_title,
                )?;
            }
        }
        Detection::Keywords(_) => {}
    }
    Ok(())
}

/// The OR over per-algorithm fields that replaces one hashes detection item.
fn hash_value_group(
    item: &DetectionItem,
    hashes: &HashesFields<'_>,
    rule_title: &str,
) -> Result<Detection> {
    let mut by_field: Vec<(String, Vec<SigmaValue>)> = Vec::new();
    for value in &item.values {
        let SigmaValue::String(s) = value else {
            continue;
        };
        let plain = plain_text_with_wildcards(s);
        let parts: Vec<&str> = if plain.contains('|') {
            plain.split('|').collect()
        } else {
            plain.split('=').collect()
        };
        let (algo, hash) = if let [algo, hash] = parts.as_slice() {
            (
                algo.trim_start_matches('*').to_uppercase(),
                hash.trim_matches(['*', '?']),
            )
        } else {
            let hash = parts[0].trim_matches(['*', '?']);
            let algo = match hash.len() {
                32 => "MD5",
                40 => "SHA1",
                64 => "SHA256",
                128 => "SHA512",
                _ => "",
            };
            (algo.to_string(), hash)
        };
        if algo.is_empty() || !hashes.valid_hash_algos.contains(&algo) {
            continue;
        }
        let field = if hashes.drop_algo_prefix {
            hashes.field_prefix.to_string()
        } else {
            format!("{}{algo}", hashes.field_prefix)
        };
        if field.is_empty() {
            continue;
        }
        let hash = SigmaValue::String(SigmaString::new(hash));
        match by_field.iter_mut().find(|(name, _)| *name == field) {
            Some((_, values)) => values.push(hash),
            None => by_field.push((field, vec![hash])),
        }
    }
    if by_field.is_empty() {
        return Err(EvalError::InvalidModifiers(format!(
            "no valid hash algorithm found in field '{}'; use one of: {} (rule: {rule_title})",
            item.field.name.as_deref().unwrap_or_default(),
            hashes.valid_hash_algos.join(", ")
        )));
    }
    Ok(Detection::AnyOf(
        by_field
            .into_iter()
            .map(|(field, values)| {
                Detection::AllOf(vec![DetectionItem {
                    field: FieldSpec::new(Some(field), Vec::new()),
                    values,
                }])
            })
            .collect(),
    ))
}

/// The text of a Sigma string with wildcards written as `*` and `?`.
fn plain_text_with_wildcards(s: &SigmaString) -> String {
    s.parts
        .iter()
        .map(|part| match part {
            StringPart::Plain(text) => text.as_str(),
            StringPart::Special(SpecialChar::WildcardMulti) => "*",
            StringPart::Special(SpecialChar::WildcardSingle) => "?",
        })
        .collect()
}

// =============================================================================
// Map string values
// =============================================================================

pub(super) fn map_string_values(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    mapping: &HashMap<String, Vec<String>>,
) {
    for detection in rule.detection.named.values_mut() {
        map_strings_in_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            mapping,
        );
    }
}

fn map_strings_in_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    mapping: &HashMap<String, Vec<String>>,
) {
    match detection {
        Detection::AllOf(items) => {
            for item in items.iter_mut() {
                if item_conditions_match(item, state, detection_conditions, field_name_conditions) {
                    map_string_expand_values(&mut item.values, mapping);
                }
            }
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                map_strings_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    mapping,
                );
            }
        }
        Detection::ArrayMatch { body, .. } => {
            map_strings_in_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                mapping,
            );
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                map_strings_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    mapping,
                );
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                map_strings_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    mapping,
                );
            }
        }
        Detection::Keywords(values) => {
            map_string_expand_values(values, mapping);
        }
    }
}

/// Map string values with one-to-many support.
///
/// When a mapping entry has multiple replacements (e.g. `"foo": ["bar", "baz"]`),
/// the original value is replaced with the first alternative and additional
/// alternatives are appended to the values list. This expands the detection
/// item's value list, matching pySigma's `MapStringTransformation` behavior.
fn map_string_expand_values(values: &mut Vec<SigmaValue>, mapping: &HashMap<String, Vec<String>>) {
    let mut extra: Vec<(usize, Vec<SigmaValue>)> = Vec::new();

    for (i, val) in values.iter_mut().enumerate() {
        if let SigmaValue::String(s) = val {
            let plain = s.as_plain().unwrap_or_else(|| s.original.clone());
            if let Some(replacements) = mapping.get(&plain) {
                if let Some(first) = replacements.first() {
                    *s = SigmaString::new(first);
                }
                if replacements.len() > 1 {
                    let extras: Vec<SigmaValue> = replacements[1..]
                        .iter()
                        .map(|r| SigmaValue::String(SigmaString::new(r)))
                        .collect();
                    extra.push((i, extras));
                }
            }
        }
    }

    // Insert extra values in reverse order so indices remain valid
    for (idx, extras) in extra.into_iter().rev() {
        for (j, v) in extras.into_iter().enumerate() {
            values.insert(idx + 1 + j, v);
        }
    }
}

// =============================================================================
// Set value
// =============================================================================

pub(super) fn set_detection_item_values(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    value: &SigmaValue,
) {
    for detection in rule.detection.named.values_mut() {
        set_values_in_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            value,
        );
    }
}

fn set_values_in_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    value: &SigmaValue,
) {
    match detection {
        Detection::AllOf(items) => {
            for item in items.iter_mut() {
                if item_conditions_match(item, state, detection_conditions, field_name_conditions) {
                    item.values = vec![value.clone()];
                }
            }
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                set_values_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    value,
                );
            }
        }
        Detection::ArrayMatch { body, .. } => {
            set_values_in_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                value,
            );
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                set_values_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    value,
                );
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                set_values_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    value,
                );
            }
        }
        Detection::Keywords(_) => {}
    }
}

// =============================================================================
// Convert type
// =============================================================================

pub(super) fn convert_detection_item_types(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    target_type: &str,
) {
    for detection in rule.detection.named.values_mut() {
        convert_types_in_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            target_type,
        );
    }
}

fn convert_types_in_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    target_type: &str,
) {
    match detection {
        Detection::AllOf(items) => {
            for item in items.iter_mut() {
                if item_conditions_match(item, state, detection_conditions, field_name_conditions) {
                    for val in item.values.iter_mut() {
                        *val = convert_value(val, target_type);
                    }
                }
            }
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                convert_types_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    target_type,
                );
            }
        }
        Detection::ArrayMatch { body, .. } => {
            convert_types_in_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                target_type,
            );
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                convert_types_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    target_type,
                );
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                convert_types_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    target_type,
                );
            }
        }
        Detection::Keywords(_) => {}
    }
}

fn convert_value(val: &SigmaValue, target: &str) -> SigmaValue {
    match target {
        "str" | "string" => match val {
            SigmaValue::String(_) => val.clone(),
            SigmaValue::Integer(n) => SigmaValue::String(SigmaString::new(&n.to_string())),
            SigmaValue::Float(f) => SigmaValue::String(SigmaString::new(&f.to_string())),
            SigmaValue::Bool(b) => SigmaValue::String(SigmaString::new(&b.to_string())),
            SigmaValue::Null => SigmaValue::String(SigmaString::new("null")),
        },
        "int" | "integer" => match val {
            SigmaValue::String(s) => {
                let plain = s.as_plain().unwrap_or_else(|| s.original.clone());
                plain
                    .parse::<i64>()
                    .map(SigmaValue::Integer)
                    .unwrap_or_else(|_| val.clone())
            }
            SigmaValue::Float(f) => SigmaValue::Integer(*f as i64),
            SigmaValue::Bool(b) => SigmaValue::Integer(if *b { 1 } else { 0 }),
            _ => val.clone(),
        },
        "float" => match val {
            SigmaValue::String(s) => {
                let plain = s.as_plain().unwrap_or_else(|| s.original.clone());
                plain
                    .parse::<f64>()
                    .map(SigmaValue::Float)
                    .unwrap_or_else(|_| val.clone())
            }
            SigmaValue::Integer(n) => SigmaValue::Float(*n as f64),
            SigmaValue::Bool(b) => SigmaValue::Float(if *b { 1.0 } else { 0.0 }),
            _ => val.clone(),
        },
        "bool" | "boolean" => match val {
            SigmaValue::String(s) => {
                let plain = s.as_plain().unwrap_or_else(|| s.original.clone());
                match plain.to_lowercase().as_str() {
                    "true" | "1" | "yes" => SigmaValue::Bool(true),
                    "false" | "0" | "no" => SigmaValue::Bool(false),
                    _ => val.clone(),
                }
            }
            SigmaValue::Integer(n) => SigmaValue::Bool(*n != 0),
            SigmaValue::Float(f) => SigmaValue::Bool(*f != 0.0),
            _ => val.clone(),
        },
        _ => val.clone(),
    }
}

// =============================================================================
// Case transformation
// =============================================================================

pub(super) fn apply_case_transformation(
    rule: &mut SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    case_type: &str,
) {
    for detection in rule.detection.named.values_mut() {
        apply_case_in_detection(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
            case_type,
        );
    }
}

fn apply_case_in_detection(
    detection: &mut Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
    case_type: &str,
) {
    match detection {
        Detection::AllOf(items) => {
            for item in items.iter_mut() {
                if item_conditions_match(item, state, detection_conditions, field_name_conditions) {
                    for val in item.values.iter_mut() {
                        apply_case_to_value(val, case_type);
                    }
                }
            }
        }
        Detection::AnyOf(subs) => {
            for sub in subs.iter_mut() {
                apply_case_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    case_type,
                );
            }
        }
        Detection::ArrayMatch { body, .. } => {
            apply_case_in_detection(
                body.as_mut(),
                state,
                detection_conditions,
                field_name_conditions,
                case_type,
            );
        }
        Detection::And(subs) => {
            for sub in subs.iter_mut() {
                apply_case_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    case_type,
                );
            }
        }
        Detection::Conditional { named, .. } => {
            for sub in named.values_mut() {
                apply_case_in_detection(
                    sub,
                    state,
                    detection_conditions,
                    field_name_conditions,
                    case_type,
                );
            }
        }
        Detection::Keywords(values) => {
            for val in values.iter_mut() {
                apply_case_to_value(val, case_type);
            }
        }
    }
}

fn apply_case_to_value(val: &mut SigmaValue, case_type: &str) {
    if let SigmaValue::String(s) = val {
        let transformed = match case_type {
            "lower" | "lowercase" => s.original.to_lowercase(),
            "upper" | "uppercase" => s.original.to_uppercase(),
            "snake_case" => apply_named_string_fn("snake_case", &s.original),
            _ => return,
        };
        if transformed != s.original {
            *s = SigmaString::new(&transformed);
        }
    }
}

// =============================================================================
// Shared helper: check if a detection item matches both sets of conditions
// =============================================================================

/// pySigma's `match_detection_item`: the detection-item conditions and the
/// field-name conditions evaluated over the item's field name or any of its
/// field reference targets, each set's negation applied to that result.
fn item_conditions_match(
    item: &DetectionItem,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
) -> bool {
    detection_conditions_match(item, state, detection_conditions)
        && field_name_conditions
            .iter()
            .all(|set| set.matches(|condition| condition.matches_detection_item(item, state)))
}

// =============================================================================
// Helper: check if rule has any item matching conditions
// =============================================================================

pub(super) fn rule_has_matching_item(
    rule: &SigmaRule,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
) -> bool {
    rule.detection.named.values().any(|detection| {
        detection_has_matching_item(
            detection,
            state,
            detection_conditions,
            field_name_conditions,
        )
    })
}

fn detection_has_matching_item(
    detection: &Detection,
    state: &PipelineState,
    detection_conditions: &[&ConditionSet<DetectionItemCondition>],
    field_name_conditions: &[&ConditionSet<FieldNameCondition>],
) -> bool {
    let recurse = |sub: &Detection| {
        detection_has_matching_item(sub, state, detection_conditions, field_name_conditions)
    };
    match detection {
        Detection::AllOf(items) => items.iter().any(|item| {
            item_conditions_match(item, state, detection_conditions, field_name_conditions)
        }),
        Detection::AnyOf(subs) | Detection::And(subs) => subs.iter().any(recurse),
        Detection::ArrayMatch { body, .. } => recurse(body.as_ref()),
        Detection::Conditional { named, .. } => named.values().any(recurse),
        Detection::Keywords(_) => false,
    }
}

// =============================================================================
// Detection item change tracking
// =============================================================================

/// Record every detection item that the transformation item being applied
/// changed between `before` and `after`, for detection-item
/// `processing_item_applied` conditions. An item that kept its position takes
/// over the IDs of the item it replaced; an item with no counterpart (such as
/// a `hashes_fields` replacement) only carries the current ID. Detections the
/// transformation added are not tracked.
pub(in crate::pipeline) fn track_detection_item_changes(
    before: &HashMap<String, Detection>,
    after: &HashMap<String, Detection>,
    state: &mut PipelineState,
) {
    let mut changes = Vec::new();
    for (name, detection) in after {
        if let Some(previous) = before.get(name) {
            diff_detection(previous, detection, &mut changes);
        }
    }
    let id = state.current_item_id.clone();
    for (previous, current) in changes {
        state.track_detection_item_change(previous, current, id.as_deref());
    }
}

fn diff_detection<'a>(
    before: &'a Detection,
    after: &'a Detection,
    changes: &mut Vec<(Option<&'a DetectionItem>, &'a DetectionItem)>,
) {
    match (before, after) {
        (Detection::AllOf(old), Detection::AllOf(new)) if old.len() == new.len() => {
            diff_items(old, new, changes);
        }
        (Detection::AllOf(old), Detection::AnyOf(branches))
            if branches.iter().all(
                |branch| matches!(branch, Detection::AllOf(new) if new.len() == old.len()),
            ) =>
        {
            for branch in branches {
                if let Detection::AllOf(new) = branch {
                    diff_items(old, new, changes);
                }
            }
        }
        (Detection::AnyOf(old), Detection::AnyOf(new))
        | (Detection::And(old), Detection::And(new))
            if old.len() == new.len() =>
        {
            for (old, new) in old.iter().zip(new) {
                diff_detection(old, new, changes);
            }
        }
        (Detection::ArrayMatch { body: old, .. }, Detection::ArrayMatch { body: new, .. }) => {
            diff_detection(old, new, changes);
        }
        (Detection::Conditional { named: old, .. }, Detection::Conditional { named: new, .. }) => {
            for (name, new) in new {
                if let Some(old) = old.get(name) {
                    diff_detection(old, new, changes);
                }
            }
        }
        _ => {
            let mut old_items = Vec::new();
            collect_items(before, &mut old_items);
            let mut new_items = Vec::new();
            collect_items(after, &mut new_items);
            for item in new_items {
                if !old_items.contains(&item) {
                    changes.push((None, item));
                }
            }
        }
    }
}

fn diff_items<'a>(
    old: &'a [DetectionItem],
    new: &'a [DetectionItem],
    changes: &mut Vec<(Option<&'a DetectionItem>, &'a DetectionItem)>,
) {
    for (old, new) in old.iter().zip(new) {
        if old != new {
            changes.push((Some(old), new));
        }
    }
}

fn collect_items<'a>(detection: &'a Detection, items: &mut Vec<&'a DetectionItem>) {
    match detection {
        Detection::AllOf(all) => items.extend(all),
        Detection::AnyOf(subs) | Detection::And(subs) => {
            for sub in subs {
                collect_items(sub, items);
            }
        }
        Detection::ArrayMatch { body, .. } => collect_items(body, items),
        Detection::Conditional { named, .. } => {
            for sub in named.values() {
                collect_items(sub, items);
            }
        }
        Detection::Keywords(_) => {}
    }
}