automapper-validation 0.3.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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
// <auto-generated>
// Generated by automapper-generator generate-conditions
// AHB: xml-migs-and-ahbs/FV2504/UTILTS_AHB_1_0_Fehlerkorrektur_20250218.xml
// Generated: 2026-03-12T10:04:46Z
// </auto-generated>

// LLM-produced bodies aren't idiomatic Rust — silence stylistic lints at
// file scope so `cargo clippy -D warnings` stays green. Correctness,
// suspicious, and perf categories stay on so real bugs still surface.
#![allow(clippy::style, clippy::complexity)]

#[allow(unused_imports)]
use crate::eval::format_validators::*;
use crate::eval::{Cluster, ConditionEvaluator, ConditionResult, EvaluationContext};
// HAND-EDITED: shared cluster helper for condition [61].
// Preserve across regeneration — see CLAUDE.md "Codelist Providers".
use crate::eval::ebd_cluster::any_sts_e01_in_cluster;

/// Generated condition evaluator for UTILTS FV2504.
pub struct UtiltsConditionEvaluatorFV2504 {
    // External condition IDs that require runtime context.
    external_conditions: std::collections::HashSet<u32>,
}

impl Default for UtiltsConditionEvaluatorFV2504 {
    fn default() -> Self {
        let mut external_conditions = std::collections::HashSet::new();
        external_conditions.insert(1);
        external_conditions.insert(22);
        external_conditions.insert(25);
        external_conditions.insert(26);
        external_conditions.insert(37);
        // HAND-EDITED: [61] is no longer external — EBD cluster lookup handles it.
        // external_conditions.insert(61);
        external_conditions.insert(62);
        external_conditions.insert(494);
        Self {
            external_conditions,
        }
    }
}

impl ConditionEvaluator for UtiltsConditionEvaluatorFV2504 {
    fn message_type(&self) -> &str {
        "UTILTS"
    }

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

    fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
        match condition {
            1 => self.evaluate_1(ctx),
            2 => self.evaluate_2(ctx),
            5 => self.evaluate_5(ctx),
            6 => self.evaluate_6(ctx),
            7 => self.evaluate_7(ctx),
            8 => self.evaluate_8(ctx),
            9 => self.evaluate_9(ctx),
            10 => self.evaluate_10(ctx),
            11 => self.evaluate_11(ctx),
            12 => self.evaluate_12(ctx),
            13 => self.evaluate_13(ctx),
            14 => self.evaluate_14(ctx),
            15 => self.evaluate_15(ctx),
            21 => self.evaluate_21(ctx),
            22 => self.evaluate_22(ctx),
            24 => self.evaluate_24(ctx),
            25 => self.evaluate_25(ctx),
            26 => self.evaluate_26(ctx),
            27 => self.evaluate_27(ctx),
            29 => self.evaluate_29(ctx),
            30 => self.evaluate_30(ctx),
            31 => self.evaluate_31(ctx),
            32 => self.evaluate_32(ctx),
            33 => self.evaluate_33(ctx),
            34 => self.evaluate_34(ctx),
            36 => self.evaluate_36(ctx),
            37 => self.evaluate_37(ctx),
            41 => self.evaluate_41(ctx),
            42 => self.evaluate_42(ctx),
            43 => self.evaluate_43(ctx),
            44 => self.evaluate_44(ctx),
            46 => self.evaluate_46(ctx),
            47 => self.evaluate_47(ctx),
            48 => self.evaluate_48(ctx),
            49 => self.evaluate_49(ctx),
            50 => self.evaluate_50(ctx),
            53 => self.evaluate_53(ctx),
            54 => self.evaluate_54(ctx),
            55 => self.evaluate_55(ctx),
            56 => self.evaluate_56(ctx),
            57 => self.evaluate_57(ctx),
            58 => self.evaluate_58(ctx),
            59 => self.evaluate_59(ctx),
            61 => self.evaluate_61(ctx),
            62 => self.evaluate_62(ctx),
            490 => self.evaluate_490(ctx),
            491 => self.evaluate_491(ctx),
            494 => self.evaluate_494(ctx),
            501 => self.evaluate_501(ctx),
            502 => self.evaluate_502(ctx),
            504 => self.evaluate_504(ctx),
            505 => self.evaluate_505(ctx),
            506 => self.evaluate_506(ctx),
            507 => self.evaluate_507(ctx),
            508 => self.evaluate_508(ctx),
            509 => self.evaluate_509(ctx),
            510 => self.evaluate_510(ctx),
            511 => self.evaluate_511(ctx),
            512 => self.evaluate_512(ctx),
            513 => self.evaluate_513(ctx),
            514 => self.evaluate_514(ctx),
            515 => self.evaluate_515(ctx),
            516 => self.evaluate_516(ctx),
            517 => self.evaluate_517(ctx),
            518 => self.evaluate_518(ctx),
            519 => self.evaluate_519(ctx),
            520 => self.evaluate_520(ctx),
            521 => self.evaluate_521(ctx),
            522 => self.evaluate_522(ctx),
            523 => self.evaluate_523(ctx),
            524 => self.evaluate_524(ctx),
            525 => self.evaluate_525(ctx),
            526 => self.evaluate_526(ctx),
            527 => self.evaluate_527(ctx),
            528 => self.evaluate_528(ctx),
            529 => self.evaluate_529(ctx),
            530 => self.evaluate_530(ctx),
            531 => self.evaluate_531(ctx),
            532 => self.evaluate_532(ctx),
            533 => self.evaluate_533(ctx),
            534 => self.evaluate_534(ctx),
            912 => self.evaluate_912(ctx),
            913 => self.evaluate_913(ctx),
            914 => self.evaluate_914(ctx),
            915 => self.evaluate_915(ctx),
            930 => self.evaluate_930(ctx),
            931 => self.evaluate_931(ctx),
            932 => self.evaluate_932(ctx),
            933 => self.evaluate_933(ctx),
            937 => self.evaluate_937(ctx),
            939 => self.evaluate_939(ctx),
            940 => self.evaluate_940(ctx),
            947 => self.evaluate_947(ctx),
            950 => self.evaluate_950(ctx),
            951 => self.evaluate_951(ctx),
            960 => self.evaluate_960(ctx),
            963 => self.evaluate_963(ctx),
            964 => self.evaluate_964(ctx),
            965 => self.evaluate_965(ctx),
            969 => self.evaluate_969(ctx),
            2001 => self.evaluate_2001(ctx),
            2002 => self.evaluate_2002(ctx),
            2004 => self.evaluate_2004(ctx),
            2005 => self.evaluate_2005(ctx),
            2006 => self.evaluate_2006(ctx),
            2007 => self.evaluate_2007(ctx),
            _ => ConditionResult::Unknown,
        }
    }

    fn is_external(&self, condition: u32) -> bool {
        self.external_conditions.contains(&condition)
    }
    fn is_known(&self, condition: u32) -> bool {
        matches!(
            condition,
            1 | 2
                | 5
                | 6
                | 7
                | 8
                | 9
                | 10
                | 11
                | 12
                | 13
                | 14
                | 15
                | 21
                | 22
                | 24
                | 25
                | 26
                | 27
                | 29
                | 30
                | 31
                | 32
                | 33
                | 34
                | 36
                | 37
                | 41
                | 42
                | 43
                | 44
                | 46
                | 47
                | 48
                | 49
                | 50
                | 53
                | 54
                | 55
                | 56
                | 57
                | 58
                | 59
                | 61
                | 62
                | 490
                | 491
                | 494
                | 501
                | 502
                | 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
                | 912
                | 913
                | 914
                | 915
                | 930
                | 931
                | 932
                | 933
                | 937
                | 939
                | 940
                | 947
                | 950
                | 951
                | 960
                | 963
                | 964
                | 965
                | 969
                | 2001
                | 2002
                | 2004
                | 2005
                | 2006
                | 2007
        )
    }
}

impl UtiltsConditionEvaluatorFV2504 {
    /// [8] Rechenschrittidentifikator aus einem SG8 SEQ+Z37 (Bestandteil des Rechenschritts) DE1050 desselben SG5 IDE+24 und derselben Zeitraum-ID wie bei diesem SG8
    // REVIEW: Validates that RFF+Z23 references in SG8 SEQ+Z37 instances point to existing SEQ+Z37 DE1050 values. Follows the Example 27 pattern with SG5/SG8 group path. The Zeitraum-ID same-scope constraint and same-SG5 IDE+24 scoping are not fully enforced — cross-SG5 step IDs could be accepted — but within a single-transaction UTILTS message this is typically equivalent. RFF+Z23 is the standard Rechenschrittidentifikator reference qualifier based on Example 27. (medium confidence)
    fn evaluate_8(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
        let mut valid_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
            for seq in &seq_segs {
                if seq
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z37")
                {
                    if let Some(val) = seq.elements.get(1).and_then(|e| e.first()) {
                        if !val.is_empty() {
                            valid_ids.insert(val.clone());
                        }
                    }
                }
            }
        }
        if valid_ids.is_empty() {
            return ConditionResult::Unknown;
        }
        for i in 0..sg8_count {
            let rff_segs = nav.find_segments_in_group("RFF", &["SG5", "SG8"], i);
            for rff in &rff_segs {
                if rff
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z23")
                {
                    if let Some(ref_val) = rff.elements.first().and_then(|e| e.get(1)) {
                        if !ref_val.is_empty() && !valid_ids.contains(ref_val) {
                            return ConditionResult::False;
                        }
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [9] Der hier angegebene Rechenschrittidentifikator darf nicht identisch mit dem Rechenschrittidentifikator aus diesem SG8 SEQ+Z37 DE1050 sein
    // REVIEW: Checks that within each SG8 SEQ+Z37 instance, the RFF+Z23 reference value does not equal the current SG8's own SEQ DE1050 Rechenschrittidentifikator (no self-reference). Iterates all SG8 instances globally and returns False on first self-referential cycle detected. (medium confidence)
    fn evaluate_9(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
            let own_id = seq_segs
                .iter()
                .find(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z37")
                })
                .and_then(|s| s.elements.get(1))
                .and_then(|e| e.first())
                .filter(|v| !v.is_empty())
                .cloned();
            let Some(own_id) = own_id else {
                continue;
            };
            let rff_segs = nav.find_segments_in_group("RFF", &["SG5", "SG8"], i);
            for rff in &rff_segs {
                if rff
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z23")
                {
                    if let Some(ref_val) = rff.elements.first().and_then(|e| e.get(1)) {
                        if ref_val == &own_id {
                            return ConditionResult::False;
                        }
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [11] Wenn in SG8 SEQ+Z37 SG9 CCI+++Z86 CAV+Z69/Z70 (Addition / Subtraktion) vorhanden, darf es in dem Vorgang beliebig viele weitere SG8 SEQ+Z37 mit identischem Rechenschrittidentifikator mit derselben ...
    // REVIEW: When multiple SG8 SEQ+Z37 share the same Rechenschrittidentifikator (duplicates), all operator CAV codes across those instances must be exclusively Z69 (Addition) or Z70 (Subtraktion). Navigates SG9 children of each SG8 to collect operator codes, groups by step ID, and checks the constraint for duplicates. Zeitraum-ID same-scope matching is not enforced due to API limitations — treats global step_id grouping as approximation. (medium confidence)
    fn evaluate_11(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
        if sg8_count == 0 {
            return ConditionResult::Unknown;
        }
        // Map step_id -> (instance_count, all_operator_codes_across_all_instances)
        let mut step_data: std::collections::HashMap<String, (usize, Vec<String>)> =
            std::collections::HashMap::new();
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
            let step_id = seq_segs
                .iter()
                .find(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z37")
                })
                .and_then(|s| s.elements.get(1))
                .and_then(|e| e.first())
                .filter(|v| !v.is_empty())
                .cloned();
            let Some(step_id) = step_id else {
                continue;
            };
            let sg9_count = nav.child_group_instance_count(&["SG5", "SG8"], i, "SG9");
            let mut ops: Vec<String> = Vec::new();
            for j in 0..sg9_count {
                let cavs = nav.find_segments_in_child_group("CAV", &["SG5", "SG8"], i, "SG9", j);
                for cav in &cavs {
                    if let Some(code) = cav.elements.first().and_then(|e| e.first()) {
                        if matches!(code.as_str(), "Z69" | "Z70" | "Z80" | "Z81" | "Z82" | "Z83") {
                            ops.push(code.clone());
                        }
                    }
                }
            }
            let entry = step_data.entry(step_id).or_insert((0, Vec::new()));
            entry.0 += 1;
            entry.1.extend(ops);
        }
        // Rule: for any step_id with duplicate SG8 instances, ALL operators must be Z69 or Z70
        for (_step_id, (count, operators)) in &step_data {
            if *count > 1 && operators.iter().any(|op| op != "Z69" && op != "Z70") {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [12] Wenn in SG8 SEQ+Z37 SG9 CCI+++Z86 CAV+Z83 (Positivwert) vorhanden, darf es in dem Vorgang keine weitere SG8 SEQ+Z37 mit identischem Rechenschrittidentifikator und derselben Zeitraum-ID geben
    // REVIEW: When a calculation step SG8 SEQ+Z37 contains the Z83 (Positivwert) operator in its SG9 CAV, no other SG8 SEQ+Z37 may share the same Rechenschrittidentifikator within the Vorgang. Groups step IDs by count and checks that any step with Z83 appears exactly once. Zeitraum-ID scoping approximated by global step_id grouping. (medium confidence)
    fn evaluate_12(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
        if sg8_count == 0 {
            return ConditionResult::Unknown;
        }
        // Map step_id -> (instance_count, has_z83_operator)
        let mut step_data: std::collections::HashMap<String, (usize, bool)> =
            std::collections::HashMap::new();
        for i in 0..sg8_count {
            let seq_segs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
            let step_id = seq_segs
                .iter()
                .find(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z37")
                })
                .and_then(|s| s.elements.get(1))
                .and_then(|e| e.first())
                .filter(|v| !v.is_empty())
                .cloned();
            let Some(step_id) = step_id else {
                continue;
            };
            let sg9_count = nav.child_group_instance_count(&["SG5", "SG8"], i, "SG9");
            let mut has_z83 = false;
            for j in 0..sg9_count {
                let cavs = nav.find_segments_in_child_group("CAV", &["SG5", "SG8"], i, "SG9", j);
                if cavs.iter().any(|c| {
                    c.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z83")
                }) {
                    has_z83 = true;
                }
            }
            let entry = step_data.entry(step_id).or_insert((0, false));
            entry.0 += 1;
            entry.1 |= has_z83;
        }
        // Rule: if Z83 (Positivwert) operator is present for a step_id, that step_id must be unique
        for (_step_id, (count, has_z83)) in &step_data {
            if *has_z83 && *count > 1 {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [25] Wenn MP-ID in SG2 NAD+MR (Nachrichtenempfänger) in der Rolle LF
    /// EXTERNAL: Requires context from outside the message.
    fn evaluate_25(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("recipient_is_lf")
    }

    /// [26] sofern per ORDERS reklamiert
    /// EXTERNAL: Requires context from outside the message.
    // REVIEW: Cannot be determined from EDIFACT message content alone — requires external knowledge of whether a prior ORDERS message was used to make a claim. Depends on business process context outside the current message. (medium confidence)
    fn evaluate_26(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("claimed_via_orders")
    }

    /// [37] Wenn ein Gültigkeitsende bereits angegeben werden kann.
    /// EXTERNAL: Requires context from outside the message.
    // REVIEW: Whether a validity end date can already be specified is an organizational business decision at message creation time. Checking DTM+Z35 presence would be circular (condition guards whether to include that very field). Must be resolved from business context external to the message. (medium confidence)
    fn evaluate_37(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("validity_end_known")
    }

    /// [42] Der in diesem Datenlement angegebene Code der Schaltzeitdefinition muss innerhalb eines Vorgangs (IDE) eindeutig sein.
    // REVIEW: Uniqueness of Schaltzeitdefinition codes within an IDE (SG5 group). The only Z44-keyed element in the provided SG8 schema is DTM+Z44 (Schaltzeitänderungszeitpunkt), so uniqueness is enforced on the DTM value within each SG5 instance. Medium confidence because the schema reference only shows DTM segments for SG8 — the actual 'Code' data element could reside in a CCI/SEQ segment not shown here. (medium confidence)
    fn evaluate_42(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg5_count = nav.group_instance_count(&["SG5"]);
        for i in 0..sg5_count {
            let sg8_count = nav.child_group_instance_count(&["SG5"], i, "SG8");
            let mut seen = std::collections::HashSet::new();
            for j in 0..sg8_count {
                let dtms = nav.find_segments_in_child_group("DTM", &["SG5"], i, "SG8", j);
                for dtm in &dtms {
                    if dtm
                        .elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z44")
                    {
                        if let Some(val) = dtm.elements.first().and_then(|e| e.get(1)) {
                            if !val.is_empty() && !seen.insert(val.clone()) {
                                return ConditionResult::False;
                            }
                        }
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [43] Der in diesem Datenlement angegebene Code der Leistungskurvendefinition muss innerhalb eines Vorgangs (IDE) eindeutig sein.
    // REVIEW: Uniqueness of Leistungskurvendefinition codes within an IDE (SG5 group). Mirrors condition 42 but targets DTM+Z45 (Leistungskurvenänderungszeitpunkt). Same caveat: the actual 'Code' element might live in a CCI/SEQ segment absent from the provided schema reference — medium confidence. (medium confidence)
    fn evaluate_43(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg5_count = nav.group_instance_count(&["SG5"]);
        for i in 0..sg5_count {
            let sg8_count = nav.child_group_instance_count(&["SG5"], i, "SG8");
            let mut seen = std::collections::HashSet::new();
            for j in 0..sg8_count {
                let dtms = nav.find_segments_in_child_group("DTM", &["SG5"], i, "SG8", j);
                for dtm in &dtms {
                    if dtm
                        .elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z45")
                    {
                        if let Some(val) = dtm.elements.first().and_then(|e| e.get(1)) {
                            if !val.is_empty() && !seen.insert(val.clone()) {
                                return ConditionResult::False;
                            }
                        }
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [56] Wenn dieses DTM+Z25 (Verwendung der Daten ab) im SG6 RFF (Verwendungszeitraum der Daten) mit der Zeitraum ID "1" im DE1156 ist, muss das Datum der darauffolgende oder ein älterer Tag 0:00 Uhr deut...
    // REVIEW: Checks that DTM+Z25 (Verwendung der Daten ab) in any SG6 whose associated RFF has Zeitraum-ID '1' in DE1156 (C506 component [0][2]) is at most the day following DTM+137 (message date) at 0:00. Date arithmetic is implemented inline without external crates. Timezone nuance ('0:00 Uhr deutscher Zeit' = CET/CEST midnight, not UTC midnight) is approximated — threshold uses CCYYMMDD+10000 of the next calendar day in UTC, which introduces up to 2-hour margin of error around DST transitions. The Zeitraum-ID '1' is checked at elements[0][2] per the explicit DE1156 reference in the condition text. (medium confidence)
    fn evaluate_56(&self, ctx: &EvaluationContext) -> ConditionResult {
        let msg_dtm_segs = ctx.find_segments_with_qualifier("DTM", 0, "137");
        let msg_date_val = match msg_dtm_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
        {
            Some(v) => v.clone(),
            None => return ConditionResult::Unknown,
        };
        if msg_date_val.len() < 8 {
            return ConditionResult::Unknown;
        }
        let year: u32 = match msg_date_val[..4].parse::<u32>() {
            Ok(v) => v,
            Err(_) => return ConditionResult::Unknown,
        };
        let month: u32 = match msg_date_val[4..6].parse::<u32>() {
            Ok(v) => v,
            Err(_) => return ConditionResult::Unknown,
        };
        let day: u32 = match msg_date_val[6..8].parse::<u32>() {
            Ok(v) => v,
            Err(_) => return ConditionResult::Unknown,
        };
        let days_in_month: u32 = match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => {
                if year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) {
                    29
                } else {
                    28
                }
            }
            _ => return ConditionResult::Unknown,
        };
        let (ny, nm, nd): (u32, u32, u32) = if day >= days_in_month {
            if month == 12 {
                (year + 1, 1, 1)
            } else {
                (year, month + 1, 1)
            }
        } else {
            (year, month, day + 1)
        };
        let threshold = format!("{:04}{:02}{:02}0000", ny, nm, nd);
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg5_count = nav.group_instance_count(&["SG5"]);
        for i in 0..sg5_count {
            let sg6_count = nav.child_group_instance_count(&["SG5"], i, "SG6");
            for j in 0..sg6_count {
                let rffs = nav.find_segments_in_child_group("RFF", &["SG5"], i, "SG6", j);
                let has_zeitraum_1 = rffs.iter().any(|rff| {
                    rff.elements
                        .first()
                        .and_then(|e| e.get(2))
                        .is_some_and(|v| v == "1")
                });
                if has_zeitraum_1 {
                    let dtms = nav.find_segments_in_child_group("DTM", &["SG5"], i, "SG6", j);
                    for dtm in &dtms {
                        if dtm
                            .elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z25")
                        {
                            if let Some(dtm_val) = dtm.elements.first().and_then(|e| e.get(1)) {
                                if dtm_val.as_str() > threshold.as_str() {
                                    return ConditionResult::False;
                                }
                            }
                        }
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [57] Wenn dieses DTM+Z25 (Verwendung der Daten ab) nicht im SG6 RFF+Z49/ Z53 (Verwendungszeitraum der Daten: Gültige Daten/ Keine Daten) mit der Zeitraum ID "1" im DE1156 ist, muss das Datum dem DTM+Z2...
    // REVIEW: Complex cross-SG6 ordering condition: for each SG6 with Zeitraum-ID != 1, its DTM+Z25 must equal the DTM+Z26 of the SG6 with the next lower Zeitraum-ID. Implemented via navigator collecting (id, z25, z26) tuples per SG6 instance, then verifying the sequential boundary constraint. (medium confidence)
    fn evaluate_57(&self, ctx: &EvaluationContext) -> ConditionResult {
        let nav = match ctx.navigator() {
            Some(n) => n,
            None => return ConditionResult::Unknown,
        };
        let sg6_path: &[&str] = &["SG5", "SG6"];
        let sg6_count = nav.group_instance_count(sg6_path);
        if sg6_count == 0 {
            return ConditionResult::Unknown;
        }
        // Build (zeitraum_id, dtm_z25, dtm_z26) per SG6
        let mut entries: Vec<(u32, Option<String>, Option<String>)> = Vec::new();
        for i in 0..sg6_count {
            let rff_segs = nav.find_segments_in_group("RFF", sg6_path, i);
            let mut zeitraum_id: Option<u32> = None;
            for rff in &rff_segs {
                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(id_str) = rff.elements.first().and_then(|e| e.get(2)) {
                        if let Ok(id) = id_str.parse::<u32>() {
                            zeitraum_id = Some(id);
                        }
                    }
                }
            }
            let id = match zeitraum_id {
                Some(id) => id,
                None => continue,
            };
            let dtm_segs = nav.find_segments_in_group("DTM", sg6_path, i);
            let mut dtm_z25: Option<String> = None;
            let mut dtm_z26: Option<String> = None;
            for dtm in &dtm_segs {
                let qual = dtm
                    .elements
                    .first()
                    .and_then(|e| e.first())
                    .map(|s| s.as_str());
                let val = dtm
                    .elements
                    .first()
                    .and_then(|e| e.get(1))
                    .filter(|v| !v.is_empty())
                    .cloned();
                match qual {
                    Some("Z25") => dtm_z25 = val,
                    Some("Z26") => dtm_z26 = val,
                    _ => {}
                }
            }
            entries.push((id, dtm_z25, dtm_z26));
        }
        // For non-ID-1 entries, check DTM+Z25 == DTM+Z26 of next-lower Zeitraum-ID
        for (id, dtm_z25, _) in &entries {
            if *id == 1 {
                continue;
            }
            let current_z25 = match dtm_z25 {
                Some(v) => v,
                None => continue,
            };
            let next_lower = entries
                .iter()
                .filter(|(other_id, _, _)| *other_id < *id)
                .map(|(other_id, _, _)| *other_id)
                .max();
            let lower_id = match next_lower {
                Some(lid) => lid,
                None => return ConditionResult::Unknown,
            };
            match entries.iter().find(|(eid, _, _)| *eid == lower_id) {
                Some((_, _, Some(lower_z26))) => {
                    if current_z25 != lower_z26 {
                        return ConditionResult::False;
                    }
                }
                Some((_, _, None)) => return ConditionResult::Unknown,
                None => return ConditionResult::Unknown,
            }
        }
        ConditionResult::True
    }

    /// [490] wenn Wert in diesem DE, an der Stelle CCYYMMDD ein Datum aus dem angegeben Zeitraum der Tabelle Kapitel 3.5 „Prozesszeitpunkt bei MESZ mit UTC“ ist
    fn evaluate_490(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_segs = ctx.find_segments_with_qualifier("DTM", 0, "137");
        match dtm_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
        {
            Some(val) => is_mesz_utc(val),
            None => ConditionResult::False, // segment absent → condition not applicable
        }
    }

    /// [491] wenn Wert in diesem DE, an der Stelle CCYYMMDD ein Datum aus dem angegeben Zeitraum der Tabelle Kapitel 3.6 „Prozesszeitpunkt bei MEZ mit UTC“ ist
    fn evaluate_491(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_segs = ctx.find_segments_with_qualifier("DTM", 0, "137");
        match dtm_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
        {
            Some(val) => is_mez_utc(val),
            None => ConditionResult::False, // segment absent → condition not applicable
        }
    }

    /// [1] Nur MP-ID aus Sparte Strom
    /// EXTERNAL: Requires context from outside the message.
    // REVIEW: Whether the MP-ID belongs to the electricity sector (Sparte Strom) cannot be determined from the EDIFACT message alone — requires external market participant registry lookup. (medium confidence)
    fn evaluate_1(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("mp_id_is_strom_sector")
    }

    /// [2] Wenn SG5 STS+Z23+Z34 (Berechnungsformel muss beim Absender angefragt werden) in einem SG5 IDE vorhanden
    fn evaluate_2(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_qualified_value("STS", 0, "Z23", 1, 0, &["Z34"], &["SG5"])
    }

    /// [5] Wenn das SG8 RFF+Z19 (Referenz auf eine Messlokation) in derselben SG8 SEQ+Z37 nicht vorhanden
    fn evaluate_5(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_qualifier_without("RFF", 0, "Z19", "SEQ", 0, "Z37", &["SG4", "SG8"])
    }

    /// [6] Wenn das SG8 RFF+Z23 (Referenz auf Rechenschritt) in derselben SG8 SEQ+Z37 nicht vorhanden
    fn evaluate_6(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_qualifier_without("RFF", 0, "Z23", "SEQ", 0, "Z37", &["SG4", "SG8"])
    }

    /// [7] Wenn in derselben SG8 SEQ+Z37 das SG8 RFF+Z19 (Referenz auf eine Messlokation) vorhanden
    fn evaluate_7(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z37"], "RFF", 0, 0, &["Z19"], &["SG4", "SG8"])
    }

    /// [10] wenn vorhanden
    fn evaluate_10(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // "wenn vorhanden" — conditional modifier meaning the associated rule applies
        // only when the element is present. As a standalone boolean predicate this
        // always evaluates to True: the condition itself imposes no additional
        // constraint beyond the field's own optionality.
        ConditionResult::True
    }

    /// [13] Wenn in SG8 SEQ+Z37 SG9 CCI+++Z86 CAV+Z80/Z81 (Divisor / Dividend) vorhanden, muss in diesem Vorgang genau eine zweite SG8 SEQ+Z37 mit identischen Rechenschrittidentifikator und derselben Zeitraum-...
    // REVIEW: Complex cross-SG8 pairing invariant: for each Z80 (Divisor) or Z81 (Dividend) operator in SG9 CCI+Z86, there must be exactly one matching SG8 with the same Rechenschrittidentifikator (SEQ.elements[1][0]) and Zeitraum-ID (RFF+Z46) that carries the complementary operator. Requires full navigator traversal. (medium confidence)
    fn evaluate_13(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let nav = match ctx.navigator() {
                Some(n) => n,
                None => return ConditionResult::Unknown,
            };

            let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
            // Collect (rs_id, zt_id, operator) for all Z37 SG8s that have CCI+++Z86 and CAV+Z80/Z81
            let mut div_instances: Vec<(String, String, String)> = Vec::new();

            for i in 0..sg8_count {
                let seqs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
                let seq_z37 = seqs.iter().find(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z37")
                });
                let seq_z37 = match seq_z37 {
                    Some(s) => s,
                    None => continue,
                };

                let rs_id = seq_z37
                    .elements
                    .get(1)
                    .and_then(|e| e.first())
                    .cloned()
                    .unwrap_or_default();

                let rffs = nav.find_segments_in_group("RFF", &["SG5", "SG8"], i);
                let zt_id = rffs
                    .iter()
                    .find(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z46")
                    })
                    .and_then(|s| s.elements.first())
                    .and_then(|e| e.get(1))
                    .cloned()
                    .unwrap_or_default();

                let sg9_count = nav.child_group_instance_count(&["SG5", "SG8"], i, "SG9");
                for j in 0..sg9_count {
                    let ccis =
                        nav.find_segments_in_child_group("CCI", &["SG5", "SG8"], i, "SG9", j);
                    let has_z86 = ccis.iter().any(|s| {
                        s.elements
                            .get(2)
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z86")
                    });
                    if !has_z86 {
                        continue;
                    }
                    let cavs =
                        nav.find_segments_in_child_group("CAV", &["SG5", "SG8"], i, "SG9", j);
                    for cav in &cavs {
                        let op = cav
                            .elements
                            .first()
                            .and_then(|e| e.first())
                            .map(|s| s.as_str());
                        if matches!(op, Some("Z80") | Some("Z81")) {
                            div_instances.push((
                                rs_id.clone(),
                                zt_id.clone(),
                                op.unwrap().to_string(),
                            ));
                        }
                    }
                }
            }

            if div_instances.is_empty() {
                return ConditionResult::Unknown;
            }

            // Each Z80 must have exactly one Z81 counterpart with same IDs, and vice versa
            for (rs_id, zt_id, op) in &div_instances {
                let counterpart = if op == "Z80" { "Z81" } else { "Z80" };
                let count = div_instances
                    .iter()
                    .filter(|(rs, zt, o)| rs == rs_id && zt == zt_id && o == counterpart)
                    .count();
                if count != 1 {
                    return ConditionResult::False;
                }
            }

            ConditionResult::True
        }
    }

    /// [14] Wenn in SG8 SEQ+Z37 SG9 CCI+++Z86 CAV+Z82 (Faktor) vorhanden, darf es in dem Vorgang beliebig viele weitere SG8 SEQ+Z37 mit identischem Rechenschrittidentifikator und derselben Zeitraum-ID geben, d...
    // REVIEW: When a Z82 (Faktor/Multiplikation) operator is present in a group of SG8s sharing the same Rechenschrittidentifikator and Zeitraum-ID, ALL members of that group must exclusively carry Z82 — no mixing with Z80/Z81. Returns True when this homogeneity constraint holds. (medium confidence)
    fn evaluate_14(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let nav = match ctx.navigator() {
                Some(n) => n,
                None => return ConditionResult::Unknown,
            };

            let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
            // Collect (rs_id, zt_id, operators) for all Z37 SG8s with CCI+++Z86
            let mut instances: Vec<(String, String, Vec<String>)> = Vec::new();

            for i in 0..sg8_count {
                let seqs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
                let seq_z37 = seqs.iter().find(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z37")
                });
                let seq_z37 = match seq_z37 {
                    Some(s) => s,
                    None => continue,
                };

                let rs_id = seq_z37
                    .elements
                    .get(1)
                    .and_then(|e| e.first())
                    .cloned()
                    .unwrap_or_default();

                let rffs = nav.find_segments_in_group("RFF", &["SG5", "SG8"], i);
                let zt_id = rffs
                    .iter()
                    .find(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z46")
                    })
                    .and_then(|s| s.elements.first())
                    .and_then(|e| e.get(1))
                    .cloned()
                    .unwrap_or_default();

                let sg9_count = nav.child_group_instance_count(&["SG5", "SG8"], i, "SG9");
                let mut ops: Vec<String> = Vec::new();
                for j in 0..sg9_count {
                    let ccis =
                        nav.find_segments_in_child_group("CCI", &["SG5", "SG8"], i, "SG9", j);
                    if !ccis.iter().any(|s| {
                        s.elements
                            .get(2)
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z86")
                    }) {
                        continue;
                    }
                    let cavs =
                        nav.find_segments_in_child_group("CAV", &["SG5", "SG8"], i, "SG9", j);
                    for cav in &cavs {
                        if let Some(op) = cav.elements.first().and_then(|e| e.first()) {
                            ops.push(op.clone());
                        }
                    }
                }
                if !ops.is_empty() {
                    instances.push((rs_id, zt_id, ops));
                }
            }

            // Find any (rs_id, zt_id) key that has a Z82 operator
            let z82_keys: Vec<(&str, &str)> = instances
                .iter()
                .filter(|(_, _, ops)| ops.iter().any(|op| op == "Z82"))
                .map(|(rs, zt, _)| (rs.as_str(), zt.as_str()))
                .collect();

            if z82_keys.is_empty() {
                return ConditionResult::Unknown;
            }

            // For each group keyed by (rs_id, zt_id) that has Z82, all operators must be exclusively Z82
            for (rs_id, zt_id) in &z82_keys {
                for (rs, zt, ops) in &instances {
                    if rs.as_str() == *rs_id && zt.as_str() == *zt_id {
                        if ops.iter().any(|op| op != "Z82") {
                            return ConditionResult::False;
                        }
                    }
                }
            }

            ConditionResult::True
        }
    }

    /// [15] Wenn in einem SG5 IDE+24 nur eine SEQ+Z37 mit einer SG8 RFF+Z19 (Messlokation) und der selben Zeitraum-ID vorhanden ist
    // REVIEW: Checks that within the current SG5 (IDE+24) transaction group there is exactly one SG8 that contains both SEQ+Z37 (Bestandteil des Rechenschritts) and RFF+Z19 (Messlokation reference), and that all such matching SG8s reference the same Zeitraum-ID via RFF+Z46. (medium confidence)
    fn evaluate_15(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let nav = match ctx.navigator() {
                Some(n) => n,
                None => return ConditionResult::Unknown,
            };

            let sg8_count = nav.group_instance_count(&["SG5", "SG8"]);
            let mut matching_count = 0usize;
            let mut first_zt_id: Option<String> = None;

            for i in 0..sg8_count {
                let seqs = nav.find_segments_in_group("SEQ", &["SG5", "SG8"], i);
                let has_z37 = seqs.iter().any(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z37")
                });
                if !has_z37 {
                    continue;
                }

                let rffs = nav.find_segments_in_group("RFF", &["SG5", "SG8"], i);
                let has_z19 = rffs.iter().any(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|v| v == "Z19")
                });
                if !has_z19 {
                    continue;
                }

                // Verify Zeitraum-ID consistency across all matching instances
                let zt_id = rffs
                    .iter()
                    .find(|s| {
                        s.elements
                            .first()
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == "Z46")
                    })
                    .and_then(|s| s.elements.first())
                    .and_then(|e| e.get(1))
                    .cloned();

                if let Some(ref zt) = zt_id {
                    match &first_zt_id {
                        None => first_zt_id = Some(zt.clone()),
                        Some(first) => {
                            if first != zt {
                                return ConditionResult::False;
                            }
                        }
                    }
                }

                matching_count += 1;
            }

            ConditionResult::from(matching_count == 1)
        }
    }

    /// [21] Wenn in dieser CAV+ZD3 der Wert im DE7110 mit Z32 (sonstiger Zählzeitdefinitionstyp) vorhanden ist
    fn evaluate_21(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.has_qualified_value("CAV", 0, "ZD3", 0, 3, &["Z32"])
    }

    /// [22] Wenn MP-ID in SG2 NAD+MS (Nachrichtenabsender) in der Rolle NB
    /// EXTERNAL: Requires context from outside the message.
    // REVIEW: Whether the MP-ID in NAD+MS (Nachrichtenabsender) holds the role of NB (Netzbetreiber) cannot be determined from the EDIFACT message alone — requires external market participant role registry. (medium confidence)
    fn evaluate_22(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("sender_is_nb")
    }

    /// [24] Wenn SG5 STS+Z36+Z45 (Definitionen werden verwendet) vorhanden
    fn evaluate_24(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.has_qualified_value("STS", 0, "Z36", 1, 0, &["Z45"])
    }

    /// [27] Wenn in SG9 CAV+ZD4+Z26 (keine Verwendung des Hochlastzeitfensters) vorhanden
    fn evaluate_27(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.has_qualified_value("CAV", 0, "ZD4", 0, 3, &["Z26"])
    }

    /// [29] Wenn in SG8 SEQ+Z43 DTM+Z33 (Zählzeitänderungszeitpunkt) im DE2379 der Code 303 vorhanden
    // REVIEW: In the same SG8, SEQ+Z43 (Zählzeitdefinition) must be present and DTM must have format code 303 at elements[0][2]. In a SEQ+Z43 SG8, the only DTM present is DTM+Z33, so checking format code 303 without qualifying by Z33 is safe. (medium confidence)
    fn evaluate_29(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z43"], "DTM", 0, 2, &["303"], &["SG5", "SG8"])
    }

    /// [30] Der Wert von CCYY in diesem DE muss genau um eins höher sein, als der Wert CCYY des SG5 DTM+Z34 (Gültigkeitsbeginn) DE2380
    // REVIEW: Compares CCYY of DTM+Z35 (Gültigkeitsende) to CCYY of DTM+Z34 (Gültigkeitsbeginn), checking that the end year is exactly start year + 1. 'Diesem DE' most plausibly refers to DTM+Z35 since it is the natural counterpart to DTM+Z34 and its year is constrained relative to Z34. (medium confidence)
    fn evaluate_30(&self, ctx: &EvaluationContext) -> ConditionResult {
        // CCYY in this DE must be exactly one higher than CCYY of SG5 DTM+Z34 DE2380
        // This applies to DTM+Z35 (Gültigkeitsende) whose year must be Z34 year + 1
        let z34_segs = ctx.find_segments_with_qualifier("DTM", 0, "Z34");
        let z35_segs = ctx.find_segments_with_qualifier("DTM", 0, "Z35");
        let z34_year = z34_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
            .and_then(|v| v.get(..4))
            .and_then(|y| y.parse::<u32>().ok());
        let this_year = z35_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
            .and_then(|v| v.get(..4))
            .and_then(|y| y.parse::<u32>().ok());
        match (z34_year, this_year) {
            (Some(start), Some(end)) => ConditionResult::from(end == start + 1),
            _ => ConditionResult::Unknown,
        }
    }

    /// [31] Wenn im DE2379 dieses Segments der Code 303 vorhanden
    // REVIEW: Checks if any DTM segment has format code 303 at elements[0][2] (DE2379). Applies to DTM+Z33/Z44/Z45 which can carry format codes 303 or 401. Message-wide check is sufficient since these are the only DTMs with variable format codes. (medium confidence)
    fn evaluate_31(&self, ctx: &EvaluationContext) -> ConditionResult {
        ConditionResult::from(ctx.find_segments("DTM").iter().any(|s| {
            s.elements
                .first()
                .and_then(|e| e.get(2))
                .map(|v| v == "303")
                .unwrap_or(false)
        }))
    }

    /// [32] Der Zeitpunkt in diesem DE muss ≥ dem Zeitpunkt aus dem DE2380 des Gültigkeitsbeginn der ausgerollten Definition (SG5 DTM+Z34) sein
    // REVIEW: Validates that SG8 change timestamps (Z33/Z44/Z45) are >= the SG5 DTM+Z34 validity start. 'Diesem DE' refers to the change-point timestamp being validated in SG8. First 12 characters (YYYYMMDDHHmm) are used for consistent lexicographic date comparison in format 303. (medium confidence)
    fn evaluate_32(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Timestamp in this DE >= DTM+Z34 (Gültigkeitsbeginn der ausgerollten Definition)
        // Applies to SG8 change-point timestamps (Z33 Zählzeit, Z44 Schaltzeit, Z45 Leistungskurve)
        let z34_segs = ctx.find_segments_with_qualifier("DTM", 0, "Z34");
        let z34_value = match z34_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
        {
            Some(v) => v.clone(),
            None => return ConditionResult::Unknown,
        };
        let threshold = z34_value.get(..12).unwrap_or(z34_value.as_str());
        for qual in &["Z33", "Z44", "Z45"] {
            let segs = ctx.find_segments_with_qualifier("DTM", 0, qual);
            for seg in &segs {
                if let Some(val) = seg.elements.first().and_then(|e| e.get(1)) {
                    let v = val.get(..12).unwrap_or(val);
                    if v < threshold {
                        return ConditionResult::False;
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [33] Der Zeitpunkt in diesem DE muss ≤ dem Zeitpunkt aus dem DE2380 des Gültigkeitsende der ausgerollten Definition (SG5 DTM+Z35) sein
    // REVIEW: Validates that SG8 change timestamps (Z33/Z44/Z45) are <= the SG5 DTM+Z35 validity end. Symmetric counterpart to condition 32. First 12 characters used for format-303 string comparison. (medium confidence)
    fn evaluate_33(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Timestamp in this DE <= DTM+Z35 (Gültigkeitsende der ausgerollten Definition)
        // Applies to SG8 change-point timestamps (Z33 Zählzeit, Z44 Schaltzeit, Z45 Leistungskurve)
        let z35_segs = ctx.find_segments_with_qualifier("DTM", 0, "Z35");
        let z35_value = match z35_segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
        {
            Some(v) => v.clone(),
            None => return ConditionResult::Unknown,
        };
        let threshold = z35_value.get(..12).unwrap_or(z35_value.as_str());
        for qual in &["Z33", "Z44", "Z45"] {
            let segs = ctx.find_segments_with_qualifier("DTM", 0, qual);
            for seg in &segs {
                if let Some(val) = seg.elements.first().and_then(|e| e.get(1)) {
                    let v = val.get(..12).unwrap_or(val);
                    if v > threshold {
                        return ConditionResult::False;
                    }
                }
            }
        }
        ConditionResult::True
    }

    /// [34] Wenn im DE2379 dieses Segments der Code 401 vorhanden
    // REVIEW: Checks if any DTM segment has format code 401 at elements[0][2] (DE2379). Counterpart to condition [31] for the 401 format code (point-in-time without timezone vs. UTC offset). (medium confidence)
    fn evaluate_34(&self, ctx: &EvaluationContext) -> ConditionResult {
        ConditionResult::from(ctx.find_segments("DTM").iter().any(|s| {
            s.elements
                .first()
                .and_then(|e| e.get(2))
                .map(|v| v == "401")
                .unwrap_or(false)
        }))
    }

    /// [36] Wenn in SG8 SEQ+Z43 DTM+Z33 (Zählzeitänderungszeitpunkt) im DE2379 der Code 401 vorhanden
    // REVIEW: In the same SG8, SEQ+Z43 (Zählzeitdefinition) must be present and DTM+Z33 must have format code 401 at elements[0][2]. Counterpart to condition [29] for the 401 format code. (medium confidence)
    fn evaluate_36(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z43"], "DTM", 0, 2, &["401"], &["SG5", "SG8"])
    }

    /// [41] Wenn SG8 SEQ+Z42 (Zählzeitdefinition) vorhanden
    fn evaluate_41(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_qualifier("SEQ", 0, "Z42", &["SG5", "SG8"])
    }

    /// [44] Der in diesem Datenlement angegebene Code der Zählzeitdefinition muss innerhalb eines Vorgangs (IDE) eindeutig sein.
    // REVIEW: RFF+Z27 (elements[0][1]) in SG8 holds the Zählzeitdefinition code per the segment reference. Collects all Z27 reference values message-wide and checks for duplicates. Returns True when all codes are distinct (unique), False when a duplicate exists, Unknown when no Z27 segments found. Group navigator would be needed to properly scope to SG5 boundaries — approximated as message-wide. (medium confidence)
    fn evaluate_44(&self, ctx: &EvaluationContext) -> ConditionResult {
        // RFF+Z27 in SG8 holds the Zählzeitdefinition code — must be unique within the IDE (SG5) scope.
        // Approximate with message-wide check: all Z27 values must be distinct.
        let rff_segs = ctx.find_segments("RFF");
        let z27_values: Vec<&str> = rff_segs
            .iter()
            .filter(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|q| q == "Z27")
            })
            .filter_map(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.get(1))
                    .map(|s| s.as_str())
            })
            .collect();
        if z27_values.is_empty() {
            return ConditionResult::Unknown;
        }
        let unique_count: std::collections::HashSet<&str> = z27_values.iter().copied().collect();
        ConditionResult::from(unique_count.len() == z27_values.len())
    }

    /// [46] Wenn in SG8 SEQ+Z73 DTM+Z44 (Schaltzeitänderungszeitpunkt) im DE2379 der Code 303 vorhanden
    fn evaluate_46(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z73"], "DTM", 0, 2, &["303"], &["SG5", "SG8"])
    }

    /// [47] Wenn in SG8 SEQ+Z73 DTM+Z44 (Schaltzeitänderungszeitpunkt) im DE2379 der Code 401 vorhanden
    fn evaluate_47(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z73"], "DTM", 0, 2, &["401"], &["SG5", "SG8"])
    }

    /// [48] Wenn in SG8 SEQ+Z74 DTM+Z45 (Leistungskurvenänderungszeitpunkt) im DE2379 der Code 303 vorhanden
    fn evaluate_48(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z74"], "DTM", 0, 2, &["303"], &["SG5", "SG8"])
    }

    /// [49] Wenn in SG8 SEQ+Z74 DTM+Z45 (Leistungskurvenänderungszeitpunkt) im DE2379 der Code 401 vorhanden
    fn evaluate_49(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.any_group_has_co_occurrence("SEQ", 0, &["Z74"], "DTM", 0, 2, &["401"], &["SG5", "SG8"])
    }

    /// [50] In jedem DE2379 dieses DTM-Segments innerhalb eines IDE+24 (Vorgangs) muss der gleiche Code angegeben werden
    // REVIEW: Checks that all DTM segments in the message use the same DE2379 format code. Full per-IDE+24 scoping would require a navigator, but message-wide consistency is a practical approximation — in well-formed UTILTS messages a single IDE is common. Returns Unknown when no DTMs are found. (medium confidence)
    fn evaluate_50(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let dtms = ctx.find_segments("DTM");
            let format_codes: Vec<&str> = dtms
                .iter()
                .filter_map(|s| s.elements.first()?.get(2).map(|s| s.as_str()))
                .filter(|s| !s.is_empty())
                .collect();
            if format_codes.is_empty() {
                return ConditionResult::Unknown;
            }
            let first = format_codes[0];
            ConditionResult::from(format_codes.iter().all(|&c| c == first))
        }
    }

    /// [53] Wenn im DE3155 in demselben COM der Code EM vorhanden ist
    fn evaluate_53(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let coms = ctx.find_segments("COM");
            ConditionResult::from(coms.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.get(1))
                    .is_some_and(|v| v == "EM")
            }))
        }
    }

    /// [54] Wenn im DE3155 in demselben COM der Code TE / FX / AJ / AL vorhanden ist
    fn evaluate_54(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let coms = ctx.find_segments("COM");
            ConditionResult::from(coms.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.get(1))
                    .is_some_and(|v| matches!(v.as_str(), "TE" | "FX" | "AJ" | "AL"))
            }))
        }
    }

    /// [55] Es ist der Wert einzutragen, der sich aus der Wiederholungshäufigkeit des SG6 RFF+Z49/ Z53 (Verwendungszeitraum der Daten: Gültige Daten/ Keine Daten) ergibt. Bedeutet: Das erste SG6 RFF+Z49/ Z53...
    fn evaluate_55(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: The value to enter is derived from the repetition index of SG6 RFF+Z49/Z53:
        // first occurrence = "1", second = "2", third = "3", etc.
        // This is an informational annotation describing how to populate the data element.
        ConditionResult::True
    }

    /// [58] Wenn im selben SG6 RFF+Z49/ Z53 (Verwendungszeitraum der Daten: Gültige Daten/ Keine Daten) im DE1156 (Zeitraum-ID) eine Zeitraum ID genannt ist, die kleiner ist als in einem anderen SG6 RFF+Z49/ ...
    // REVIEW: True when at least two SG6 RFF+Z49/Z53 instances exist with different DE1156 Zeitraum-IDs (i.e. min < max across all parsed integer IDs). This satisfies the 'smaller than another' ordering condition. Returns False for single-instance or equal-ID cases. (medium confidence)
    fn evaluate_58(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let rffs = ctx.find_segments("RFF");
            let ids: Vec<i64> = rffs
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|q| q == "Z49" || q == "Z53")
                })
                .filter_map(|s| s.elements.first()?.get(2)?.parse::<i64>().ok())
                .collect();
            if ids.len() < 2 {
                return ConditionResult::False;
            }
            let min = *ids.iter().min().unwrap();
            let max = *ids.iter().max().unwrap();
            ConditionResult::from(min < max)
        }
    }

    /// [59] Es ist die Zeitraum-ID vom DE1156 aus einem passenden SG6 RFF+Z49 (Verwendungszeitraum der Daten) einzutragen
    // REVIEW: Cross-group Zeitraum-ID correlation: SG8 RFF+Z46 DE1154 (reference to Zeitraum-ID) must match a DE1156 value from SG6 RFF+Z49 (Verwendungszeitraum der Daten). Collects DE1156 values from all RFF+Z49 instances and checks whether any RFF+Z46 reference value matches. Returns Unknown when either set is empty. (medium confidence)
    fn evaluate_59(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            let rffs = ctx.find_segments("RFF");
            let sg6_ids: Vec<String> = rffs
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|q| q == "Z49")
                })
                .filter_map(|s| s.elements.first()?.get(2).cloned())
                .filter(|v| !v.is_empty())
                .collect();
            if sg6_ids.is_empty() {
                return ConditionResult::Unknown;
            }
            let sg8_refs: Vec<String> = rffs
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .is_some_and(|q| q == "Z46")
                })
                .filter_map(|s| s.elements.first()?.get(1).cloned())
                .filter(|v| !v.is_empty())
                .collect();
            if sg8_refs.is_empty() {
                return ConditionResult::Unknown;
            }
            ConditionResult::from(sg8_refs.iter().any(|r| sg6_ids.contains(r)))
        }
    }

    /// [61] Wenn in einem STS+E01 im DE9013 (Status der Antwort) ein Antwortcode aus dem Cluster Ablehnung vorhanden ist
    // HAND-EDITED: driven by per-EBD cluster data (mako_prozesse).
    // The condition is existential — any Ablehnung STS+E01 → True.
    fn evaluate_61(&self, ctx: &EvaluationContext) -> ConditionResult {
        any_sts_e01_in_cluster(ctx, Cluster::is_ablehnung)
    }

    /// [62] Wenn MP-ID in SG2 NAD+MR (Nachrichtenempfänger) in der Rolle MSB
    /// EXTERNAL: Requires context from outside the message.
    fn evaluate_62(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("recipient_is_msb")
    }

    /// [494] Das hier genannte Datum muss der Zeitpunkt sein, zu dem das Dokument erstellt wurde, oder ein Zeitpunkt, der davor liegt.
    /// EXTERNAL: Requires context from outside the message.
    // REVIEW: The date must be the document creation time or earlier (i.e. not in the future relative to when the document was created). This requires comparing the EDIFACT field value against an external reference timestamp (the actual document creation time or processing time), which is not available within the message segments themselves. (medium confidence)
    fn evaluate_494(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.external.evaluate("document_date_not_in_future")
    }

    /// [501] Hinweis: Verwendung der ID der Marktlokation
    fn evaluate_501(&self, _ctx: &EvaluationContext) -> ConditionResult {
        ConditionResult::True
    }

    /// [502] Hinweis: Verwendung der ID der Messlokation
    fn evaluate_502(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Verwendung der ID der Messlokation — informational note, always applies
        ConditionResult::True
    }

    /// [504] Hinweis: Wert aus BGM+Z55 DE1004 der ORDERS mit der die Reklamation einer Definition erfolgt ist
    fn evaluate_504(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Wert aus BGM+Z55 DE1004 der ORDERS mit der die Reklamation einer Definition erfolgt ist — informational note, always applies
        ConditionResult::True
    }

    /// [505] Hinweis: Jede ausgerollte Zählzeitdefinition ist in einem eigenen IDE anzugeben
    fn evaluate_505(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Jede ausgerollte Zählzeitdefinition ist in einem eigenen IDE anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [506] Hinweis: Zeitpunkt, ab dem die Übersicht der Zählzeitdefinitionen gültig ist
    fn evaluate_506(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Zeitpunkt, ab dem die Übersicht der Zählzeitdefinitionen gültig ist — informational note, always applies
        ConditionResult::True
    }

    /// [507] Hinweis: Es ist die Zeit nach der deutschen gesetzlichen Zeit anzugeben
    fn evaluate_507(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Es ist die Zeit nach der deutschen gesetzlichen Zeit anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [508] Hinweis: Zeitpunkt, ab dem die Übersicht der Schaltzeitdefinitionen gültig ist
    fn evaluate_508(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Zeitpunkt, ab dem die Übersicht der Schaltzeitdefinitionen gültig ist — informational note, always applies
        ConditionResult::True
    }

    /// [509] Hinweis: Zeitpunkt, ab dem die Übersicht der Leistungskurvendefinition gültig ist
    fn evaluate_509(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Zeitpunkt, ab dem die Übersicht der Leistungskurvendefinition gültig ist — informational note, always applies
        ConditionResult::True
    }

    /// [510] Hinweis: Für jeden Zählzeitänderungszeitpunkt (SG8 DTM+Z33) ist diese Sementgruppe einmal anzugeben
    fn evaluate_510(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Für jeden Zählzeitänderungszeitpunkt (SG8 DTM+Z33) ist diese Segmentgruppe einmal anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [511] Hinweis: Der Zählzeitänderungszeitpunkt (SG8DTM+Z33) dieser SG8 darf in keiner anderen SG8 „Zählzeitdefinition“ wiederholt werden
    // REVIEW: Checks that no DTM+Z33 DE2380 value is repeated across SG8 instances. Collects all Z33 qualifier DTM segments and verifies uniqueness. Medium confidence because SG8-scoped iteration falls back to message-wide, which is correct here since each DTM+Z33 belongs to a distinct SG8. (medium confidence)
    fn evaluate_511(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Uniqueness check: no DTM+Z33 value in DE2380 may appear in more than one SG8
        let dtm_z33_segments = ctx.find_segments_with_qualifier("DTM", 0, "Z33");
        let values: Vec<&str> = dtm_z33_segments
            .iter()
            .filter_map(|s| s.elements.first()?.get(1).map(|v| v.as_str()))
            .filter(|v| !v.is_empty())
            .collect();
        if values.is_empty() {
            return ConditionResult::Unknown;
        }
        // Check for duplicates: if all values are unique, condition is satisfied (True)
        let mut seen = std::collections::HashSet::new();
        let all_unique = values.iter().all(|v| seen.insert(*v));
        ConditionResult::from(all_unique)
    }

    /// [512] Hinweis: Wenn der Code 303 im DE2379 des Zählzeitänderungszeitpunkt (SG8 DTM+Z33) genutzt wird, muss genau ein Wert im DE2380 des Zählzeitänderungszeitpunkt (SG8 DTM+Z33) identisch mit dem Wert...
    // REVIEW: When DTM+Z33 uses format code 303 in elements[0][2], exactly one DE2380 value (elements[0][1]) across all Z33 instances must equal the DE2380 value of DTM+Z34 from SG5. Medium confidence due to cross-SG group scoping — the message-wide fallback gives correct semantics here since we're correlating across SG5 and SG8 boundaries. (medium confidence)
    fn evaluate_512(&self, ctx: &EvaluationContext) -> ConditionResult {
        // When format code 303 is used in DTM+Z33 DE2379,
        // exactly one DE2380 value of DTM+Z33 must match the DE2380 of SG5 DTM+Z34
        let dtm_z33_segments = ctx.find_segments_with_qualifier("DTM", 0, "Z33");
        // Only consider Z33 segments that use format code 303
        let z33_303_values: Vec<&str> = dtm_z33_segments
            .iter()
            .filter(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.get(2))
                    .is_some_and(|v| v == "303")
            })
            .filter_map(|s| s.elements.first()?.get(1).map(|v| v.as_str()))
            .filter(|v| !v.is_empty())
            .collect();
        if z33_303_values.is_empty() {
            // No Z33 with format 303 present — condition not applicable
            return ConditionResult::Unknown;
        }
        // Collect DE2380 values from SG5 DTM+Z34
        let dtm_z34_segments = ctx.find_segments_with_qualifier("DTM", 0, "Z34");
        let z34_values: Vec<&str> = dtm_z34_segments
            .iter()
            .filter_map(|s| s.elements.first()?.get(1).map(|v| v.as_str()))
            .filter(|v| !v.is_empty())
            .collect();
        if z34_values.is_empty() {
            return ConditionResult::Unknown;
        }
        // Exactly one Z33 DE2380 value must match a Z34 DE2380 value
        let match_count = z33_303_values
            .iter()
            .filter(|v| z34_values.contains(v))
            .count();
        ConditionResult::from(match_count == 1)
    }

    /// [513] Hinweis: Wenn der Code 401 im DE2379 des Zählzeitänderungszeitpunkt (SG8 DTM+Z33) genutzt wird, muss genau ein Wert = 0000 im DE2380 des Zählzeitänderungszeitpunkt (SG8 DTM+Z33) sein
    fn evaluate_513(&self, ctx: &EvaluationContext) -> ConditionResult {
        // When format code 401 is used in DTM+Z33 DE2379,
        // exactly one DE2380 value must equal "0000"
        let dtm_z33_segments = ctx.find_segments_with_qualifier("DTM", 0, "Z33");
        // Only consider Z33 segments that use format code 401
        let z33_401_values: Vec<&str> = dtm_z33_segments
            .iter()
            .filter(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.get(2))
                    .is_some_and(|v| v == "401")
            })
            .filter_map(|s| s.elements.first()?.get(1).map(|v| v.as_str()))
            .filter(|v| !v.is_empty())
            .collect();
        if z33_401_values.is_empty() {
            // No Z33 with format 401 present — condition not applicable
            return ConditionResult::Unknown;
        }
        // Exactly one value must equal "0000"
        let zero_count = z33_401_values.iter().filter(|v| **v == "0000").count();
        ConditionResult::from(zero_count == 1)
    }

    /// [514] Hinweis: Für jeden Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) ist diese Sementgruppe einmal anzugeben
    fn evaluate_514(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Für jeden Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) ist diese Segmentgruppe einmal anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [515] Hinweis: Kein Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) darf mehrfach vorkommen
    fn evaluate_515(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_z44 = ctx.find_segments_with_qualifier("DTM", 0, "Z44");
        let mut values = std::collections::HashSet::new();
        for seg in &dtm_z44 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let value = c507.get(1).map(|s| s.as_str()).unwrap_or("");
            if !value.is_empty() {
                if !values.insert(value.to_string()) {
                    return ConditionResult::False;
                }
            }
        }
        if dtm_z44.is_empty() {
            ConditionResult::Unknown
        } else {
            ConditionResult::True
        }
    }

    /// [516] Hinweis: Wenn der Code 303 im DE2379 des Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) genutzt wird, muss genau ein Wert im DE2380 des Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) identisch mit dem We...
    // REVIEW: When format code 303 is used in DTM+Z44 DE2379, at least one DTM+Z44 DE2380 value must match a SG5 DTM+Z34 DE2380 value. Cross-group check; medium confidence due to SG5 context dependency. (medium confidence)
    fn evaluate_516(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_z44 = ctx.find_segments_with_qualifier("DTM", 0, "Z44");
        let dtm_z34 = ctx.find_segments_with_qualifier("DTM", 0, "Z34");
        let mut has_303 = false;
        let mut z34_values: std::collections::HashSet<String> = std::collections::HashSet::new();
        for seg in &dtm_z34 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let value = c507.get(1).map(|s| s.clone()).unwrap_or_default();
            if !value.is_empty() {
                z34_values.insert(value);
            }
        }
        for seg in &dtm_z44 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let format_code = c507.get(2).map(|s| s.as_str()).unwrap_or("");
            if format_code == "303" {
                has_303 = true;
                let value = c507.get(1).map(|s| s.as_str()).unwrap_or("");
                if z34_values.contains(value) {
                    return ConditionResult::True;
                }
            }
        }
        if has_303 {
            ConditionResult::False
        } else {
            ConditionResult::Unknown
        }
    }

    /// [517] Hinweis: Wenn der Code 401 im DE2379 des Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) genutzt wird, muss genau ein Wert = 0000 im DE2380 des Schaltzeitänderungszeitpunkt (SG8 DTM+Z44) sein
    fn evaluate_517(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_z44 = ctx.find_segments_with_qualifier("DTM", 0, "Z44");
        let mut has_401 = false;
        for seg in &dtm_z44 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let format_code = c507.get(2).map(|s| s.as_str()).unwrap_or("");
            if format_code == "401" {
                has_401 = true;
                let value = c507.get(1).map(|s| s.as_str()).unwrap_or("");
                if value == "0000" {
                    return ConditionResult::True;
                }
            }
        }
        if has_401 {
            ConditionResult::False
        } else {
            ConditionResult::Unknown
        }
    }

    /// [518] Hinweis: Für jeden Leistungskurvenänderungszeitpunkt (SG8 DTM+Z45) ist diese Sementgruppe einmal anzugeben
    fn evaluate_518(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Für jeden Leistungskurvenänderungszeitpunkt (SG8 DTM+Z45) ist diese Segmentgruppe einmal anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [519] Hinweis: Kein Leistungskurvenänderungszeitpunkt (SG8 DTM+Z45) darf mehrfach vorkommen
    fn evaluate_519(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_z45 = ctx.find_segments_with_qualifier("DTM", 0, "Z45");
        let mut values = std::collections::HashSet::new();
        for seg in &dtm_z45 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let value = c507.get(1).map(|s| s.as_str()).unwrap_or("");
            if !value.is_empty() {
                if !values.insert(value.to_string()) {
                    return ConditionResult::False;
                }
            }
        }
        if dtm_z45.is_empty() {
            ConditionResult::Unknown
        } else {
            ConditionResult::True
        }
    }

    /// [520] Hinweis: Wenn der Code 303 im DE2379 des Leistungskurvenänderungszeitpunkt (SG8 DTM+Z45) genutzt wird, muss genau ein Wert im DE2380 des Leistungskurvenänderungszeitpunkt (SG8 DTM+Z45) identisch ...
    // REVIEW: When format code 303 is used in DTM+Z45 DE2379, at least one DTM+Z45 DE2380 value must match a SG5 DTM+Z34 DE2380 value. Same pattern as 516 but for Z45. (medium confidence)
    fn evaluate_520(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_z45 = ctx.find_segments_with_qualifier("DTM", 0, "Z45");
        let dtm_z34 = ctx.find_segments_with_qualifier("DTM", 0, "Z34");
        let mut has_303 = false;
        let mut z34_values: std::collections::HashSet<String> = std::collections::HashSet::new();
        for seg in &dtm_z34 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let value = c507.get(1).map(|s| s.clone()).unwrap_or_default();
            if !value.is_empty() {
                z34_values.insert(value);
            }
        }
        for seg in &dtm_z45 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let format_code = c507.get(2).map(|s| s.as_str()).unwrap_or("");
            if format_code == "303" {
                has_303 = true;
                let value = c507.get(1).map(|s| s.as_str()).unwrap_or("");
                if z34_values.contains(value) {
                    return ConditionResult::True;
                }
            }
        }
        if has_303 {
            ConditionResult::False
        } else {
            ConditionResult::Unknown
        }
    }

    /// [521] Hinweis: Wenn der Code 401 im DE2379 des Leistungskurvenänderungszeitpunkt (SG8 DTM+Z45)
    // REVIEW: Incomplete condition text but follows the same pattern as 517 (DTM+Z44/401/'0000') but for DTM+Z45. Medium confidence due to incomplete specification. (medium confidence)
    fn evaluate_521(&self, ctx: &EvaluationContext) -> ConditionResult {
        let dtm_z45 = ctx.find_segments_with_qualifier("DTM", 0, "Z45");
        let mut has_401 = false;
        for seg in &dtm_z45 {
            let c507 = match seg.elements.first() {
                Some(e) => e,
                None => continue,
            };
            let format_code = c507.get(2).map(|s| s.as_str()).unwrap_or("");
            if format_code == "401" {
                has_401 = true;
                let value = c507.get(1).map(|s| s.as_str()).unwrap_or("");
                if value == "0000" {
                    return ConditionResult::True;
                }
            }
        }
        if has_401 {
            ConditionResult::False
        } else {
            ConditionResult::Unknown
        }
    }

    /// [522] Hinweis: Jede ausgerollte Schaltzeitdefinition ist in einem eigenen IDE anzugeben
    fn evaluate_522(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Jede ausgerollte Schaltzeitdefinition ist in einem eigenen IDE anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [523] Hinweis: Jede ausgerollte Leistungskurvendefinition ist in einem eigenen IDE anzugeben
    fn evaluate_523(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Jede ausgerollte Leistungskurvendefinition ist in einem eigenen IDE anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [524] Hinweis: Es ist der Code einer Zählzeitdefinition anzugeben
    fn evaluate_524(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Es ist der Code einer Zählzeitdefinition anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [525] Hinweis: Es ist der Code einer Schaltzeitdefinition anzugeben
    fn evaluate_525(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Es ist der Code einer Schaltzeitdefinition anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [526] Hinweis: Es ist der Code einer Leistungskurvendefinition anzugeben
    fn evaluate_526(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Es ist der Code einer Leistungskurvendefinition anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [527] Hinweis: Dieser Code ist anzugeben, wenn es sich um eine einmalig zu übermittelnde Definition handelt
    fn evaluate_527(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Dieser Code ist anzugeben, wenn es sich um eine einmalig zu übermittelnde Definition handelt — informational note, always applies
        ConditionResult::True
    }

    /// [528] Hinweis: Dieser Code ist anzugeben, wenn es sich um eine jährlich zu übermittelnde Definition handelt
    fn evaluate_528(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Dieser Code ist anzugeben, wenn es sich um eine jährlich zu übermittelnde Definition handelt — informational note, always applies
        ConditionResult::True
    }

    /// [529] Hinweis: Verwendung der ID der Netzlokation
    fn evaluate_529(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Verwendung der ID der Netzlokation — informational note, always applies
        ConditionResult::True
    }

    /// [530] Hinweis: Es darf nur eine Information im DE3148 übermittelt werden
    fn evaluate_530(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Es darf nur eine Information im DE3148 übermittelt werden — informational note, always applies
        ConditionResult::True
    }

    /// [531] Hinweis: Für weitere Details siehe Kapitel 4.1 "Übermittlung einer Vielzahl von Berechnungsformeln in einem Vorgang"
    fn evaluate_531(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Für weitere Details siehe Kapitel 4.1 "Übermittlung einer Vielzahl von Berechnungsformeln in einem Vorgang" — informational note, always applies
        ConditionResult::True
    }

    /// [532] Hinweis: Es ist die Zeitraum-ID vom DE1156 aus einem passenden SG6 RFF+Z49/Z53 (Verwendungszeitraum der Daten: "Gültige Daten", "Keine Daten") aus der Übermittlung der Berechnungsformel aus SG6 R...
    // REVIEW: Cross-group Zeitraum-ID matching: collect DE1156 values from SG6 RFF+Z49/Z53 segments, then verify that SG8 RFF+Z46 references (DE1154) point to one of those IDs. Medium confidence because the condition is a hint about correct data linkage across groups, and the exact scoping (per-SG5/SG6 instance vs message-wide) may require navigator-based logic for full correctness. (medium confidence)
    fn evaluate_532(&self, ctx: &EvaluationContext) -> ConditionResult {
        {
            // Collect Zeitraum-IDs (DE1156 = elements[0][2]) from SG6 RFF+Z49 and RFF+Z53
            let rff_segments = ctx.find_segments("RFF");
            let zeitraum_ids: Vec<String> = rff_segments
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.first())
                        .map(|q| q == "Z49" || q == "Z53")
                        .unwrap_or(false)
                })
                .filter_map(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.get(2))
                        .filter(|v| !v.is_empty())
                        .cloned()
                })
                .collect();

            if zeitraum_ids.is_empty() {
                return ConditionResult::Unknown;
            }

            // Check SG8 RFF+Z46 references (DE1154 = elements[0][1]) against collected Zeitraum-IDs
            let rff_z46_segments = ctx.find_segments_with_qualifier("RFF", 0, "Z46");
            if rff_z46_segments.is_empty() {
                return ConditionResult::Unknown;
            }

            let any_match = rff_z46_segments.iter().any(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.get(1))
                    .map(|ref_id| zeitraum_ids.iter().any(|zid| zid == ref_id))
                    .unwrap_or(false)
            });

            ConditionResult::from(any_match)
        }
    }

    /// [533] Hinweis: Für jeden übermittelten Zeitraum aus der Übermittlung der Berechnungsformel ist genau einmal das Segement anzugeben
    fn evaluate_533(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Für jeden übermittelten Zeitraum aus der Übermittlung der Berechnungsformel ist genau einmal das Segment anzugeben — informational note, always applies
        ConditionResult::True
    }

    /// [534] Hinweis: Wert aus SG5 IDE+24 DE7402 mit der die Übermitt-lung der Berechnungsformel erfolgt ist.
    fn evaluate_534(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Wert aus SG5 IDE+24 DE7402 — value comes from the Vorgangsnummer of the Berechnungsformel transmission; informational note, always applies
        ConditionResult::True
    }

    /// [912] Format: Wert kann mit maximal 6 Nachkommastellen angegeben werden
    // REVIEW: Format condition: max 6 decimal places. Applies to a numeric quantity value; QTY is the standard numeric segment in UTILTS. The AHB row context is not in the structure reference but QTY.elements[0][1] is the standard value position. (medium confidence)
    fn evaluate_912(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_max_decimal_places(val, 6))
    }

    /// [913] Format: Mögliche Werte: 1 bis 99999
    // REVIEW: Format condition: value must be in range [1, 99999]. Both bounds checked with validate_numeric and combined with AND logic. Applied to QTY value element as the most common numeric data element in UTILTS. (medium confidence)
    fn evaluate_913(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Format: Mögliche Werte: 1 bis 99999
        let segs = ctx.find_segments("QTY");
        match segs
            .first()
            .and_then(|s| s.elements.first())
            .and_then(|e| e.get(1))
        {
            Some(val) => {
                let ge1 = validate_numeric(val, ">=", 1.0);
                let le99999 = validate_numeric(val, "<=", 99999.0);
                match (ge1, le99999) {
                    (ConditionResult::True, ConditionResult::True) => ConditionResult::True,
                    (ConditionResult::False, _) | (_, ConditionResult::False) => {
                        ConditionResult::False
                    }
                    _ => ConditionResult::Unknown,
                }
            }
            None => ConditionResult::False, // segment absent → condition not applicable
        }
    }

    /// [914] Format: Möglicher Wert: &gt; 0
    // REVIEW: Format condition: value must be strictly greater than 0. Applied to QTY value element; validate_numeric with '>' operator handles this directly. (medium confidence)
    fn evaluate_914(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_numeric(val, ">", 0.0))
    }

    /// [915] Format: Möglicher Wert: ≠ 1
    // REVIEW: Format condition: value must not equal 1. Applied to the QTY quantity value (element[0][1]) as this is the standard numeric data element in UTILTS. Medium confidence because the exact segment/element this applies to is inferred from context rather than stated explicitly. (medium confidence)
    fn evaluate_915(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_numeric(val, "!=", 1.0))
    }

    /// [930] Format: max. 2 Nachkommastellen
    fn evaluate_930(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_max_decimal_places(val, 2))
    }

    /// [931] Format: ZZZ = +00
    fn evaluate_931(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("DTM", 0, 1, validate_timezone_utc)
    }

    /// [932] Format: HHMM = 2200
    fn evaluate_932(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("DTM", 0, 1, |val| validate_hhmm_equals(val, "2200"))
    }

    /// [933] Format: HHMM = 2300
    fn evaluate_933(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("DTM", 0, 1, |val| validate_hhmm_equals(val, "2300"))
    }

    /// [937] Format: keine Nachkommastelle
    fn evaluate_937(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_max_decimal_places(val, 0))
    }

    /// [939] Format: Die Zeichenkette muss die Zeichen @ und . enthalten
    fn evaluate_939(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("COM", 0, 0, validate_email)
    }

    /// [940] Format: Die Zeichenkette muss mit dem Zeichen + beginnen und danach dürfen nur noch Ziffern folgen
    fn evaluate_940(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("COM", 0, 0, validate_phone)
    }

    /// [947] Format: MMDDHHMM = 12312300
    fn evaluate_947(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("DTM", 0, 1, |val| validate_mmddhhmm_equals(val, "12312300"))
    }

    /// [950] Format: Marktlokations-ID
    fn evaluate_950(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check_qualified("LOC", 0, "Z16", 1, 0, validate_malo_id)
    }

    /// [951] Format: Zählpunktbezeichnung
    // REVIEW: Zählpunktbezeichnung (metering point designation) is a 33-character alphanumeric ID. The validate_zahlpunkt helper checks this format. The segment is typically LOC with a metering point qualifier (Z17 for Messlokation or Z19 for SteuerbareRessource in UTILTS). Using both as fallback. (medium confidence)
    fn evaluate_951(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check_qualified("LOC", 0, "Z19", 1, 0, validate_zahlpunkt)
    }

    /// [960] Format: Netzlokations-ID
    // REVIEW: Netzlokations-ID (network location ID) follows the same 11-digit Luhn check digit format as MaLo-ID. LOC+Z18 is the qualifier for Netzlokation in UTILTS messages. (medium confidence)
    fn evaluate_960(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check_qualified("LOC", 0, "Z18", 1, 0, validate_malo_id)
    }

    /// [963] Format: Möglicher Wert: ≤ 100
    // REVIEW: Format condition: value must be <= 100. Applied to QTY segment value (element 0, component 1). Uses validate_numeric helper. (medium confidence)
    fn evaluate_963(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_numeric(val, "<=", 100.0))
    }

    /// [964] Format: HHMM ≥ 0000
    // REVIEW: Format condition: HHMM >= 0000. Combined with condition 965 (HHMM <= 2359), together they validate a valid time range. Using validate_hhmm_range covering both bounds. Applied to DTM segment time value. (medium confidence)
    fn evaluate_964(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("DTM", 0, 1, |val| validate_hhmm_range(val, "0000", "2359"))
    }

    /// [965] Format: HHMM ≤ 2359
    // REVIEW: Format condition: HHMM <= 2359. Paired with condition 964 (HHMM >= 0000). Together they validate a valid HHMM time. Using validate_hhmm_range for both bounds on the DTM segment. (medium confidence)
    fn evaluate_965(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("DTM", 0, 1, |val| validate_hhmm_range(val, "0000", "2359"))
    }

    /// [969] Format: Möglicher Wer: ≤ 1
    // REVIEW: 900-series format condition: 'Möglicher Wert: ≤ 1' means the value must be <= 1. Applied to QTY quantity value (most common numeric value in UTILTS). validate_numeric with "<=" operator handles this. Medium confidence because the exact target segment is inferred from context. (medium confidence)
    fn evaluate_969(&self, ctx: &EvaluationContext) -> ConditionResult {
        ctx.format_check("QTY", 0, 1, |val| validate_numeric(val, "<=", 1.0))
    }

    /// [2001] Segment bzw. Segmentgruppe ist genau einmal anzugeben
    fn evaluate_2001(&self, _ctx: &EvaluationContext) -> ConditionResult {
        // Hinweis: Segment bzw. Segmentgruppe ist genau einmal anzugeben — informational cardinality note, always applies
        ConditionResult::True
    }

    /// [2002] Für jeden Code der Zählzeit aus SG8 SEQ+Z42 (Zählzeitdefinition) SG9 CCI+Z39 (Code der Zählzeitdefinition) sind mindestens zwei Register anzugeben, bei denen in dieser SG8 das SG8 RFF+Z27 mit d...
    // REVIEW: For each CCI+Z39 code (Zählzeitdefinition code, elements[2][0]) found in SG9 groups, at least 2 SG8 instances must have RFF+Z27 (elements[0][0]=Z27, elements[0][1]=code value) matching that code. Uses message-wide scan since navigator API does not expose a simple find-in-group method for non-child groups. (medium confidence)
    fn evaluate_2002(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Collect CCI+Z39 codes from SG9 (Code der Zählzeitdefinition) message-wide
        let cci_segments = ctx.find_segments("CCI");
        let codes: Vec<String> = cci_segments
            .iter()
            .filter(|s| {
                s.elements
                    .first()
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z39")
            })
            .filter_map(|s| s.elements.get(2).and_then(|e| e.first()).cloned())
            .filter(|c| !c.is_empty())
            .collect();
        if codes.is_empty() {
            return ConditionResult::Unknown;
        }
        // For each code, at least 2 SG8 instances must have RFF+Z27 referencing that code
        let rff_z27 = ctx.find_segments_with_qualifier("RFF", 0, "Z27");
        for code in &codes {
            let count = rff_z27
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.get(1))
                        .is_some_and(|v| v == code)
                })
                .count();
            if count < 2 {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [2004] Segment ist genau einmal für jede Zeitraum-ID aus dem DE1156 der SG6 RFF+Z49 (Verwendungszeitraum der Daten: "Gültige Daten") anzugeben
    // REVIEW: For each Zeitraum-ID from SG6 RFF+Z49 DE1156 (elements[0][2]), exactly one SG5 STS must reference it. STS+E01 (Status der Antwort) stores Zeitraum-ID at elements[2][3] (DE9012). STS+Z23 (Status der Berechnungsformel) stores it at elements[2][0] (DE9013). Checks count == 1 for each Zeitraum-ID. (medium confidence)
    fn evaluate_2004(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Collect Zeitraum-IDs from SG6 RFF+Z49 DE1156 (elements[0][2])
        let rff_z49 = ctx.find_segments_with_qualifier("RFF", 0, "Z49");
        if rff_z49.is_empty() {
            return ConditionResult::Unknown;
        }
        let zeitraum_ids: Vec<String> = rff_z49
            .iter()
            .filter_map(|s| s.elements.first().and_then(|e| e.get(2)).cloned())
            .filter(|id| !id.is_empty())
            .collect();
        if zeitraum_ids.is_empty() {
            return ConditionResult::Unknown;
        }
        let sts_segments = ctx.find_segments("STS");
        for zid in &zeitraum_ids {
            // STS+E01: Zeitraum-ID at elements[2][3] (DE9012)
            // STS+Z23: Zeitraum-ID at elements[2][0] (DE9013)
            let count = sts_segments
                .iter()
                .filter(|s| {
                    let qual = s
                        .elements
                        .first()
                        .and_then(|e| e.first())
                        .map(|v| v.as_str())
                        .unwrap_or("");
                    match qual {
                        "E01" => s
                            .elements
                            .get(2)
                            .and_then(|e| e.get(3))
                            .is_some_and(|v| v == zid),
                        "Z23" => s
                            .elements
                            .get(2)
                            .and_then(|e| e.first())
                            .is_some_and(|v| v == zid),
                        _ => false,
                    }
                })
                .count();
            if count != 1 {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [2005] Segment ist genau einmal für jede Zeitraum-ID aus dem DE9012 der SG5 STS+E01 ("Status der Antwort") anzugeben, wenn im selben SG5 STS+E01 im DE9013 der Code A99 ("Sontiges") enthalten ist
    // REVIEW: Finds STS+E01 segments where DE9013 (Code des Prüfschritts, elements[2][0]) = 'A99' (Sonstiges), then collects Zeitraum-IDs from DE9012 (elements[2][3]). For each such ID, checks that exactly one SG8 RFF+Z46 (elements[0][1]) references it, confirming the annotated segment appears exactly once per qualifying Zeitraum-ID. (medium confidence)
    fn evaluate_2005(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Collect Zeitraum-IDs from STS+E01 where DE9013 (elements[2][0]) = A99 (Sonstiges)
        let sts_e01 = ctx.find_segments_with_qualifier("STS", 0, "E01");
        let zeitraum_ids: Vec<String> = sts_e01
            .iter()
            .filter(|s| {
                s.elements
                    .get(2)
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "A99")
            })
            .filter_map(|s| s.elements.get(2).and_then(|e| e.get(3)).cloned())
            .filter(|id| !id.is_empty())
            .collect();
        if zeitraum_ids.is_empty() {
            return ConditionResult::Unknown;
        }
        // For each Zeitraum-ID, exactly one SG8 RFF+Z46 (Referenz auf Zeitraum-ID) must reference it
        let rff_z46 = ctx.find_segments_with_qualifier("RFF", 0, "Z46");
        for zid in &zeitraum_ids {
            let count = rff_z46
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.get(1))
                        .is_some_and(|v| v == zid)
                })
                .count();
            if count != 1 {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [2006] Segmentgruppe ist mindestens einmal für jede Zeitraum-ID aus dem DE9013 der SG5 STS+Z23+Z33 (Berechnungsformel angefügt) anzugeben
    // REVIEW: Finds STS+Z23 (Status der Berechnungsformel) where status code (elements[1][0]) = 'Z33' (formula attached), collects Zeitraum-IDs from DE9013 (elements[2][0]). For each such ID, checks that at least one SG8 RFF+Z46 (elements[0][1]) references it, confirming the calculation formula group appears at minimum once per qualifying Zeitraum-ID. (medium confidence)
    fn evaluate_2006(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Collect Zeitraum-IDs from STS+Z23 (Berechnungsformel) where status code = Z33 (angefügt)
        let sts_z23 = ctx.find_segments_with_qualifier("STS", 0, "Z23");
        let zeitraum_ids: Vec<String> = sts_z23
            .iter()
            .filter(|s| {
                s.elements
                    .get(1)
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z33")
            })
            .filter_map(|s| s.elements.get(2).and_then(|e| e.first()).cloned())
            .filter(|id| !id.is_empty())
            .collect();
        if zeitraum_ids.is_empty() {
            return ConditionResult::Unknown;
        }
        // For each Zeitraum-ID, at least one SG8 RFF+Z46 must reference it
        let rff_z46 = ctx.find_segments_with_qualifier("RFF", 0, "Z46");
        for zid in &zeitraum_ids {
            let count = rff_z46
                .iter()
                .filter(|s| {
                    s.elements
                        .first()
                        .and_then(|e| e.get(1))
                        .is_some_and(|v| v == zid)
                })
                .count();
            if count < 1 {
                return ConditionResult::False;
            }
        }
        ConditionResult::True
    }

    /// [2007] Segmentgruppe ist genau einmal für jede Zeitraum-ID aus dem DE9013 der SG5 STS+Z23+Z33 (Berechnungsformel angefügt) anzugeben
    // REVIEW: The condition says the segment group must appear exactly once for each Zeitraum-ID from SG5 STS+Z23+Z33 (Berechnungsformel angefügt). From the MIG reference, STS with Statuskategorie Z23 has elements[0][0]=Z23, elements[1][0]=status code (Z33=angefügt), and elements[2][0]=Zeitraum-ID. The evaluator returns True when at least one such STS+Z23+Z33 is present in the message, which is when the cardinality rule triggers. Full cardinality counting (exactly one group per Zeitraum-ID) would require navigator-level group instance counting and cross-referencing, which goes beyond what the boolean ConditionResult can express — the condition is really a presence trigger for the group requirement. (medium confidence)
    fn evaluate_2007(&self, ctx: &EvaluationContext) -> ConditionResult {
        // Condition 2007: Segment group required exactly once per Zeitraum-ID from SG5 STS+Z23+Z33
        // Evaluates to True when at least one STS in SG5 has Statuskategorie=Z23 and Status=Z33
        // (Berechnungsformel angefügt), indicating the group must be present for that Zeitraum-ID.
        // STS Z23 structure: elements[0][0]=Z23 (Statuskategorie), elements[1][0]=Z33 (Status), elements[2][0]=Zeitraum-ID
        let sts_segments = ctx.find_segments("STS");
        let has_z23_z33 = sts_segments.iter().any(|s| {
            s.elements
                .first()
                .and_then(|e| e.first())
                .is_some_and(|v| v == "Z23")
                && s.elements
                    .get(1)
                    .and_then(|e| e.first())
                    .is_some_and(|v| v == "Z33")
        });
        ConditionResult::from(has_z23_z33)
    }
}