automapper-validation 0.1.57

AHB condition expression parsing, evaluation, and EDIFACT validation
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
//! Merged AHB + EDIFACT tree for validation.
//!
//! [`build_validated_tree`] joins an [`AhbWorkflow`] (what should be there)
//! with an [`AssembledTree`] (what is there) into a single [`ValidatedTree`]
//! where each node carries both the AHB rule and the resolved EDIFACT value.

use std::collections::HashMap;

use crate::expr::ConditionExpr;

use super::validate::{AhbFieldRule, AhbWorkflow};
use mig_assembly::assembler::{
    AssembledGroup, AssembledGroupInstance, AssembledSegment, AssembledTree,
};

/// A single AHB field matched against EDIFACT data.
#[derive(Debug)]
pub struct AhbNode<'a> {
    /// The AHB field rule (segment path, ahb_status, codes, etc.)
    pub rule: &'a AhbFieldRule,
    /// The actual value found in the EDIFACT at this position. `None` if absent.
    pub value: Option<&'a str>,
    /// The full segment elements for cross-element access. `None` if segment absent.
    pub segment_elements: Option<&'a [Vec<String>]>,
}

/// A segment group instance matched against EDIFACT data.
#[derive(Debug)]
pub struct AhbGroupNode<'a> {
    /// Group ID (e.g., "SG4", "SG8").
    pub group_id: &'a str,
    /// AHB status of this group.
    pub ahb_status: Option<&'a str>,
    /// Fields in this group instance, resolved against EDIFACT segments.
    pub fields: Vec<AhbNode<'a>>,
    /// Child group instances.
    pub children: Vec<AhbGroupNode<'a>>,
}

/// AHB workflow merged with assembled EDIFACT data.
#[derive(Debug)]
pub struct ValidatedTree<'a> {
    /// The Pruefidentifikator.
    pub pruefidentifikator: &'a str,
    /// UB definitions for condition expansion.
    pub ub_definitions: &'a HashMap<String, ConditionExpr>,
    /// Root-level fields (outside segment groups).
    pub root_fields: Vec<AhbNode<'a>>,
    /// Top-level group instances.
    pub groups: Vec<AhbGroupNode<'a>>,
    /// Rules whose `mig_number` did not match any assembled group instance.
    ///
    /// These represent entirely-absent group variants (e.g., NAD+MS when only
    /// NAD+MR is present). `validate_tree` evaluates these using the flat
    /// `is_field_present`/`is_group_variant_absent` logic to correctly
    /// distinguish mandatory-but-missing variants from optional-and-absent ones.
    pub unmatched_rules: Vec<&'a AhbFieldRule>,
}

/// Build a [`ValidatedTree`] by merging an AHB workflow with an assembled EDIFACT tree.
///
/// The join key is `mig_number`: both [`AhbFieldRule::mig_number`] and
/// [`AssembledSegment::mig_number`] carry the MIG `Number` attribute that
/// uniquely identifies a segment variant.
pub fn build_validated_tree<'a>(
    workflow: &'a AhbWorkflow,
    tree: &'a AssembledTree,
) -> ValidatedTree<'a> {
    // Partition AHB rules into root-level and per-group buckets.
    let mut root_rules: Vec<&'a AhbFieldRule> = Vec::new();
    // Map from top-level group prefix (e.g., "SG2", "SG4") to rules.
    let mut group_rules: HashMap<String, Vec<&'a AhbFieldRule>> = HashMap::new();

    for rule in &workflow.fields {
        match extract_top_group(&rule.segment_path) {
            Some(group_id) => {
                group_rules
                    .entry(group_id.to_owned())
                    .or_default()
                    .push(rule);
            }
            None => {
                root_rules.push(rule);
            }
        }
    }

    // Resolve root-level fields against root segments.
    let root_fields = resolve_fields(&root_rules, &tree.segments);

    // Resolve groups recursively (depth 0 = top-level groups).
    let groups = resolve_groups(&tree.groups, &group_rules, 0);

    // Find rules whose mig_number wasn't matched to any tree node.
    // Collect all mig_numbers that appear in the assembled tree.
    let mut matched_mig_numbers: std::collections::HashSet<&str> = std::collections::HashSet::new();
    collect_matched_mig_numbers_from_groups(&groups, &mut matched_mig_numbers);
    // Also include root segment mig_numbers.
    for seg in &tree.segments {
        if let Some(ref num) = seg.mig_number {
            matched_mig_numbers.insert(num.as_str());
        }
    }

    let unmatched_rules: Vec<&AhbFieldRule> = workflow
        .fields
        .iter()
        .filter(|rule| {
            rule.mig_number
                .as_ref()
                .is_some_and(|num| !matched_mig_numbers.contains(num.as_str()))
        })
        .collect();

    ValidatedTree {
        pruefidentifikator: &workflow.pruefidentifikator,
        ub_definitions: &workflow.ub_definitions,
        root_fields,
        groups,
        unmatched_rules,
    }
}

/// Collect all mig_numbers from rules that were accepted into the tree.
///
/// Any rule in the tree — even with `value: None` — was accepted by the
/// variant filter and is therefore "claimed". Rules NOT in this set are
/// genuinely unmatched (their variant is entirely absent).
fn collect_matched_mig_numbers_from_groups<'a>(
    groups: &[AhbGroupNode<'a>],
    out: &mut std::collections::HashSet<&'a str>,
) {
    for group in groups {
        for node in &group.fields {
            if let Some(ref num) = node.rule.mig_number {
                out.insert(num.as_str());
            }
        }
        collect_matched_mig_numbers_from_groups(&group.children, out);
    }
}

/// Extract the top-level segment group from a segment path.
///
/// `"SG4/DTM/C507/2380"` -> `Some("SG4")`
/// `"SG4/SG5/LOC/3225"` -> `Some("SG4")`
/// `"BGM/1004"` -> `None`
fn extract_top_group(segment_path: &str) -> Option<&str> {
    let first = segment_path.split('/').next()?;
    if first.starts_with("SG") {
        Some(first)
    } else {
        None
    }
}

/// Extract the child group prefix from a path that already had parent groups stripped.
///
/// `"SG5/LOC/3225"` -> `Some("SG5")`
/// `"DTM/C507/2380"` -> `None`
fn extract_child_group(stripped_path: &str) -> Option<&str> {
    let first = stripped_path.split('/').next()?;
    if first.starts_with("SG") {
        Some(first)
    } else {
        None
    }
}

/// Resolve AHB fields against a list of assembled segments.
///
/// For each rule, tries to find a matching segment by `mig_number` first,
/// then falls back to segment tag matching. Rules that don't match any
/// segment get `value: None` — condition evaluation decides if that's an error.
fn resolve_fields<'a>(
    rules: &[&'a AhbFieldRule],
    segments: &'a [AssembledSegment],
) -> Vec<AhbNode<'a>> {
    rules
        .iter()
        .map(|rule| {
            let matched_segment = find_segment(rule, segments);
            let (value, elements) = match matched_segment {
                Some(seg) => {
                    let val = extract_value(seg, rule);
                    (val, Some(seg.elements.as_slice()))
                }
                None => (None, None),
            };
            AhbNode {
                rule,
                value,
                segment_elements: elements,
            }
        })
        .collect()
}

/// Find the assembled segment matching an AHB field rule.
///
/// Matching strategy when the rule has a `mig_number`:
/// 1. **Strict match**: find a segment with the exact `mig_number`.
/// 2. **Tag fallback**: if no segment has that `mig_number`, fall back to tag
///    matching — but ONLY against segments that don't have a *different*
///    `mig_number` assigned. This prevents cross-matching between same-tag
///    segments with known identities (e.g., DTM+92 rules must not match a
///    DTM+93 segment that has `mig_number` "00024").
/// 3. Segments with `mig_number: None` (unattributed) are eligible for the
///    tag fallback, preserving backward compatibility with greedy assembly.
fn find_segment<'a>(
    rule: &AhbFieldRule,
    segments: &'a [AssembledSegment],
) -> Option<&'a AssembledSegment> {
    let tag = extract_segment_tag(&rule.segment_path)?;

    // Qualifier-aware match: when the rule's codes identify a segment
    // variant (e.g. `STS/C601/9015` with codes=[Z32]), pick the segment
    // whose value at the rule's position matches one of those codes.
    // This overrides any mig_number that the assembler may have
    // mis-assigned positionally to same-tag variants sharing a single
    // group instance (e.g. MSCONS SG10 carries STS+Z32 *and* STS+Z40,
    // and the assembler tags them by MIG slot order, not by qualifier).
    //
    // When *no* segment in the instance carries a matching qualifier,
    // the outcome depends on how many same-tag segments are in view:
    //   * 2+ same-tag segments → real contention between variants; the
    //     rule's variant is genuinely absent from this instance, so
    //     return None and let condition evaluation decide if that's an
    //     error.
    //   * 0–1 same-tag segment → no contention. Fall through to the
    //     mig_number / tag match below to preserve behavior for merged
    //     entry slots where multiple variants share one mig_number
    //     (MSCONS SG2 collapses NAD+MS and NAD+MR onto mig=00013).
    if !rule.codes.is_empty() {
        let el_idx = rule.element_index.unwrap_or(0);
        let comp_idx = rule.component_index.unwrap_or(0);
        let expected: std::collections::HashSet<&str> =
            rule.codes.iter().map(|c| c.value.as_str()).collect();
        if let Some(seg) = segments.iter().find(|s| {
            s.tag == tag
                && s.elements
                    .get(el_idx)
                    .and_then(|e| e.get(comp_idx))
                    .is_some_and(|v| expected.contains(v.as_str()))
        }) {
            return Some(seg);
        }
        let same_tag_count = segments.iter().filter(|s| s.tag == tag).count();
        if same_tag_count > 1 {
            return None;
        }
    }

    if let Some(ref mig_num) = rule.mig_number {
        // 1. Strict mig_number match.
        if let Some(seg) = segments
            .iter()
            .find(|s| s.mig_number.as_deref() == Some(mig_num.as_str()))
        {
            return Some(seg);
        }

        // 2. Tag fallback, excluding segments with a conflicting mig_number.
        return segments
            .iter()
            .find(|s| s.tag == tag && s.mig_number.as_ref().map_or(true, |m| m == mig_num));
    }

    // No mig_number on rule — pure tag match.
    segments.iter().find(|s| s.tag == tag)
}

/// Extract the segment tag from a segment path.
///
/// `"SG4/DTM/C507/2380"` -> `"DTM"` (first non-SG component)
/// `"BGM/1004"` -> `"BGM"`
fn extract_segment_tag(segment_path: &str) -> Option<&str> {
    segment_path.split('/').find(|part| !part.starts_with("SG"))
}

/// Extract a field value from an assembled segment using element/component indices.
fn extract_value<'a>(segment: &'a AssembledSegment, rule: &AhbFieldRule) -> Option<&'a str> {
    let elem_idx = rule.element_index.unwrap_or(0);
    let comp_idx = rule.component_index.unwrap_or(0);

    let element = segment.elements.get(elem_idx)?;
    let component = element.get(comp_idx)?;

    if component.is_empty() {
        None
    } else {
        Some(component.as_str())
    }
}

/// Resolve assembled groups against grouped AHB rules, recursively.
///
/// `depth` is the number of group prefixes to strip from each rule's
/// `segment_path` before classifying it as direct or child.
fn resolve_groups<'a>(
    assembled_groups: &'a [AssembledGroup],
    group_rules: &HashMap<String, Vec<&'a AhbFieldRule>>,
    depth: usize,
) -> Vec<AhbGroupNode<'a>> {
    let mut result = Vec::new();

    for assembled_group in assembled_groups {
        let rules = group_rules.get(&assembled_group.group_id);

        for instance in &assembled_group.repetitions {
            let node = resolve_group_instance(&assembled_group.group_id, instance, rules, depth);
            result.push(node);
        }
    }

    result
}

/// Strip `n` leading group prefixes from a segment path.
///
/// `strip_n_groups("SG4/SG5/LOC/3225", 2)` -> `"LOC/3225"`
fn strip_n_groups(path: &str, n: usize) -> &str {
    let mut rest = path;
    for _ in 0..n {
        match rest.find('/') {
            Some(idx) => rest = &rest[idx + 1..],
            None => return rest,
        }
    }
    rest
}

/// Resolve a single group instance.
///
/// `depth` is how many group prefixes have been consumed so far (0 for top-level groups).
///
/// Rules are filtered to this instance by `mig_number`: a rule only applies if
/// its `mig_number` matches a segment in this instance (or a segment in a child
/// group instance). This prevents rules for SG8/SEQ+Z79 from generating false
/// missing-field errors against an SG8/SEQ+Z01 rep.
fn resolve_group_instance<'a>(
    group_id: &'a str,
    instance: &'a AssembledGroupInstance,
    rules: Option<&Vec<&'a AhbFieldRule>>,
    depth: usize,
) -> AhbGroupNode<'a> {
    // We need to strip (depth + 1) group prefixes to get below this group level.
    let strip_count = depth + 1;

    // Use the variant's full set of mig_numbers (from MIG definition) to
    // determine which rules belong to this instance. This includes numbers
    // for segments that may be absent — so missing-field detection still works.
    // Falls back to collecting from present segments if variant_mig_numbers is empty.
    let variant_numbers: std::collections::HashSet<&str> =
        if !instance.variant_mig_numbers.is_empty() {
            instance
                .variant_mig_numbers
                .iter()
                .map(|s| s.as_str())
                .collect()
        } else {
            collect_instance_mig_numbers(instance)
        };

    let mut direct_rules: Vec<&'a AhbFieldRule> = Vec::new();
    let mut child_group_rules: HashMap<String, Vec<&'a AhbFieldRule>> = HashMap::new();
    let mut ahb_status: Option<&'a str> = None;

    if let Some(rules) = rules {
        for rule in rules {
            // Skip rules whose mig_number doesn't belong to this variant.
            // Rules without mig_number pass through (tag-based fallback).
            if let Some(ref rule_mig) = rule.mig_number {
                if !variant_numbers.contains(rule_mig.as_str()) {
                    continue;
                }
            }

            // Strip all parent group prefixes plus this group to get the relative path.
            let stripped = strip_n_groups(&rule.segment_path, strip_count);

            if let Some(child_group_id) = extract_child_group(stripped) {
                child_group_rules
                    .entry(child_group_id.to_owned())
                    .or_default()
                    .push(rule);
            } else {
                direct_rules.push(rule);
            }

            // Capture the parent group AHB status if present.
            if ahb_status.is_none() {
                if let Some(ref status) = rule.parent_group_ahb_status {
                    ahb_status = Some(status.as_str());
                }
            }
        }
    }

    // Resolve direct fields against instance segments.
    let fields = resolve_fields(&direct_rules, &instance.segments);

    // Recurse into child groups one level deeper.
    let children = resolve_groups(&instance.child_groups, &child_group_rules, strip_count);

    AhbGroupNode {
        group_id,
        ahb_status,
        fields,
        children,
    }
}

/// Collect all mig_numbers present in a group instance, including child groups recursively.
fn collect_instance_mig_numbers(
    instance: &AssembledGroupInstance,
) -> std::collections::HashSet<&str> {
    let mut numbers = std::collections::HashSet::new();
    for seg in &instance.segments {
        if let Some(ref num) = seg.mig_number {
            numbers.insert(num.as_str());
        }
    }
    for child_group in &instance.child_groups {
        for child_instance in &child_group.repetitions {
            numbers.extend(collect_instance_mig_numbers(child_instance));
        }
    }
    numbers
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validator::validate::{AhbFieldRule, AhbWorkflow};
    use mig_assembly::assembler::{
        AssembledGroup, AssembledGroupInstance, AssembledSegment, AssembledTree,
    };
    use std::collections::{BTreeMap, HashMap};

    fn empty_workflow() -> AhbWorkflow {
        AhbWorkflow {
            pruefidentifikator: "11001".to_string(),
            description: String::new(),
            communication_direction: None,
            fields: vec![],
            ub_definitions: HashMap::new(),
        }
    }

    fn empty_tree() -> AssembledTree {
        AssembledTree {
            segments: vec![],
            groups: vec![],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        }
    }

    fn make_segment(
        tag: &str,
        elements: Vec<Vec<&str>>,
        mig_number: Option<&str>,
    ) -> AssembledSegment {
        AssembledSegment {
            tag: tag.to_string(),
            elements: elements
                .into_iter()
                .map(|e| e.into_iter().map(|s| s.to_string()).collect())
                .collect(),
            mig_number: mig_number.map(|s| s.to_string()),
        }
    }

    fn make_rule(
        segment_path: &str,
        name: &str,
        ahb_status: &str,
        mig_number: Option<&str>,
        element_index: Option<usize>,
        component_index: Option<usize>,
    ) -> AhbFieldRule {
        AhbFieldRule {
            segment_path: segment_path.to_string(),
            name: name.to_string(),
            ahb_status: ahb_status.to_string(),
            codes: vec![],
            parent_group_ahb_status: None,
            segment_ahb_status: None,
            element_index,
            component_index,
            mig_number: mig_number.map(|s| s.to_string()),
        }
    }

    #[test]
    fn test_empty_workflow_empty_tree() {
        let workflow = empty_workflow();
        let tree = empty_tree();
        let result = build_validated_tree(&workflow, &tree);

        assert_eq!(result.pruefidentifikator, "11001");
        assert!(result.root_fields.is_empty());
        assert!(result.groups.is_empty());
    }

    #[test]
    fn test_root_field_matches_root_segment() {
        let mut workflow = empty_workflow();
        workflow.fields.push(make_rule(
            "BGM/C002/1001",
            "Nachrichtentyp",
            "X",
            Some("0001"),
            Some(0),
            Some(0),
        ));

        let tree = AssembledTree {
            segments: vec![make_segment("BGM", vec![vec!["E01"]], Some("0001"))],
            groups: vec![],
            post_group_start: 1,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);

        assert_eq!(result.root_fields.len(), 1);
        let node = &result.root_fields[0];
        assert_eq!(node.value, Some("E01"));
        assert!(node.segment_elements.is_some());
        assert_eq!(node.rule.name, "Nachrichtentyp");
    }

    #[test]
    fn test_sg4_dtm_mig_number_matching() {
        // Two DTM segments with different mig_numbers.
        // AHB rule for DTM+92 (mig_number "0082") should match the correct one.
        let mut workflow = empty_workflow();

        // Rule for DTM+92: element 0 = qualifier "92", element 1 = the date value.
        workflow.fields.push(make_rule(
            "SG4/DTM/C507/2380",
            "Eingangsdatum",
            "X",
            Some("0082"),
            Some(1), // date value is element 1
            Some(0),
        ));

        // Rule for DTM+137.
        workflow.fields.push(make_rule(
            "SG4/DTM/C507/2380",
            "Dokumentendatum",
            "X",
            Some("0083"),
            Some(1),
            Some(0),
        ));

        let tree = AssembledTree {
            segments: vec![],
            groups: vec![AssembledGroup {
                group_id: "SG4".to_string(),
                repetitions: vec![AssembledGroupInstance {
                    segments: vec![
                        make_segment("DTM", vec![vec!["92"], vec!["20260101"]], Some("0082")),
                        make_segment("DTM", vec![vec!["137"], vec!["20260401"]], Some("0083")),
                    ],
                    child_groups: vec![],
                    entry_mig_number: None,
                    variant_mig_numbers: vec![],
                    skipped_segments: vec![],
                    skipped_positions: Vec::new(),
                }],
            }],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);

        assert_eq!(result.groups.len(), 1);
        let sg4 = &result.groups[0];
        assert_eq!(sg4.group_id, "SG4");
        assert_eq!(sg4.fields.len(), 2);

        // Eingangsdatum (mig_number 0082) should get DTM+92's date.
        let eingangsdatum = &sg4.fields[0];
        assert_eq!(eingangsdatum.rule.name, "Eingangsdatum");
        assert_eq!(eingangsdatum.value, Some("20260101"));

        // Dokumentendatum (mig_number 0083) should get DTM+137's date.
        let dokumentendatum = &sg4.fields[1];
        assert_eq!(dokumentendatum.rule.name, "Dokumentendatum");
        assert_eq!(dokumentendatum.value, Some("20260401"));
    }

    #[test]
    fn test_rule_filtered_to_correct_variant() {
        // A rule with mig_number "0099" is filtered out from an instance
        // that doesn't contain any segment with that mig_number.
        // This prevents false missing-field errors for wrong SG8 variants.
        let mut workflow = empty_workflow();
        workflow.fields.push(make_rule(
            "SG4/RFF/C506/1154",
            "Referenz",
            "X",
            Some("0099"),
            Some(0),
            Some(1),
        ));

        let tree = AssembledTree {
            segments: vec![],
            groups: vec![AssembledGroup {
                group_id: "SG4".to_string(),
                repetitions: vec![AssembledGroupInstance {
                    segments: vec![], // No segments — wrong variant
                    child_groups: vec![],
                    entry_mig_number: None,
                    variant_mig_numbers: vec![],
                    skipped_segments: vec![],
                    skipped_positions: Vec::new(),
                }],
            }],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);
        assert_eq!(result.groups.len(), 1);
        // Rule is filtered out — its mig_number doesn't match this instance
        assert_eq!(result.groups[0].fields.len(), 0);
    }

    #[test]
    fn test_missing_segment_within_correct_variant() {
        // A rule with mig_number "0099" IS included when the instance's
        // variant_mig_numbers lists it — even though the segment is absent.
        // This enables missing-field detection within the correct variant.
        let mut workflow = empty_workflow();
        // Entry segment rule (present)
        workflow.fields.push(make_rule(
            "SG4/SEQ/1229",
            "Qualifier",
            "X",
            Some("0098"),
            Some(0),
            Some(0),
        ));
        // Second segment rule (absent — should report missing)
        workflow.fields.push(make_rule(
            "SG4/RFF/C506/1154",
            "Referenz",
            "X",
            Some("0099"),
            Some(0),
            Some(1),
        ));

        let tree = AssembledTree {
            segments: vec![],
            groups: vec![AssembledGroup {
                group_id: "SG4".to_string(),
                repetitions: vec![AssembledGroupInstance {
                    segments: vec![
                        // Only the entry segment — RFF is missing
                        make_segment("SEQ", vec![vec!["Z01"]], Some("0098")),
                    ],
                    child_groups: vec![],
                    entry_mig_number: Some("0098".to_string()),
                    // variant_mig_numbers includes both "0098" (SEQ) and "0099" (RFF)
                    variant_mig_numbers: vec!["0098".to_string(), "0099".to_string()],
                    skipped_segments: vec![],
                    skipped_positions: Vec::new(),
                }],
            }],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);
        assert_eq!(result.groups.len(), 1);
        // Both rules match because variant_mig_numbers includes both
        assert_eq!(result.groups[0].fields.len(), 2);
        assert_eq!(result.groups[0].fields[0].rule.name, "Qualifier");
        assert_eq!(result.groups[0].fields[0].value, Some("Z01"));
        // RFF is missing — value is None (condition eval will report it)
        assert_eq!(result.groups[0].fields[1].rule.name, "Referenz");
        assert_eq!(result.groups[0].fields[1].value, None);
    }

    #[test]
    fn test_missing_group_variant_populates_unmatched_rules() {
        // AHB requires two SG2 variants: NAD+MS (mig "0010") and NAD+MR (mig "0011").
        // EDIFACT only has NAD+MR. Rules for NAD+MS must appear in unmatched_rules
        // so validate_tree can report them as missing using flat logic.
        let mut workflow = empty_workflow();

        // NAD+MS qualifier rule
        workflow.fields.push(make_rule(
            "SG2/NAD/3035",
            "MP-ID Absender Qualifier",
            "X",
            Some("0010"),
            Some(0),
            Some(0),
        ));
        // NAD+MS ID rule
        workflow.fields.push(make_rule(
            "SG2/NAD/C082/3039",
            "MP-ID Absender",
            "X",
            Some("0010"),
            Some(1),
            Some(0),
        ));
        // NAD+MR qualifier rule
        workflow.fields.push(make_rule(
            "SG2/NAD/3035",
            "MP-ID Empfänger Qualifier",
            "X",
            Some("0011"),
            Some(0),
            Some(0),
        ));
        // NAD+MR ID rule
        workflow.fields.push(make_rule(
            "SG2/NAD/C082/3039",
            "MP-ID Empfänger",
            "X",
            Some("0011"),
            Some(1),
            Some(0),
        ));

        // Only NAD+MR present in assembled tree.
        let tree = AssembledTree {
            segments: vec![],
            groups: vec![AssembledGroup {
                group_id: "SG2".to_string(),
                repetitions: vec![AssembledGroupInstance {
                    segments: vec![make_segment(
                        "NAD",
                        vec![vec!["MR"], vec!["9900269000000", "", "293"]],
                        Some("0011"),
                    )],
                    child_groups: vec![],
                    entry_mig_number: Some("0011".to_string()),
                    variant_mig_numbers: vec!["0011".to_string()],
                    skipped_segments: vec![],
                    skipped_positions: Vec::new(),
                }],
            }],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);

        // Tree should have 1 SG2 group node (NAD+MR).
        assert_eq!(result.groups.len(), 1);
        assert_eq!(result.groups[0].fields.len(), 2);
        assert_eq!(result.groups[0].fields[0].value, Some("MR"));

        // NAD+MS rules should be in unmatched_rules.
        assert_eq!(
            result.unmatched_rules.len(),
            2,
            "Expected 2 unmatched rules (NAD+MS), got {}",
            result.unmatched_rules.len()
        );
        assert_eq!(result.unmatched_rules[0].name, "MP-ID Absender Qualifier");
        assert_eq!(result.unmatched_rules[1].name, "MP-ID Absender");
    }

    #[test]
    fn test_entirely_absent_group_populates_unmatched_rules() {
        // AHB requires SG2 with NAD+MS (mig "0010"), but no SG2 exists at all.
        let mut workflow = empty_workflow();
        workflow.fields.push(make_rule(
            "SG2/NAD/3035",
            "MP-ID Absender Qualifier",
            "X",
            Some("0010"),
            Some(0),
            Some(0),
        ));

        let tree = empty_tree(); // No groups at all.

        let result = build_validated_tree(&workflow, &tree);

        // No tree nodes.
        assert!(result.groups.is_empty());

        // The rule should be in unmatched_rules.
        assert_eq!(
            result.unmatched_rules.len(),
            1,
            "Expected 1 unmatched rule, got {}",
            result.unmatched_rules.len()
        );
        assert_eq!(result.unmatched_rules[0].name, "MP-ID Absender Qualifier");
    }

    #[test]
    fn test_fallback_to_tag_when_no_mig_number() {
        let mut workflow = empty_workflow();
        workflow.fields.push(make_rule(
            "BGM/C002/1001",
            "Nachrichtentyp",
            "X",
            None, // No mig_number — should fall back to tag.
            Some(0),
            Some(0),
        ));

        let tree = AssembledTree {
            segments: vec![make_segment("BGM", vec![vec!["E01"]], None)],
            groups: vec![],
            post_group_start: 1,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);
        assert_eq!(result.root_fields.len(), 1);
        assert_eq!(result.root_fields[0].value, Some("E01"));
    }

    #[test]
    fn test_nested_child_groups() {
        let mut workflow = empty_workflow();
        // A rule in SG4/SG5.
        workflow.fields.push(make_rule(
            "SG4/SG5/LOC/C517/3225",
            "Marktlokations-ID",
            "X",
            Some("0050"),
            Some(0),
            Some(0),
        ));

        let tree = AssembledTree {
            segments: vec![],
            groups: vec![AssembledGroup {
                group_id: "SG4".to_string(),
                repetitions: vec![AssembledGroupInstance {
                    segments: vec![],
                    entry_mig_number: None,
                    child_groups: vec![AssembledGroup {
                        group_id: "SG5".to_string(),
                        repetitions: vec![AssembledGroupInstance {
                            segments: vec![make_segment(
                                "LOC",
                                vec![vec!["DE00012345678"]],
                                Some("0050"),
                            )],
                            child_groups: vec![],
                            entry_mig_number: None,
                            variant_mig_numbers: vec![],
                            skipped_segments: vec![],
                            skipped_positions: Vec::new(),
                        }],
                    }],
                    variant_mig_numbers: vec![],
                    skipped_segments: vec![],
                    skipped_positions: Vec::new(),
                }],
            }],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);
        assert_eq!(result.groups.len(), 1);
        let sg4 = &result.groups[0];
        assert_eq!(sg4.children.len(), 1);

        let sg5 = &sg4.children[0];
        assert_eq!(sg5.group_id, "SG5");
        assert_eq!(sg5.fields.len(), 1);
        assert_eq!(sg5.fields[0].value, Some("DE00012345678"));
        assert_eq!(sg5.fields[0].rule.name, "Marktlokations-ID");
    }

    #[test]
    fn test_qualifier_aware_segment_matching_same_tag_variants() {
        // MSCONS SG10 has four STS variants (9015=Z33, Z32, Z34, Z40) with
        // mig_numbers 00035..00038. The assembler matches same-tag MIG slots
        // positionally, so when input contains STS+Z32++Z92 and STS+Z40++Z75,
        // the segments end up tagged with mig=00035 and mig=00036 (the first
        // two MIG slots) instead of mig=00036 and mig=00038.
        //
        // `find_segment` must therefore prefer a segment whose qualifier value
        // matches the rule's single-code constraint over the assembler's
        // positional mig_number. Otherwise:
        //   * rule for Z33 (mig 00035) attaches to the Z32 segment and looks
        //     "present" with the wrong value, suppressing the genuine absence;
        //   * rule for Z40 (mig 00038) finds no segment and reports the Z40
        //     STS as "missing" even though it is present in the input.
        let mut workflow = empty_workflow();

        // Z33 variant — not present in input, must resolve to None.
        let mut z33 = make_rule(
            "SG10/STS/C601/9015",
            "Statuskategorie Z33",
            "X",
            Some("00035"),
            Some(0),
            Some(0),
        );
        z33.codes = vec![super::super::validate::AhbCodeRule {
            value: "Z33".into(),
            description: String::new(),
            ahb_status: "X".into(),
        }];
        workflow.fields.push(z33);

        // Z32 variant — present in input.
        let mut z32 = make_rule(
            "SG10/STS/C601/9015",
            "Statuskategorie Z32",
            "X",
            Some("00036"),
            Some(0),
            Some(0),
        );
        z32.codes = vec![super::super::validate::AhbCodeRule {
            value: "Z32".into(),
            description: String::new(),
            ahb_status: "X".into(),
        }];
        workflow.fields.push(z32);

        // Z40 variant — present in input.
        let mut z40 = make_rule(
            "SG10/STS/C601/9015",
            "Statuskategorie Z40",
            "X",
            Some("00038"),
            Some(0),
            Some(0),
        );
        z40.codes = vec![super::super::validate::AhbCodeRule {
            value: "Z40".into(),
            description: String::new(),
            ahb_status: "X".into(),
        }];
        workflow.fields.push(z40);

        // Assembler assigned mig=00035 to the Z32 segment and mig=00036 to the Z40
        // segment (positional), mimicking the real MSCONS 13025 pipeline output.
        let tree = AssembledTree {
            segments: vec![],
            groups: vec![AssembledGroup {
                group_id: "SG10".to_string(),
                repetitions: vec![AssembledGroupInstance {
                    segments: vec![
                        make_segment("STS", vec![vec!["Z32"], vec![], vec!["Z92"]], Some("00035")),
                        make_segment("STS", vec![vec!["Z40"], vec![], vec!["Z75"]], Some("00036")),
                    ],
                    child_groups: vec![],
                    entry_mig_number: None,
                    variant_mig_numbers: vec![
                        "00035".into(),
                        "00036".into(),
                        "00037".into(),
                        "00038".into(),
                    ],
                    skipped_segments: vec![],
                    skipped_positions: Vec::new(),
                }],
            }],
            post_group_start: 0,
            inter_group_segments: BTreeMap::new(),
        };

        let result = build_validated_tree(&workflow, &tree);
        assert_eq!(result.groups.len(), 1);
        let sg10 = &result.groups[0];
        assert_eq!(
            sg10.fields.len(),
            3,
            "all three rules should pass the variant filter"
        );

        let by_name = |name: &str| sg10.fields.iter().find(|f| f.rule.name == name).unwrap();

        // Z33 is genuinely absent — no STS in the input has 9015=Z33.
        assert_eq!(
            by_name("Statuskategorie Z33").value,
            None,
            "Z33 has no matching STS in the input; must not silently pick up Z32's segment"
        );

        // Z32 must resolve to the STS segment whose 9015 is Z32,
        // regardless of the assembler's mis-assigned mig_number.
        assert_eq!(
            by_name("Statuskategorie Z32").value,
            Some("Z32"),
            "rule for Z32 must attach to the STS segment with qualifier Z32"
        );

        // Z40 must resolve to the STS segment whose 9015 is Z40.
        assert_eq!(
            by_name("Statuskategorie Z40").value,
            Some("Z40"),
            "rule for Z40 must attach to the STS segment with qualifier Z40"
        );
    }
}