automapper-validation 0.12.0

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
// <auto-generated>
// Generated by automapper-generator generate-conditions
// AHB: xml-migs-and-ahbs/FV2510/UTILMD_AHB_Strom_2_1_Fehlerkorrektur_20260302.xml
// Generated: 2026-09-23T08:11:11Z
// Delegates unchanged conditions to UtilmdStromConditionEvaluatorFV2504 (FV2504).
// </auto-generated>

#![allow(clippy::style, clippy::complexity)]

#[allow(unused_imports)]
use crate::eval::format_validators::*;
use crate::eval::{ConditionEvaluator, ConditionResult, EvaluationContext};
use crate::generated::fv2504::UtilmdStromConditionEvaluatorFV2504;

/// Condition evaluator for UTILMD_Strom FV2510.
///
/// Delegates to [`UtilmdStromConditionEvaluatorFV2504`] for conditions whose AHB description is
/// unchanged from that version. Local overrides: [2], [3], [20], [28], [29], [79], [136], [139], [157], [158], [168], [169], [242], [253], [258], [263], [297], [312], [313], [326], [328], [346], [413], [414], [415], [416], [461], [534], [557], [560], [561], [562], [564], [565], [578], [681], [686], [2000], [2016], [2121].
pub struct UtilmdStromConditionEvaluatorFV2510 {
    fallback: UtilmdStromConditionEvaluatorFV2504,
}

impl Default for UtilmdStromConditionEvaluatorFV2510 {
    fn default() -> Self {
        Self {
            fallback: UtilmdStromConditionEvaluatorFV2504::default(),
        }
    }
}

/// Condition IDs whose implementation differs from the fallback.
const FV2510_OVERRIDES: &[u32] = &[
    2, 3, 20, 28, 29, 79, 136, 139, 157, 158, 168, 169, 242, 253, 258, 263, 297, 312, 313, 326,
    328, 346, 413, 414, 415, 416, 461, 534, 557, 560, 561, 562, 564, 565, 578, 681, 686, 2000,
    2016, 2121,
];

/// Overrides that require context from outside the message.
const FV2510_EXTERNAL: &[u32] = &[3, 326, 328];

impl ConditionEvaluator for UtilmdStromConditionEvaluatorFV2510 {
    fn message_type(&self) -> &str {
        "UTILMD_Strom"
    }

    fn format_version(&self) -> &str {
        "FV2510"
    }

    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        match condition {
            2 => self.evaluate_2(ctx),
            3 => self.evaluate_3(ctx),
            20 => self.evaluate_20(ctx),
            28 => self.evaluate_28(ctx),
            29 => self.evaluate_29(ctx),
            79 => self.evaluate_79(ctx),
            136 => self.evaluate_136(ctx),
            139 => self.evaluate_139(ctx),
            157 => self.evaluate_157(ctx),
            158 => self.evaluate_158(ctx),
            168 => self.evaluate_168(ctx),
            169 => self.evaluate_169(ctx),
            242 => self.evaluate_242(ctx),
            253 => self.evaluate_253(ctx),
            258 => self.evaluate_258(ctx),
            263 => self.evaluate_263(ctx),
            297 => self.evaluate_297(ctx),
            312 => self.evaluate_312(ctx),
            313 => self.evaluate_313(ctx),
            326 => self.evaluate_326(ctx),
            328 => self.evaluate_328(ctx),
            346 => self.evaluate_346(ctx),
            413 => self.evaluate_413(ctx),
            414 => self.evaluate_414(ctx),
            415 => self.evaluate_415(ctx),
            416 => self.evaluate_416(ctx),
            461 => self.evaluate_461(ctx),
            534 => self.evaluate_534(ctx),
            557 => self.evaluate_557(ctx),
            560 => self.evaluate_560(ctx),
            561 => self.evaluate_561(ctx),
            562 => self.evaluate_562(ctx),
            564 => self.evaluate_564(ctx),
            565 => self.evaluate_565(ctx),
            578 => self.evaluate_578(ctx),
            681 => self.evaluate_681(ctx),
            686 => self.evaluate_686(ctx),
            2000 => self.evaluate_2000(ctx),
            2016 => self.evaluate_2016(ctx),
            2121 => self.evaluate_2121(ctx),
            other => self.fallback.evaluate(other, ctx),
        }
    }

    fn is_external(&self, condition: u32) -> bool {
        if FV2510_OVERRIDES.contains(&condition) {
            FV2510_EXTERNAL.contains(&condition)
        } else {
            self.fallback.is_external(condition)
        }
    }

    fn is_known(&self, condition: u32) -> bool {
        FV2510_OVERRIDES.contains(&condition) || self.fallback.is_known(condition)
    }
}

impl UtilmdStromConditionEvaluatorFV2510 {
    /// [2] Wenn UNH DE0070 (Übermittlungsfolgenummer) mit 1 vorhanden
    fn evaluate_2(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.has_segment_matching("UNH", &[(3, 0, "1")])
    }

    /// [3] Bei Aufteilung, in der Nachricht mit der höchsten Übermittlungsfolgenummer
    /// EXTERNAL: Requires context from outside the message.
    fn evaluate_3(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("is_highest_sequence_in_split")
    }

    /// [20] Wenn im SG8 SEQ+Z01 (Daten der Marktlokation) mit der gleichen ID im SG8 RFF+Z18 (Referenz auf die ID der Marktlokation) wie in diesem SG8 das SG10 CCI+Z30++Z07 (Verbrauch) vorhanden
    fn evaluate_20(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ctx.has_qualified_value("CCI", 0, "Z30", 2, 0, &["Z07"]),
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            let has_z01 = seq_segs.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z01")
            });
            if !has_z01 {
                continue;
            }
            let sg10_count = nav.child_group_instance_count(&["SG4", "SG8"], i, "SG10");
            for j in 0..sg10_count {
                let ccis = nav.find_segments_in_child_group("CCI", &["SG4", "SG8"], i, "SG10", j);
                if ccis.iter().any(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z30")
                        && s.elements
                            .get(2)
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z07")
                }) {
                    return ConditionResult::True;
                }
            }
        }
        ConditionResult::False
    }

    /// [28] Wenn in dieser SG4 IDE+24 das STS+E01++A04: E_0017 bzw. A03: E_0052 (Zusätzlicher Datensatz / ergänzte Marktlokation) nicht vorhanden
    // REVIEW: Within each SG4 containing IDE+24 (Vorgang), check if STS+E01 with Prüfschritt A04:E_0017 (Zusätzlicher Datensatz) or A03:E_0052 (ergänzte Marktlokation) is absent. Uses navigator to scope the check per SG4 instance. STS elements[0][0]="E01", elements[2][0]=Prüfschritt code, elements[2][1]=codelist. Condition is True when this STS is NOT found in the SG4, indicating no 'additional record' status was set. (medium confidence)
    fn evaluate_28(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => {
                let sts_segs = ctx.find_segments_with_qualifier("STS", 0, "E01");
                let found = sts_segs.iter().any(|s| {
                    let code = s
                        .elements
                        .get(2)
                        .and_then(|e| e.first())
                        .map(|v| v.as_str());
                    let list = s.elements.get(2).and_then(|e| e.get(1)).map(|v| v.as_str());
                    (code == Some("A04") && list == Some("E_0017"))
                        || (code == Some("A03") && list == Some("E_0052"))
                });
                return ConditionResult::from(!found);
            }
        };
        let sg4_count = nav.group_instance_count(&["SG4"]);
        for i in 0..sg4_count {
            let ide_segs = nav.find_segments_in_group("IDE", &["SG4"], i);
            let has_ide_24 = ide_segs.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "24")
            });
            if !has_ide_24 {
                continue;
            }
            let sts_segs = nav.find_segments_in_group("STS", &["SG4"], i);
            let found = sts_segs.iter().any(|s| {
                let qual = s
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .map(|v| v.as_str());
                let code = s
                    .elements
                    .get(2)
                    .and_then(|e| e.first())
                    .map(|v| v.as_str());
                let list = s.elements.get(2).and_then(|e| e.get(1)).map(|v| v.as_str());
                qual == Some("E01")
                    && ((code == Some("A04") && list == Some("E_0017"))
                        || (code == Some("A03") && list == Some("E_0052")))
            });
            if !found {
                return ConditionResult::True;
            }
        }
        ConditionResult::False
    }

    /// [29] Wenn in dieser SG4 IDE+24 das STS+E01++A06: E_0017 bzw. A05: E_0052 (Zu viele Marktlokationen enthalten / entfallene Marktlokation) nicht vorhanden
    // REVIEW: Within each SG4 containing IDE+24 (Vorgang), check if STS+E01 with Prüfschritt A06:E_0017 (Zu viele Marktlokationen) or A05:E_0052 (entfallene Marktlokation) is absent. Mirrors condition [28] but for the 'too many / dropped Marktlokation' status codes. True when neither combination is found in the SG4, indicating no 'excess/dropped records' status was set. (medium confidence)
    fn evaluate_29(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => {
                let sts_segs = ctx.find_segments_with_qualifier("STS", 0, "E01");
                let found = sts_segs.iter().any(|s| {
                    let code = s
                        .elements
                        .get(2)
                        .and_then(|e| e.first())
                        .map(|v| v.as_str());
                    let list = s.elements.get(2).and_then(|e| e.get(1)).map(|v| v.as_str());
                    (code == Some("A06") && list == Some("E_0017"))
                        || (code == Some("A05") && list == Some("E_0052"))
                });
                return ConditionResult::from(!found);
            }
        };
        let sg4_count = nav.group_instance_count(&["SG4"]);
        for i in 0..sg4_count {
            let ide_segs = nav.find_segments_in_group("IDE", &["SG4"], i);
            let has_ide_24 = ide_segs.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "24")
            });
            if !has_ide_24 {
                continue;
            }
            let sts_segs = nav.find_segments_in_group("STS", &["SG4"], i);
            let found = sts_segs.iter().any(|s| {
                let qual = s
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .map(|v| v.as_str());
                let code = s
                    .elements
                    .get(2)
                    .and_then(|e| e.first())
                    .map(|v| v.as_str());
                let list = s.elements.get(2).and_then(|e| e.get(1)).map(|v| v.as_str());
                qual == Some("E01")
                    && ((code == Some("A06") && list == Some("E_0017"))
                        || (code == Some("A05") && list == Some("E_0052")))
            });
            if !found {
                return ConditionResult::True;
            }
        }
        ConditionResult::False
    }

    /// [79] Wenn SG4 STS+7++Z33 (Auszug wegen Stilllegung) vorhanden
    fn evaluate_79(&self, ctx: &EvaluationContext) -> ConditionResult {
        // STS+7++Z33: elements[0][0]="7" (Transaktionsgrund), elements[2][0]="Z33" (Auszug wegen Stilllegung).
        // FV2504's text read STS+7+++Z33 (element 3); since the 2026-03-02 AHB it is element 2, as in [157].
        ctx.has_segment_matching("STS", &[(0, 0, "7"), (2, 0, "Z33")])
    }

    /// [136] Wenn SG10 CCI+++E13 (Zählertyp) CAV+EHZ (elektronischer Haushaltszähler) in dieser SG8 vorhanden
    fn evaluate_136(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ctx.has_qualified_value("CAV", 0, "EHZ", 0, 0, &["EHZ"]),
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        for i in 0..sg8_count {
            let sg10_count = nav.child_group_instance_count(&["SG4", "SG8"], i, "SG10");
            for j in 0..sg10_count {
                let ccis = nav.find_segments_in_child_group("CCI", &["SG4", "SG8"], i, "SG10", j);
                let has_cci_e13 = ccis.iter().any(|s| {
                    s.elements
                        .get(2)
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "E13")
                });
                if has_cci_e13 {
                    let cavs =
                        nav.find_segments_in_child_group("CAV", &["SG4", "SG8"], i, "SG10", j);
                    if cavs.iter().any(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "EHZ")
                    }) {
                        return ConditionResult::True;
                    }
                }
            }
        }
        ConditionResult::False
    }

    /// [139] Wenn SG10 CAV+IVA (Individuelle Abstimmung) in dieser SG8 nicht vorhanden
    // REVIEW: True when no SG10 child of any SG8 contains a CAV with elements[0][0]=='IVA'. Iterates all SG8 instances and their SG10 children; returns False as soon as IVA is found, True if absent throughout. 'In dieser SG8' is evaluated message-wide since no specific parent qualifier filter is given. (medium confidence)
    fn evaluate_139(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ctx.lacks_qualifier("CAV", 0, "IVA"),
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        for i in 0..sg8_count {
            let sg10_count = nav.child_group_instance_count(&["SG4", "SG8"], i, "SG10");
            for j in 0..sg10_count {
                let cavs = nav.find_segments_in_child_group("CAV", &["SG4", "SG8"], i, "SG10", j);
                if cavs.iter().any(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "IVA")
                }) {
                    return ConditionResult::False;
                }
            }
        }
        ConditionResult::True
    }

    /// [157] Wenn SG4 STS+7++Z33+ZZB nicht vorhanden
    fn evaluate_157(&self, ctx: &EvaluationContext) -> ConditionResult {
        let result = ctx.has_segment_matching("STS", &[(0, 0, "7"), (2, 0, "Z33"), (3, 0, "ZZB")]);
        match result {
            ConditionResult::True => ConditionResult::False,
            ConditionResult::False => ConditionResult::True,
            ConditionResult::Unknown => ConditionResult::Unknown,
        }
    }

    /// [158] Wenn im selben Segment im DE2379 der Code 106 vorhanden ist
    fn evaluate_158(&self, ctx: &EvaluationContext) -> ConditionResult {
        ConditionResult::from(ctx.self_segment_value_equals("DTM", 0, 2, "106"))
    }

    /// [168] Wenn in dieser SG8 im SG8 PIA+Z02 (Gruppenartikel- ID / Artikel-ID), die Artikel-ID 1-02-0-002/ 003/ 004 vorhanden
    fn evaluate_168(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_qualified_value(
            "PIA",
            0,
            "Z02",
            1,
            0,
            &["1-02-0-002", "1-02-0-003", "1-02-0-004"],
            &["SG4", "SG8"],
        )
    }

    /// [169] Wenn zwei SG8 SEQ+Z45 (Netznutzungsabrechnungsdaten der Marktlokation), mit derselben Zeitraum-ID im DE1050, mit Artikel-ID im SG8 PIA+Z02 (Gruppenartikel-ID / Artikel-ID), eine SG8 mit 1-02-0-002 ...
    // REVIEW: Complex cross-group condition. Collects all SG8 instances having SEQ+Z45 (Netznutzungsabrechnungsdaten), extracting the Zeitraum-ID from SEQ elements[1][0] (DE1050) and the PIA+Z02 article ID from elements[1][0]. Then checks if two such SG8 instances share the same Zeitraum-ID where one has article 1-02-0-002 and the other has 1-02-0-003 or 1-02-0-004. Medium confidence because the article ID string format ('1-02-0-002') must match exactly as stored in the EDIFACT value. (medium confidence)
    fn evaluate_169(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        let mut sg8_data: Vec<(String, String)> = Vec::new();
        for i in 0..sg8_count {
            let seqs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            let zeitraum_id = seqs
                .iter()
                .find(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z45")
                })
                .and_then(|s| s.elements.get(1))
                .and_then(|e| e.first())
                .filter(|v| !v.is_empty())
                .cloned();
            if let Some(zid) = zeitraum_id {
                let pias = nav.find_segments_in_group("PIA", &["SG4", "SG8"], i);
                let article_id = pias
                    .iter()
                    .find(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z02")
                    })
                    .and_then(|s| s.elements.get(1))
                    .and_then(|e| e.first())
                    .cloned()
                    .unwrap_or_default();
                sg8_data.push((zid, article_id));
            }
        }
        for i in 0..sg8_data.len() {
            for j in (i + 1)..sg8_data.len() {
                if sg8_data[i].0 == sg8_data[j].0 {
                    let (id_i, id_j) = (&sg8_data[i].1, &sg8_data[j].1);
                    let i_is_002 = id_i == "1-02-0-002";
                    let j_is_002 = id_j == "1-02-0-002";
                    let i_is_003_004 = id_i == "1-02-0-003" || id_i == "1-02-0-004";
                    let j_is_003_004 = id_j == "1-02-0-003" || id_j == "1-02-0-004";
                    if (i_is_002 && j_is_003_004) || (j_is_002 && i_is_003_004) {
                        return ConditionResult::True;
                    }
                }
            }
        }
        if sg8_data.is_empty() {
            ConditionResult::Unknown
        } else {
            ConditionResult::False
        }
    }

    /// [242] Wenn mehr als ein SG8 (Referenz auf die Lokationsbündelstruktur) mit der selben Zeitraum-ID im DE1050 vorhanden
    fn evaluate_242(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        let mut ids: Vec<String> = Vec::new();
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            for seq in &seq_segs {
                let qual = seq
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .map(|s| s.as_str());
                if matches!(qual, Some("Z78") | Some("ZC7") | Some("ZC8") | Some("ZD5")) {
                    if let Some(id) = seq.elements.get(1).and_then(|e| e.first()) {
                        if !id.is_empty() {
                            ids.push(id.clone());
                        }
                    }
                }
            }
        }
        if ids.is_empty() {
            return ConditionResult::Unknown;
        }
        let mut seen = std::collections::HashSet::new();
        ConditionResult::from(ids.iter().any(|id| !seen.insert(id.as_str())))
    }

    /// [253] Wenn SG4 STS+E01++ZC9 (Ablehnung (keine Zuordnung möglich)) nicht vorhanden
    fn evaluate_253(&self, ctx: &EvaluationContext) -> ConditionResult {
        match ctx.has_segment_matching("STS", &[(0, 0, "E01"), (2, 0, "ZC9")]) {
            ConditionResult::True => ConditionResult::False,
            ConditionResult::False => ConditionResult::True,
            ConditionResult::Unknown => ConditionResult::Unknown,
        }
    }

    /// [258] Wenn in dieser SG8 SEQ+Z01 (Daten der Marktlokation) SG10 CCI+Z30++Z07 (Verbrauch) vorhanden
    fn evaluate_258(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ctx.has_qualified_value("CCI", 0, "Z30", 2, 0, &["Z07"]),
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            let has_z01 = seq_segs.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z01")
            });
            if has_z01 {
                let sg10_count = nav.child_group_instance_count(&["SG4", "SG8"], i, "SG10");
                for j in 0..sg10_count {
                    let ccis =
                        nav.find_segments_in_child_group("CCI", &["SG4", "SG8"], i, "SG10", j);
                    if ccis.iter().any(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z30")
                            && s.elements
                                .get(2)
                                .and_then(|e| e.first())
                                .is_some_and(|v| v == "Z07")
                    }) {
                        return ConditionResult::True;
                    }
                }
            }
        }
        ConditionResult::False
    }

    /// [263] Wenn SG8 SEQ+Z01 (Daten der Marktlokation) SG10 CCI+Z30++Z07 (Verbrauch) vorhanden
    // Message-wide: any SG8 SEQ+Z01 with an SG10 CCI+Z30++Z07. This is FV2504's [20] text, renumbered.
    fn evaluate_263(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ctx.has_qualified_value("CCI", 0, "Z30", 2, 0, &["Z07"]),
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            let has_z01 = seq_segs.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z01")
            });
            if !has_z01 {
                continue;
            }
            let sg10_count = nav.child_group_instance_count(&["SG4", "SG8"], i, "SG10");
            for j in 0..sg10_count {
                let ccis = nav.find_segments_in_child_group("CCI", &["SG4", "SG8"], i, "SG10", j);
                if ccis.iter().any(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z30")
                        && s.elements
                            .get(2)
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z07")
                }) {
                    return ConditionResult::True;
                }
            }
        }
        ConditionResult::False
    }

    /// [297] Wenn mehr als eine SG8 SEQ+Z02/ ZE3 (OBIS- Daten der Marktlokation) mit einer OBIS-Kennzahl für Energiemenge im PIA+5, mit gleicher Zeitraum-ID und identischem Code im DE1229 des SG8 SEQ+Z02/ZA1/Z...
    // REVIEW: Find SG8 instances with SEQ qualifier Z02 or ZE3 that also have a PIA+5 segment. Collect (de1229_code, zeitraum_id) tuples. Condition is True when more than one such SG8 shares the same combination. Note: 'OBIS-Kennzahl für Energiemenge' filtering is not enforced here (would require knowledge of valid OBIS patterns), so presence of PIA+5 is used as a proxy. (medium confidence)
    fn evaluate_297(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        // Collect (seq_qualifier, zeitraum_id) tuples from SG8 instances with SEQ+Z02/ZE3 that also have PIA+5
        let mut keys: Vec<(String, String)> = Vec::new();
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            for seq in &seq_segs {
                let qual = seq
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .map(|s| s.as_str());
                if matches!(qual, Some("Z02") | Some("ZE3")) {
                    let pia_segs = nav.find_segments_in_group("PIA", &["SG4", "SG8"], i);
                    let has_pia5 = pia_segs.iter().any(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "5")
                    });
                    if has_pia5 {
                        let zeitraum_id = seq
                            .elements
                            .get(1)
                            .and_then(|e| e.first())
                            .cloned()
                            .unwrap_or_default();
                        if !zeitraum_id.is_empty() {
                            keys.push((qual.unwrap_or_default().to_string(), zeitraum_id));
                        }
                    }
                }
            }
        }
        if keys.is_empty() {
            return ConditionResult::Unknown;
        }
        let mut seen = std::collections::HashSet::new();
        ConditionResult::from(keys.iter().any(|k| !seen.insert(k)))
    }

    /// [312] Wenn DTM+137 (Nachrichtendatum) im DE2380 &lt; 202603312200?+00
    fn evaluate_312(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.dtm_lt("137", "202603312200+00")
    }

    /// [313] Wenn DTM+137 (Nachrichtendatum) im DE2380 ≥ 202603312200?+00
    fn evaluate_313(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.dtm_ge("137", "202603312200+00")
    }

    /// [326] Wenn die Marktlokation nicht stillgelegt wird
    /// EXTERNAL: Requires context from outside the message.
    fn evaluate_326(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("market_location_not_decommissioned")
    }

    /// [328] Wenn die Marktlokation stillgelegt wird
    /// EXTERNAL: Requires context from outside the message.
    fn evaluate_328(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("market_location_decommissioned")
    }

    /// [346] Wenn SG10 CCI+++E13 (Zählertyp) CAV+MME (mME) in dieser SG8 vorhanden
    fn evaluate_346(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => {
                // Fallback: message-wide check for both CCI+E13 and CAV+MME
                let has_cci = ctx.has_qualifier("CCI", 2, "E13");
                let has_cav = ctx.has_qualifier("CAV", 0, "MME");
                return match (has_cci, has_cav) {
                    (ConditionResult::True, ConditionResult::True) => ConditionResult::True,
                    (ConditionResult::False, _) | (_, ConditionResult::False) => {
                        ConditionResult::False
                    }
                    _ => ConditionResult::Unknown,
                };
            }
        };
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        for i in 0..sg8_count {
            let sg10_count = nav.child_group_instance_count(&["SG4", "SG8"], i, "SG10");
            for j in 0..sg10_count {
                let ccis = nav.find_segments_in_child_group("CCI", &["SG4", "SG8"], i, "SG10", j);
                let has_cci_e13 = ccis.iter().any(|s| {
                    s.elements
                        .get(2)
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "E13")
                });
                if has_cci_e13 {
                    let cavs =
                        nav.find_segments_in_child_group("CAV", &["SG4", "SG8"], i, "SG10", j);
                    if cavs.iter().any(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "MME")
                    }) {
                        return ConditionResult::True;
                    }
                }
            }
        }
        ConditionResult::False
    }

    /// [413] Wenn eine SG8 SEQ+Z02/ZA1/ZA2 (OBIS-Daten der Marktlokation) mit einer OBIS-Kennzahl für Wirkarbeit und kumuliert im PIA+5, mit gleicher Zeitraum-ID und identischem Code im DE1229 des SG8 SEQ+Z02/...
    fn evaluate_413(&self, ctx: &EvaluationContext) -> ConditionResult {
        // At least one SG8 SEQ+{Z02|ZA1|ZA2} with matching DE1229 qualifier
        // and matching DE1050 Zeitraum-ID exists whose PIA+5 OBIS is
        // Wirkarbeit-kumuliert (C ∈ {1,2}, D ∈ {8,9}).
        ConditionResult::from(ctx.count_sg8_obis_matches(is_obis_wirkarbeit_kumuliert) >= 1)
    }

    /// [414] Wenn keine SG8 SEQ+Z02/ZA1/ZA2 (OBIS-Daten der Marktlokation) mit einer OBIS-Kennzahl für Wirkarbeit und kumuliert im PIA+5, mit gleicher Zeitraum-ID und identischem Code im DE1229 des SG8 SEQ+Z02...
    fn evaluate_414(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Negation of [413] — no matching kumuliert SG8 exists.
        ConditionResult::from(ctx.count_sg8_obis_matches(is_obis_wirkarbeit_kumuliert) == 0)
    }

    /// [415] Wenn eine weitere SG8 SEQ+Z02/ZA1/ZA2 (OBIS-Daten der Marktlokation) mit einer OBIS-Kennzahl für Wirkarbeit und 1/4 Stunde im PIA+5, mit gleicher Zeitraum-ID und identischem Code im DE1229 des SG8...
    fn evaluate_415(&self, ctx: &EvaluationContext) -> ConditionResult {
        // "eine weitere" = at least one BESIDES the current → count >= 2.
        // OBIS predicate: Wirkarbeit 1/4 Stunde (C ∈ {1,2}, D = 29).
        ConditionResult::from(ctx.count_sg8_obis_matches(is_obis_wirkarbeit_quarter_hour) >= 2)
    }

    /// [416] Wenn keine SG8 SEQ+Z02/ZA1/ZA2 (OBIS-Daten der Marktlokation) mit einer OBIS-Kennzahl für Wirkarbeit und 1/4 Stunde im PIA+5, mit gleicher Zeitraum-ID und identischem Code im DE1229 des SG8 SEQ+Z0...
    fn evaluate_416(&self, ctx: &EvaluationContext) -> ConditionResult {
        // No SG8 matching current's Zeitraum-ID/qualifier has a 1/4 Stunde
        // Wirkarbeit OBIS in its PIA+5.
        ConditionResult::from(ctx.count_sg8_obis_matches(is_obis_wirkarbeit_quarter_hour) == 0)
    }

    /// [461] Wenn in derselben SG10 das CCI (Art und Nutzung der Technischen Ressource) im CAV+ZG8 (Technischen Ressource fällt unter § 14a EnWG) vorhanden
    fn evaluate_461(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Wenn in derselben SG10 das CCI (Art und Nutzung der Technischen Ressource)
        // im CAV+ZG8 (Technische Ressource fällt unter § 14a EnWG) vorhanden
        // CCI is the SG10 entry segment; condition reduces to: any SG10 has CAV with ZG8
        ctx.any_group_has_qualifier("CAV", 0, "ZG8", &["SG4", "SG8", "SG10"])
    }

    /// [534] Hinweis: Aufgrund der Wiederholbarkeit des SG4 STS Status der Antwort ist die Angabe von max. acht Verwendungszeiträumen möglich
    fn evaluate_534(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Aufgrund der Wiederholbarkeit des SG4 STS Status der Antwort ist
        // die Angabe von max. acht Verwendungszeiträumen möglich
        // — informational note about cardinality, always applies
        ConditionResult::True
    }

    /// [557] Hinweis: Wurden vom Verantwortlichen mehr als acht Verwendungszeiträume gesendet, so werden acht beliebige Verwendungszeiträume beantwortet
    fn evaluate_557(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Wurden vom Verantwortlichen mehr als acht Verwendungszeiträume
        // gesendet, so werden acht beliebige Verwendungszeiträume beantwortet
        // — informational processing note, always applies
        ConditionResult::True
    }

    /// [560] Hinweis: Dies entspricht dem Geschäftsvorfall A
    fn evaluate_560(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Dies entspricht dem Geschäftsvorfall A — informational note, always applies
        ConditionResult::True
    }

    /// [561] Hinweis: Dies entspricht dem Geschäftsvorfall B
    fn evaluate_561(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Dies entspricht dem Geschäftsvorfall B — informational note, always applies
        ConditionResult::True
    }

    /// [562] Hinweis: Bei Marktlokationen, welche auf Basis von Werten bilanziert werden, wird der erste Tag des Jahres angegeben.
    fn evaluate_562(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Bei Marktlokationen, welche auf Basis von Werten bilanziert werden, wird der erste Tag des Jahres angegeben — informational note, always applies
        ConditionResult::True
    }

    /// [564] Hinweis: Das IDE+Z01 (Liste) definiert den Geschäftsvorfall. Alle aufgelisteten IDE+24 sind Bestandteil des Geschäftsvorfalls
    fn evaluate_564(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Das IDE+Z01 (Liste) definiert den Geschäftsvorfall. Alle aufgelisteten IDE+24 sind Bestandteil des Geschäftsvorfalls — informational note, always applies
        ConditionResult::True
    }

    /// [565] Hinweis: Das IDE+24 beschreibt einen Bestandteil einer Liste, wenn ein IDE+Z01 vorhanden ist. Es beschreibt nicht den Geschäftsvorfall
    fn evaluate_565(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Das IDE+24 beschreibt einen Bestandteil einer Liste, wenn ein IDE+Z01 vorhanden ist. Es beschreibt nicht den Geschäftsvorfall — informational note, always applies
        ConditionResult::True
    }

    /// [578] Hinweis: Dies gilt für den Zeitraum welcher mit Z53 (keine Daten) definiert ist
    fn evaluate_578(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Dies gilt für den Zeitraum welcher mit Z53 (keine Daten) definiert ist — informational note, always applies
        ConditionResult::True
    }

    /// [681] Hinweis: Übergangsversorgung gibt es nur bei Marktlokationen, die unter § 38a EnWG fallen. Grundlage ist eine bilaterale Vereinbarung
    fn evaluate_681(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Übergangsversorgung applies only to Marktlokationen under § 38a EnWG based on bilateral agreement — informational note, always applies
        ConditionResult::True
    }

    /// [686] Hinweis: Zu verwenden bei der Abmeldung der Übergangsversorgung.
    fn evaluate_686(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Zu verwenden bei der Abmeldung der Übergangsversorgung — informational note, always applies
        ConditionResult::True
    }

    /// [2000] Je SG5 LOC+Z16 (Marktlokation) ist genau einmal die Segmentgruppe anzugeben
    // REVIEW: Checks that per SG4 transaction group, exactly one SG5 child group contains a LOC segment with qualifier Z16 (Marktlokation). Uses parent-child navigator to iterate SG4 instances and count LOC+Z16 occurrences in their SG5 children. Falls back to message-wide count when no navigator is available. (medium confidence)
    fn evaluate_2000(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Je SG5 LOC+Z16 (Marktlokation) ist genau einmal die Segmentgruppe anzugeben
        // Per SG4 transaction group, exactly one SG5 instance should contain LOC+Z16
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => {
                let count = ctx.count_qualified_in_group("LOC", 0, "Z16", &["SG4", "SG5"]);
                return ConditionResult::from(count == 1);
            }
        };
        let sg4_count = nav.group_instance_count(&["SG4"]);
        if sg4_count == 0 {
            return ConditionResult::Unknown;
        }
        for i in 0..sg4_count {
            let sg5_count = nav.child_group_instance_count(&["SG4"], i, "SG5");
            let mut loc_z16_count = 0usize;
            for j in 0..sg5_count {
                let locs = nav.find_segments_in_child_group("LOC", &["SG4"], i, "SG5", j);
                for loc in &locs {
                    if loc
                        .elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z16")
                    {
                        loc_z16_count += 1;
                    }
                }
            }
            if loc_z16_count != 1 {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [2016] Segmentgruppe ist mind. einmal für jede Zeitraum-ID aus dem DE1156 der SG6 RFF+Z49 / Z53 (Verwendungszeitraum der Daten: "Gültige Daten" / "Keine Daten") aus der Anfragennachricht aus SG6 RFF+TN ...
    // REVIEW: Cross-group Zeitraum-ID correlation: collect DE1156 values from SG6 RFF+Z49/Z53, verify each is covered by at least one SG8 SEQ's DE1050 reference. The mention of 'Anfragenachricht' (request message) and RFF+TN adds ambiguity about whether the source is this message or an external one; implemented as intra-message check on the most direct interpretation. (medium confidence)
    fn evaluate_2016(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Segmentgruppe ist mind. einmal für jede Zeitraum-ID aus DE1156 der SG6 RFF+Z49/Z53 anzugeben
        // Collect Zeitraum-IDs from SG6 RFF+Z49 and Z53 (DE1156 = elements[0][2])
        // Then verify each required Zeitraum-ID is referenced by at least one SG8 SEQ (DE1050 = elements[1][0])
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg6_count = nav.group_instance_count(&["SG4", "SG6"]);
        let mut required_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
        for i in 0..sg6_count {
            let rffs = nav.find_segments_in_group("RFF", &["SG4", "SG6"], i);
            for rff in &rffs {
                let qual = rff
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .map(|s| s.as_str());
                if matches!(qual, Some("Z49") | Some("Z53")) {
                    if let Some(zeitraum_id) = rff.elements.first().and_then(|e| e.get(2)) {
                        if !zeitraum_id.is_empty() {
                            required_ids.insert(zeitraum_id.clone());
                        }
                    }
                }
            }
        }
        if required_ids.is_empty() {
            return ConditionResult::Unknown;
        }
        // Check that for each required Zeitraum-ID at least one SG8 SEQ references it via DE1050
        let sg8_count = nav.group_instance_count(&["SG4", "SG8"]);
        let mut found_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
        for i in 0..sg8_count {
            let seqs = nav.find_segments_in_group("SEQ", &["SG4", "SG8"], i);
            for seq in &seqs {
                if let Some(ref_id) = seq.elements.get(1).and_then(|e| e.first()) {
                    if !ref_id.is_empty() {
                        found_ids.insert(ref_id.clone());
                    }
                }
            }
        }
        ConditionResult::from(required_ids.iter().all(|id| found_ids.contains(id)))
    }

    /// [2121] Segmentgruppe ist genau einmal je SG8 SEQ+Z01/ Z80/Z81 (Daten der Marktlokation/ Erwartete Daten der Marktlokation/ Im System vorhandene Daten der Marktlokation) anzugeben
    // REVIEW: Cardinality condition: this segment group must appear exactly once per qualifying SG8 (those with SEQ+Z01/Z80/Z81 — Daten/Erwartete Daten/Im System vorhandene Daten der Marktlokation). As a boolean predicate the condition evaluates True when such qualifying SG8 instances exist, signalling that the subject segment group is required. Full cardinality validation (exactly-once enforcement) requires the broader validator framework. (medium confidence)
    fn evaluate_2121(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Segmentgruppe ist genau einmal je SG8 SEQ+Z01/Z80/Z81 anzugeben
        // True when at least one SG8 with SEQ+Z01, Z80, or Z81 exists (cardinality trigger)
        ctx.any_group_has_any_qualifier("SEQ", 0, &["Z01", "Z80", "Z81"], &["SG4", "SG8"])
    }
}