edi-energy 0.15.0

EDI@Energy EDIFACT parser and validator for the German energy market
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
// @generated — do not edit by hand; run `cargo xtask codegen` to regenerate
#![allow(clippy::doc_markdown)]
#![allow(clippy::too_many_lines)]

/// Codegen schema version this module was generated from.
/// Compared against `mig.json` `schema_version` in CI to detect drift.
#[allow(dead_code)]
pub(crate) const CODEGEN_SCHEMA_VERSION: u32 = 1;

use std::sync::{Arc, LazyLock};

use edifact_rs::directory_validator::{ElementRef, SegmentDefinition, Status};
use edifact_rs::{
    DirectoryValidator, GroupDef, ProfileRulePack, ValidationIssue, ValidationSeverity,
};

use crate::registry::Profile;
use crate::{MessageType, Pruefidentifikator, Release};

static SEGMENTS: &[SegmentDefinition] = &[
    SegmentDefinition::new(
        "UNH",
        "Message Header",
        &[
            ElementRef::new(1, "0062", Status::Mandatory, 1),
            ElementRef::new(2, "S009", Status::Mandatory, 1),
        ],
    ),
    SegmentDefinition::new(
        "BGM",
        "Beginning of Message",
        &[
            ElementRef::new(1, "C002", Status::Mandatory, 1),
            ElementRef::new(2, "C106", Status::Conditional, 1),
        ],
    ),
    SegmentDefinition::new(
        "DTM",
        "Date/Time/Period",
        &[ElementRef::new(1, "C507", Status::Mandatory, 1)],
    ),
    SegmentDefinition::new(
        "IMD",
        "Item Description",
        &[
            ElementRef::new(1, "7077", Status::Conditional, 1),
            ElementRef::new(2, "C273", Status::Conditional, 1),
        ],
    ),
    SegmentDefinition::new(
        "FTX",
        "Free Text",
        &[
            ElementRef::new(1, "4451", Status::Mandatory, 1),
            ElementRef::new(2, "C108", Status::Conditional, 1),
        ],
    ),
    SegmentDefinition::new(
        "NAD",
        "Name and Address",
        &[
            ElementRef::new(1, "3035", Status::Mandatory, 1),
            ElementRef::new(2, "C082", Status::Conditional, 1),
        ],
    ),
    SegmentDefinition::new(
        "CTA",
        "Contact Information",
        &[
            ElementRef::new(1, "3139", Status::Conditional, 1),
            ElementRef::new(2, "C056", Status::Conditional, 1),
        ],
    ),
    SegmentDefinition::new(
        "COM",
        "Communication Contact",
        &[ElementRef::new(1, "C076", Status::Mandatory, 1)],
    ),
    SegmentDefinition::new(
        "LOC",
        "Place/Location Identification",
        &[
            ElementRef::new(1, "3227", Status::Mandatory, 1),
            ElementRef::new(2, "C517", Status::Conditional, 1),
        ],
    ),
    SegmentDefinition::new(
        "LIN",
        "Line Item",
        &[ElementRef::new(1, "1082", Status::Conditional, 1)],
    ),
    SegmentDefinition::new(
        "UNT",
        "Message Trailer",
        &[
            ElementRef::new(1, "0074", Status::Mandatory, 1),
            ElementRef::new(2, "0062", Status::Mandatory, 1),
        ],
    ),
    SegmentDefinition::new(
        "RFF",
        "Reference (Prüfidentifikator/Referenz)",
        &[ElementRef::new(1, "C506", Status::Mandatory, 1)],
    ),
    SegmentDefinition::new(
        "PIA",
        "Zusätzliche Produktidentifikation",
        &[
            ElementRef::new(1, "4347", Status::Mandatory, 1),
            ElementRef::new(2, "C212", Status::Mandatory, 1),
        ],
    ),
    SegmentDefinition::new(
        "CCI",
        "Characteristic/Class Id",
        &[
            ElementRef::new(1, "7059", Status::Conditional, 1),
            ElementRef::new(2, "C502", Status::Conditional, 1),
            ElementRef::new(3, "C240", Status::Conditional, 1),
        ],
    ),
];

static SEGMENT_MAP: LazyLock<std::collections::HashMap<&'static str, &'static SegmentDefinition>> =
    LazyLock::new(|| SEGMENTS.iter().map(|s| (s.tag, s)).collect());

pub(crate) fn segment_lookup(tag: &str) -> Option<&'static SegmentDefinition> {
    SEGMENT_MAP.get(tag).copied()
}

static CODES_1001: &[&str] = &["311", "Z29", "Z57", "Z74", "Z93"];
static CODES_1153: &[&str] = &["AEP", "AGK", "AGO", "Z13"];
static CODES_2005: &[&str] = &["137", "163", "164", "203", "469", "472"];
static CODES_3035: &[&str] = &["BY", "DP", "MR", "MS"];
static CODES_3227: &[&str] = &["172"];
static CODES_4451: &[&str] = &["REG", "ZZZ"];

pub(crate) fn is_code_valid(de_id: &str, code: &str) -> bool {
    code_list(de_id).is_none_or(|codes| codes.binary_search(&code).is_ok())
}

pub(crate) fn suggest_code(de_id: &str, code: &str) -> Option<&'static str> {
    let codes = code_list(de_id)?;
    // Return the lexicographically nearest valid code.
    // partition_point gives the insertion point for `code` in the sorted slice,
    // so codes[idx] is the first valid code >= code (or last if past end).
    let idx = codes.partition_point(|&c| c < code);
    codes.get(idx).or_else(|| codes.last()).copied()
}

fn expected_components(tag: &str, idx: usize) -> Option<u8> {
    match (tag, idx) {
        ("CCI", 0) => Some(1),
        _ => None,
    }
}

pub(crate) fn code_list(de_id: &str) -> Option<&'static [&'static str]> {
    match de_id {
        "1001" => Some(CODES_1001),
        "1153" => Some(CODES_1153),
        "2005" => Some(CODES_2005),
        "3035" => Some(CODES_3035),
        "3227" => Some(CODES_3227),
        "4451" => Some(CODES_4451),
        _ => None,
    }
}

// Layer 2 scope: mandatory segment presence, element/component counts,
// code-list validity. Does NOT check segment sequence or repetition
// cardinality — those are Layer 3 (MIG ProfileRulePack) responsibilities.
// Cached in a LazyLock so construction happens once per profile.
static DIRECTORY_VALIDATOR_REQOTE_1_3C: LazyLock<DirectoryValidator> = LazyLock::new(|| {
    DirectoryValidator::new(
        "EDI@Energy-REQOTE-1.3c",
        segment_lookup,
        is_code_valid,
        suggest_code,
        expected_components,
        None,
    )
});

pub(crate) fn directory_validator() -> &'static DirectoryValidator {
    &DIRECTORY_VALIDATOR_REQOTE_1_3C
}

fn rule_unh_mandatory(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    if !segments.iter().any(|s| s.tag == "UNH") {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                "mandatory segment UNH is missing".to_owned(),
            )
            .with_rule_id("MIG-UNH-REQ")
            .with_segment("UNH".to_owned()),
        );
    }
}

fn rule_bgm_mandatory(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    if !segments.iter().any(|s| s.tag == "BGM") {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                "mandatory segment BGM is missing".to_owned(),
            )
            .with_rule_id("MIG-BGM-REQ")
            .with_segment("BGM".to_owned()),
        );
    }
}

fn rule_dtm_mandatory(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    if !segments.iter().any(|s| s.tag == "DTM") {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                "mandatory segment DTM is missing".to_owned(),
            )
            .with_rule_id("MIG-DTM-REQ")
            .with_segment("DTM".to_owned()),
        );
    }
}

fn rule_nad_mandatory(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    if !segments.iter().any(|s| s.tag == "NAD") {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                "mandatory segment NAD is missing".to_owned(),
            )
            .with_rule_id("MIG-NAD-REQ")
            .with_segment("NAD".to_owned()),
        );
    }
}

fn rule_unt_mandatory(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    if !segments.iter().any(|s| s.tag == "UNT") {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                "mandatory segment UNT is missing".to_owned(),
            )
            .with_rule_id("MIG-UNT-REQ")
            .with_segment("UNT".to_owned()),
        );
    }
}

fn rule_rff_mandatory(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    if !segments.iter().any(|s| s.tag == "RFF") {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                "mandatory segment RFF is missing".to_owned(),
            )
            .with_rule_id("MIG-RFF-REQ")
            .with_segment("RFF".to_owned()),
        );
    }
}

/// Layer 3 — verify `DTM` appears at most 5 times in the message header.
///
/// This rule only fires for segment tags that appear exclusively in the
/// message header (not in any segment group).  Tags shared between the
/// header and groups use per-group window rules instead.
fn rule_dtm_max_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "DTM").count();
    if count > 5 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment DTM occurs {count} times; maximum is 5"),
            )
            .with_rule_id("MIG-DTM-CARD-MAX")
            .with_segment("DTM".to_owned()),
        );
    }
}

/// Layer 3 — verify `FTX` appears at most 2 times in the message header.
///
/// This rule only fires for segment tags that appear exclusively in the
/// message header (not in any segment group).  Tags shared between the
/// header and groups use per-group window rules instead.
fn rule_ftx_max_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "FTX").count();
    if count > 2 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment FTX occurs {count} times; maximum is 2"),
            )
            .with_rule_id("MIG-FTX-CARD-MAX")
            .with_segment("FTX".to_owned()),
        );
    }
}

/// Layer 3 — verify the `RFF` segment group appears at most 9999 times.
///
/// Each occurrence of the trigger segment `RFF` marks the start of
/// one group instance.  The MIG specifies a maximum of 9999 instances.
fn rule_group_sg1_rff_max_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "RFF").count();
    if count > 9_999 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment group triggered by RFF occurs {count} times; maximum is 9_999"),
            )
            .with_rule_id("MIG-REQOTE-MIG-1.3c-GROUP-SG1-RFF-CARD-MAX")
            .with_segment("RFF".to_owned()),
        );
    }
}

/// Layer 3 — verify the `NAD` segment group appears at most 99 times.
///
/// Each occurrence of the trigger segment `NAD` marks the start of
/// one group instance.  The MIG specifies a maximum of 99 instances.
fn rule_group_sg11_nad_max_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "NAD").count();
    if count > 99 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment group triggered by NAD occurs {count} times; maximum is 99"),
            )
            .with_rule_id("MIG-REQOTE-MIG-1.3c-GROUP-SG11-NAD-CARD-MAX")
            .with_segment("NAD".to_owned()),
        );
    }
}

/// Layer 3 — verify the `LIN` segment group appears at most 200000 times.
///
/// Each occurrence of the trigger segment `LIN` marks the start of
/// one group instance.  The MIG specifies a maximum of 200000 instances.
fn rule_group_sg27_lin_max_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "LIN").count();
    if count > 200_000 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment group triggered by LIN occurs {count} times; maximum is 200_000"),
            )
            .with_rule_id("MIG-REQOTE-MIG-1.3c-GROUP-SG27-LIN-CARD-MAX")
            .with_segment("LIN".to_owned()),
        );
    }
}

/// Layer 3 — verify the `RFF` segment group appears at least 1 time(s).
///
/// The MIG specifies a minimum of 1 occurrence(s) for this group.
fn rule_group_sg1_rff_min_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "RFF").count();
    if count < 1 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment group triggered by RFF occurs {count} times; minimum is 1"),
            )
            .with_rule_id("MIG-REQOTE-MIG-1.3c-GROUP-SG1-RFF-CARD-MIN")
            .with_segment("RFF".to_owned()),
        );
    }
}

/// Layer 3 — verify the `NAD` segment group appears at least 1 time(s).
///
/// The MIG specifies a minimum of 1 occurrence(s) for this group.
fn rule_group_sg11_nad_min_occurrences(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let count = segments.iter().filter(|s| s.tag == "NAD").count();
    if count < 1 {
        issues.push(
            ValidationIssue::new(
                ValidationSeverity::Error,
                format!("segment group triggered by NAD occurs {count} times; minimum is 1"),
            )
            .with_rule_id("MIG-REQOTE-MIG-1.3c-GROUP-SG11-NAD-CARD-MIN")
            .with_segment("NAD".to_owned()),
        );
    }
}

/// Layer 3.5 — verify that segment tags appear in the normative sequence.
///
/// The rule does NOT require every tag to be present (that is Layer 3's job);
/// it only checks that tag positions are non-decreasing w.r.t. the expected order.
fn rule_segment_order(segments: &[edifact_rs::Segment<'_>], issues: &mut Vec<ValidationIssue>) {
    /// Per-group expected segment order derived from the MIG.
    ///
    /// Returns an empty slice for groups not covered by the MIG or for the
    /// catch-all arm, which causes those groups to be skipped silently.
    fn group_order(name: &str) -> &'static [&'static str] {
        match name {
            "ROOT" => &[
                "UNH", "BGM", "DTM", "IMD", "FTX", "NAD", "CTA", "COM", "LOC", "LIN", "UNT",
            ],
            "SG1" => &["RFF"],
            "SG11" => &["NAD", "LOC"],
            "SG14" => &["CTA", "COM"],
            "SG27" => &["LIN", "PIA"],
            "SG28" => &["CCI"],
            _ => &[],
        }
    }

    /// Recursively verify segment order within a group and all its children.
    ///
    /// Only `direct_segment_indices()` — segments that belong directly to this
    /// group and are not claimed by any child group — are checked.  Child groups
    /// are then visited recursively, so every segment in the message is covered
    /// exactly once.
    fn check_order(
        group: &edifact_rs::group::SegmentGroupIndexed,
        all_segs: &[edifact_rs::Segment<'_>],
        rule_id: &str,
        issues: &mut Vec<ValidationIssue>,
    ) {
        let expected = group_order(group.definition);
        if !expected.is_empty() {
            let mut cursor: usize = 0;
            for idx in group.direct_segment_indices() {
                let seg = &all_segs[idx];
                if let Some(pos) = expected[cursor..].iter().position(|&t| t == seg.tag) {
                    cursor += pos;
                } else if expected.contains(&seg.tag) {
                    // Tag is known for this group but already passed — ordering violation.
                    issues.push(
                        ValidationIssue::new(
                            ValidationSeverity::Error,
                            "segment appears out of order".to_owned(),
                        )
                        .with_rule_id(rule_id)
                        .with_segment(seg.tag.to_owned()),
                    );
                }
                // Tags not in this group's expected order are unknown here;
                // they are either in a child group (checked below) or caught by the DirectoryValidator.
            }
        }
        for child in &group.children {
            check_order(child, all_segs, rule_id, issues);
        }
    }

    let tree = edifact_rs::group::group_segments_indexed(segments, GROUP_SCHEMA, "ROOT");
    check_order(&tree, segments, "MIG-REQOTE-MIG-1.3c-ORDER", issues);
}

static MIG_REQOTE_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    Arc::new(
        ProfileRulePack::new("REQOTE-MIG-1.3c")
            .for_message_type("REQOTE")
            .for_release("1.3c")
            .with_stateless_rule_fn(rule_unh_mandatory)
            .with_stateless_rule_fn(rule_bgm_mandatory)
            .with_stateless_rule_fn(rule_dtm_mandatory)
            .with_stateless_rule_fn(rule_nad_mandatory)
            .with_stateless_rule_fn(rule_unt_mandatory)
            .with_stateless_rule_fn(rule_rff_mandatory)
            .with_stateless_rule_fn(rule_dtm_max_occurrences)
            .with_stateless_rule_fn(rule_ftx_max_occurrences)
            .with_stateless_rule_fn(rule_group_sg1_rff_max_occurrences)
            .with_stateless_rule_fn(rule_group_sg11_nad_max_occurrences)
            .with_stateless_rule_fn(rule_group_sg27_lin_max_occurrences)
            .with_stateless_rule_fn(rule_group_sg1_rff_min_occurrences)
            .with_stateless_rule_fn(rule_group_sg11_nad_min_occurrences)
            .with_stateless_rule_fn(rule_segment_order),
    )
});

pub(crate) fn mig_rule_pack() -> Arc<ProfileRulePack> {
    Arc::clone(&MIG_REQOTE_PACK)
}

static GROUP_SCHEMA: &[GroupDef] = &[];
#[allow(unused_imports)]
use super::ahb_helpers::{
    ahb_check_conditional, ahb_check_field_value, ahb_check_mandatory, ahb_check_not_used,
    ahb_check_qualifier, ahb_check_required_qualifier, ahb_check_soll,
};

/// Bedingungsoperator I — I: when RFF DE[0]="Z41" is present // [17] Wenn SG1 RFF+Z41 (Referenznummer des Vorgangs der Anmeldung nach WiM) vorhanden, ist SG11 NAD (NB) Pflicht
fn rule_ahb_35004_nad_cond_0(
    segments: &[edifact_rs::Segment<'_>],
    issues: &mut Vec<ValidationIssue>,
) {
    let __start = issues.len();
    let condition_holds = segments
        .iter()
        .any(|s| s.tag == "RFF" && s.element_str(0).is_some_and(|v| v == "Z41"));
    if condition_holds && !segments.iter().any(|s| s.tag == "NAD") {
        issues.push(
                ValidationIssue::new(
                    ValidationSeverity::Error,
                    "conditional segment NAD is missing for Pruefidentifikator 35004 (I: when RFF DE[0]=\"Z41\" is present)".to_owned(),
                )
                .with_rule_id("AHB-35004-NAD-I0")
                .with_segment("NAD".to_owned())
            );
    }
    for __i in &mut issues[__start..] {
        __i.context.push(("pid".to_owned(), "35004".to_owned()));
    }
}

static AHB_35001_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    Arc::new(
        ProfileRulePack::new("REQOTE-AHB-1.3c-35001")
            .for_message_type("REQOTE")
            .for_release("1.3c")
            .with_named_stateless_rule_fn("AHB-35001-BGM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "BGM",
                    "AHB-35001-BGM-M",
                    "mandatory segment BGM is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-COM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "COM",
                    "AHB-35001-COM-M",
                    "mandatory segment COM is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-CTA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "CTA",
                    "AHB-35001-CTA-M",
                    "mandatory segment CTA is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-DTM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "DTM",
                    "AHB-35001-DTM-M",
                    "mandatory segment DTM is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-LIN-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LIN",
                    "AHB-35001-LIN-M",
                    "mandatory segment LIN is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-LOC-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LOC",
                    "AHB-35001-LOC-M",
                    "mandatory segment LOC is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-NAD-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "NAD",
                    "AHB-35001-NAD-M",
                    "mandatory segment NAD is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35001-RFF-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "RFF",
                    "AHB-35001-RFF-M",
                    "mandatory segment RFF is missing for Pruefidentifikator 35001",
                    "35001",
                    issues,
                );
            })
            .with_max_issues_per_rule(50),
    )
});

fn ahb_35001_pack() -> Arc<ProfileRulePack> {
    Arc::clone(&AHB_35001_PACK)
}

static AHB_35002_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    Arc::new(
        ProfileRulePack::new("REQOTE-AHB-1.3c-35002")
            .for_message_type("REQOTE")
            .for_release("1.3c")
            .with_named_stateless_rule_fn("AHB-35002-BGM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "BGM",
                    "AHB-35002-BGM-M",
                    "mandatory segment BGM is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-COM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "COM",
                    "AHB-35002-COM-M",
                    "mandatory segment COM is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-CTA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "CTA",
                    "AHB-35002-CTA-M",
                    "mandatory segment CTA is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-DTM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "DTM",
                    "AHB-35002-DTM-M",
                    "mandatory segment DTM is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-LIN-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LIN",
                    "AHB-35002-LIN-M",
                    "mandatory segment LIN is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-LOC-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LOC",
                    "AHB-35002-LOC-M",
                    "mandatory segment LOC is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-NAD-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "NAD",
                    "AHB-35002-NAD-M",
                    "mandatory segment NAD is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35002-RFF-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "RFF",
                    "AHB-35002-RFF-M",
                    "mandatory segment RFF is missing for Pruefidentifikator 35002",
                    "35002",
                    issues,
                );
            })
            .with_max_issues_per_rule(50),
    )
});

fn ahb_35002_pack() -> Arc<ProfileRulePack> {
    Arc::clone(&AHB_35002_PACK)
}

static AHB_35003_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    Arc::new(
        ProfileRulePack::new("REQOTE-AHB-1.3c-35003")
            .for_message_type("REQOTE")
            .for_release("1.3c")
            .with_named_stateless_rule_fn("AHB-35003-BGM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "BGM",
                    "AHB-35003-BGM-M",
                    "mandatory segment BGM is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-CCI-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "CCI",
                    "AHB-35003-CCI-M",
                    "mandatory segment CCI is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-COM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "COM",
                    "AHB-35003-COM-M",
                    "mandatory segment COM is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-CTA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "CTA",
                    "AHB-35003-CTA-M",
                    "mandatory segment CTA is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-DTM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "DTM",
                    "AHB-35003-DTM-M",
                    "mandatory segment DTM is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-FTX-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "FTX",
                    "AHB-35003-FTX-M",
                    "mandatory segment FTX is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-LIN-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LIN",
                    "AHB-35003-LIN-M",
                    "mandatory segment LIN is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-LOC-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LOC",
                    "AHB-35003-LOC-M",
                    "mandatory segment LOC is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-NAD-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "NAD",
                    "AHB-35003-NAD-M",
                    "mandatory segment NAD is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-PIA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "PIA",
                    "AHB-35003-PIA-M",
                    "mandatory segment PIA is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35003-RFF-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "RFF",
                    "AHB-35003-RFF-M",
                    "mandatory segment RFF is missing for Pruefidentifikator 35003",
                    "35003",
                    issues,
                );
            })
            .with_max_issues_per_rule(50),
    )
});

fn ahb_35003_pack() -> Arc<ProfileRulePack> {
    Arc::clone(&AHB_35003_PACK)
}

static AHB_35004_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    Arc::new(
        ProfileRulePack::new("REQOTE-AHB-1.3c-35004")
            .for_message_type("REQOTE")
            .for_release("1.3c")
            .with_named_stateless_rule_fn("AHB-35004-BGM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "BGM",
                    "AHB-35004-BGM-M",
                    "mandatory segment BGM is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-CCI-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "CCI",
                    "AHB-35004-CCI-M",
                    "mandatory segment CCI is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-COM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "COM",
                    "AHB-35004-COM-M",
                    "mandatory segment COM is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-CTA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "CTA",
                    "AHB-35004-CTA-M",
                    "mandatory segment CTA is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-DTM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "DTM",
                    "AHB-35004-DTM-M",
                    "mandatory segment DTM is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-FTX-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "FTX",
                    "AHB-35004-FTX-M",
                    "mandatory segment FTX is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-IMD-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "IMD",
                    "AHB-35004-IMD-M",
                    "mandatory segment IMD is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-LIN-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LIN",
                    "AHB-35004-LIN-M",
                    "mandatory segment LIN is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-LOC-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LOC",
                    "AHB-35004-LOC-M",
                    "mandatory segment LOC is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-NAD-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "NAD",
                    "AHB-35004-NAD-M",
                    "mandatory segment NAD is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_stateless_rule_fn(rule_ahb_35004_nad_cond_0)
            .with_named_stateless_rule_fn("AHB-35004-PIA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "PIA",
                    "AHB-35004-PIA-M",
                    "mandatory segment PIA is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35004-RFF-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "RFF",
                    "AHB-35004-RFF-M",
                    "mandatory segment RFF is missing for Pruefidentifikator 35004",
                    "35004",
                    issues,
                );
            })
            .with_max_issues_per_rule(50),
    )
});

fn ahb_35004_pack() -> Arc<ProfileRulePack> {
    Arc::clone(&AHB_35004_PACK)
}

static AHB_35005_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    Arc::new(
        ProfileRulePack::new("REQOTE-AHB-1.3c-35005")
            .for_message_type("REQOTE")
            .for_release("1.3c")
            .with_named_stateless_rule_fn("AHB-35005-BGM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "BGM",
                    "AHB-35005-BGM-M",
                    "mandatory segment BGM is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-COM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "COM",
                    "AHB-35005-COM-M",
                    "mandatory segment COM is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-DTM-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "DTM",
                    "AHB-35005-DTM-M",
                    "mandatory segment DTM is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-LIN-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LIN",
                    "AHB-35005-LIN-M",
                    "mandatory segment LIN is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-LOC-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "LOC",
                    "AHB-35005-LOC-M",
                    "mandatory segment LOC is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-NAD-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "NAD",
                    "AHB-35005-NAD-M",
                    "mandatory segment NAD is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-PIA-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "PIA",
                    "AHB-35005-PIA-M",
                    "mandatory segment PIA is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_named_stateless_rule_fn("AHB-35005-RFF-M", |segs, issues| {
                ahb_check_mandatory(
                    segs,
                    "RFF",
                    "AHB-35005-RFF-M",
                    "mandatory segment RFF is missing for Pruefidentifikator 35005",
                    "35005",
                    issues,
                );
            })
            .with_max_issues_per_rule(50),
    )
});

fn ahb_35005_pack() -> Arc<ProfileRulePack> {
    Arc::clone(&AHB_35005_PACK)
}

static AHB_ALL_PACK_REQOTE_1_3C: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    let pack = ProfileRulePack::new("REQOTE-AHB-1.3c-ALL")
        .for_message_type("REQOTE")
        .for_release("1.3c");
    let pack = pack
        .merge_with_override(ahb_35001_pack().as_ref().clone())
        .expect("AHB union pack merge_with_override failed");
    let pack = pack
        .merge_with_override(ahb_35002_pack().as_ref().clone())
        .expect("AHB union pack merge_with_override failed");
    let pack = pack
        .merge_with_override(ahb_35003_pack().as_ref().clone())
        .expect("AHB union pack merge_with_override failed");
    let pack = pack
        .merge_with_override(ahb_35004_pack().as_ref().clone())
        .expect("AHB union pack merge_with_override failed");
    let pack = pack
        .merge_with_override(ahb_35005_pack().as_ref().clone())
        .expect("AHB union pack merge_with_override failed");
    Arc::new(pack)
});

pub(crate) fn ahb_rule_pack(pid: Option<Pruefidentifikator>) -> Arc<ProfileRulePack> {
    match pid.map(super::super::pruefidentifikator::Pruefidentifikator::as_u32) {
            Some(35001) => ahb_35001_pack(),
            Some(35002) => ahb_35002_pack(),
            Some(35003) => ahb_35003_pack(),
            Some(35004) => ahb_35004_pack(),
            Some(35005) => ahb_35005_pack(),
            None => Arc::clone(&AHB_ALL_PACK_REQOTE_1_3C),
            Some(_unknown) => Arc::new(ProfileRulePack::new("unknown-pid")
                .for_message_type("REQOTE")
                .with_named_stateless_rule_fn("AHB-UNKNOWN-PID", |_segs, issues| {
                    issues.push(ValidationIssue::new(
                        ValidationSeverity::Warning,
                        "Pruefidentifikator is not registered for this release — AHB rules were not applied",
                    ).with_rule_id("AHB-UNKNOWN-PID"));
                })),
        }
}

static RELEASE_REQOTE_FV20250401: LazyLock<Release> = LazyLock::new(|| Release::new("1.3c"));

pub(crate) struct ReqoteFv20250401Profile;

impl Profile for ReqoteFv20250401Profile {
    fn message_type(&self) -> MessageType {
        MessageType::Reqote
    }
    fn release(&self) -> &Release {
        &RELEASE_REQOTE_FV20250401
    }
    fn valid_from(&self) -> Option<::time::Date> {
        Some(::time::macros::date!(2025 - 04 - 01))
    }
    fn valid_until(&self) -> Option<::time::Date> {
        Some(::time::macros::date!(2026 - 09 - 30))
    }
    fn ahb_revision(&self) -> Option<&'static str> {
        Some("1.3c")
    }
    fn source_document(&self) -> Option<&'static str> {
        Some("REQOTE MIG 1.3c, Stand 01.04.2025")
    }
    fn mig_rule_pack(&self) -> Arc<ProfileRulePack> {
        mig_rule_pack()
    }
    fn ahb_rule_pack(&self, pid: Option<Pruefidentifikator>) -> Arc<ProfileRulePack> {
        ahb_rule_pack(pid)
    }
    fn is_code_valid(&self, de_id: &str, code: &str) -> bool {
        is_code_valid(de_id, code)
    }
    fn suggest_code(&self, de_id: &str, code: &str) -> Option<&'static str> {
        suggest_code(de_id, code)
    }
    fn segment_lookup(&self, tag: &str) -> Option<&'static SegmentDefinition> {
        segment_lookup(tag)
    }
    fn code_list(&self, de_id: &str) -> Option<&'static [&'static str]> {
        code_list(de_id)
    }
    fn directory_validator(&self) -> &'static DirectoryValidator {
        directory_validator()
    }
    fn group_schema(&self) -> &'static [GroupDef] {
        GROUP_SCHEMA
    }
}

pub(crate) static PROFILE: ReqoteFv20250401Profile = ReqoteFv20250401Profile;