mig-bo4e 0.7.0

Declarative TOML-based MIG-tree to BO4E mapping engine
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
//! PID validation errors — typed, LLM-consumable error reports.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde_json::Value;

use crate::pid_requirements::{
    CodeValue, EntityRequirement, EntityScope, EntityVariantRequirement, FieldRequirement,
    PidRequirements,
};

/// Severity of a validation error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Severity {
    /// Field is unconditionally required (Muss/X) or condition evaluated to True.
    Error,
    /// Condition evaluated to Unknown (depends on external context).
    Warning,
}

/// A single PID validation error.
#[derive(Debug, Clone)]
pub enum PidValidationError {
    /// An entire entity is missing from the interchange.
    MissingEntity {
        entity: String,
        ahb_status: String,
        severity: Severity,
    },
    /// A required field is None/missing.
    MissingField {
        entity: String,
        field: String,
        ahb_status: String,
        rust_type: Option<String>,
        valid_values: Vec<(String, String)>,
        severity: Severity,
    },
    /// A code field has a value not in the allowed set.
    InvalidCode {
        entity: String,
        field: String,
        value: String,
        valid_values: Vec<(String, String)>,
    },
}

impl PidValidationError {
    pub fn severity(&self) -> &Severity {
        match self {
            Self::MissingEntity { severity, .. } => severity,
            Self::MissingField { severity, .. } => severity,
            Self::InvalidCode { .. } => &Severity::Error,
        }
    }

    pub fn is_error(&self) -> bool {
        matches!(self.severity(), Severity::Error)
    }
}

impl fmt::Display for PidValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PidValidationError::MissingEntity {
                entity,
                ahb_status,
                severity,
            } => {
                let label = severity_label(severity);
                write!(
                    f,
                    "{label}: missing entity '{entity}' (required: {ahb_status})"
                )
            }
            PidValidationError::MissingField {
                entity,
                field,
                ahb_status,
                rust_type,
                valid_values,
                severity,
            } => {
                let label = severity_label(severity);
                write!(
                    f,
                    "{label}: missing {entity}.{field} (required: {ahb_status})"
                )?;
                if let Some(rt) = rust_type {
                    write!(f, "\n  → type: {rt}")?;
                }
                if !valid_values.is_empty() {
                    let codes: Vec<String> = valid_values
                        .iter()
                        .map(|(code, meaning)| {
                            if meaning.is_empty() {
                                code.clone()
                            } else {
                                format!("{code} ({meaning})")
                            }
                        })
                        .collect();
                    write!(f, "\n  → valid: {}", codes.join(", "))?;
                }
                Ok(())
            }
            PidValidationError::InvalidCode {
                entity,
                field,
                value,
                valid_values,
            } => {
                write!(f, "INVALID: {entity}.{field} = \"{value}\"")?;
                if !valid_values.is_empty() {
                    let codes: Vec<String> = valid_values.iter().map(|(c, _)| c.clone()).collect();
                    write!(f, "\n  → valid: {}", codes.join(", "))?;
                }
                Ok(())
            }
        }
    }
}

fn severity_label(severity: &Severity) -> &'static str {
    match severity {
        Severity::Error => "ERROR",
        Severity::Warning => "WARNING",
    }
}

/// A collection of validation errors for a PID.
pub struct ValidationReport(pub Vec<PidValidationError>);

impl ValidationReport {
    /// Returns true if the report contains any errors (not just warnings).
    pub fn has_errors(&self) -> bool {
        self.0.iter().any(|e| e.is_error())
    }

    /// Returns only the errors (not warnings).
    pub fn errors(&self) -> Vec<&PidValidationError> {
        self.0.iter().filter(|e| e.is_error()).collect()
    }

    /// Returns true if the report is empty (no errors or warnings).
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of validation errors.
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl fmt::Display for ValidationReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, err) in self.0.iter().enumerate() {
            if i > 0 {
                writeln!(f)?;
            }
            write!(f, "{err}")?;
        }
        Ok(())
    }
}

// ── Validation Logic ──────────────────────────────────────────────────────

/// Validate a BO4E JSON value against PID requirements.
///
/// Validates ALL entities (both message-level and transaction-level).
/// Use [`validate_pid_json_transaction`] to validate only transaction-level entities.
///
/// Walks the requirements and checks:
/// 1. Required entities are present in the JSON
/// 2. Required fields are present within each entity
/// 3. Code fields have values in the allowed set
pub fn validate_pid_json(json: &Value, requirements: &PidRequirements) -> Vec<PidValidationError> {
    validate_entities(json, &requirements.entities, None)
}

/// Validate only transaction-level entities in a BO4E JSON value.
///
/// Skips message-level entities (e.g., Marktteilnehmer, Kontakt from SG2/SG3)
/// that are outside the transaction scope. Use this when validating a transaction
/// payload that doesn't include message-level data.
pub fn validate_pid_json_transaction(
    json: &Value,
    requirements: &PidRequirements,
) -> Vec<PidValidationError> {
    validate_entities(json, &requirements.entities, Some(EntityScope::Transaction))
}

/// Internal: validate entities, optionally filtering by scope.
fn validate_entities(
    json: &Value,
    entities: &[EntityRequirement],
    scope_filter: Option<EntityScope>,
) -> Vec<PidValidationError> {
    let mut errors = Vec::new();

    for entity_req in entities {
        // Skip entities not matching the requested scope
        if let Some(ref scope) = scope_filter {
            if &entity_req.scope != scope {
                continue;
            }
        }

        let key = to_camel_case(&entity_req.entity);

        match json.get(&key) {
            None | Some(serde_json::Value::Null) => {
                if is_unconditionally_required(&entity_req.ahb_status) {
                    errors.push(PidValidationError::MissingEntity {
                        entity: entity_req.entity.clone(),
                        ahb_status: entity_req.ahb_status.clone(),
                        severity: Severity::Error,
                    });
                }
            }
            Some(val) => {
                if entity_req.cardinality().is_list() {
                    if let Some(arr) = val.as_array() {
                        for element in arr {
                            validate_entity_fields(element, entity_req, &mut errors);
                        }
                    } else {
                        // Caller supplied a single object where the requirement
                        // expects an array (e.g. typed structs that emit one
                        // rep as an object instead of [obj]). Validate it as a
                        // single rep rather than silently skipping field checks.
                        validate_entity_fields(val, entity_req, &mut errors);
                    }
                } else {
                    validate_entity_fields(val, entity_req, &mut errors);
                }
            }
        }
    }

    errors
}

/// Traverse a dot-separated path in a JSON value, trying both the original
/// key and its camelCase variant at each level.
pub fn get_nested<'a>(json: &'a Value, path: &str) -> Option<&'a Value> {
    let mut current = json;
    for part in path.split('.') {
        current = current.get(part).or_else(|| {
            if part.contains('_') {
                current.get(snake_to_camel_case(part))
            } else {
                None
            }
        })?;
    }
    Some(current)
}

/// Validate fields within a single entity JSON object.
fn validate_entity_fields(
    entity_json: &Value,
    entity_req: &EntityRequirement,
    errors: &mut Vec<PidValidationError>,
) {
    let fields = effective_field_requirements(entity_req, entity_json);
    for field_req in fields.iter() {
        // Traverse dot-separated paths (e.g. "produktIdentifikation.funktion")
        // and try camelCase variants at each level for typed struct compatibility.
        let val = get_nested(entity_json, &field_req.bo4e_name);

        // Treat null values as missing — JSON null means "not provided"
        let val = val.filter(|v| !v.is_null());

        match val {
            None => {
                if is_unconditionally_required(&field_req.ahb_status) {
                    errors.push(PidValidationError::MissingField {
                        entity: entity_req.entity.clone(),
                        field: field_req.bo4e_name.clone(),
                        ahb_status: field_req.ahb_status.clone(),
                        rust_type: field_req.enum_name.clone(),
                        valid_values: code_values_to_tuples(&field_req.valid_codes),
                        severity: Severity::Error,
                    });
                }
            }
            Some(val) => {
                validate_code_value(val, entity_req, field_req, errors);
            }
        }
    }
}

/// Validate that a code field's value is in the allowed set.
fn validate_code_value(
    val: &Value,
    entity_req: &EntityRequirement,
    field_req: &FieldRequirement,
    errors: &mut Vec<PidValidationError>,
) {
    if let Some(value) = invalid_code_value(val, field_req) {
        errors.push(PidValidationError::InvalidCode {
            entity: entity_req.entity.clone(),
            field: field_req.bo4e_name.clone(),
            value,
            valid_values: code_values_to_tuples(&field_req.valid_codes),
        });
    }
}

/// The code carried by a BO4E code field: a plain string, or the `code` member of
/// a `{code, meaning, enum}` object as written by `from_edifact`.
pub fn code_field_value(val: &Value) -> Option<&str> {
    val.as_str()
        .or_else(|| val.get("code").and_then(|c| c.as_str()))
}

/// Check a code field's value against `field_req.valid_codes`.
///
/// Returns the offending value if it is invalid, `None` if it is valid or not a
/// code value at all. A value is valid when it equals a valid raw EDIFACT code
/// or the BO4E value the mapping's `enum_map` translates a valid code to — the
/// two spellings `to_edifact` accepts.
pub fn invalid_code_value(val: &Value, field_req: &FieldRequirement) -> Option<String> {
    if field_req.valid_codes.is_empty() {
        return None;
    }
    let value = code_field_value(val)?;
    let is_valid = field_req
        .valid_codes
        .iter()
        .any(|cv| cv.code == value || cv.bo4e_value.as_deref() == Some(value));
    (!is_valid).then(|| value.to_string())
}

/// The field requirements that apply to one element of an entity.
///
/// For an entity without [`EntityRequirement::variants`] this is simply its
/// `fields`. For a multi-variant entity (e.g. `Geschaeftspartner` fed by
/// `sg12_z03`/`sg12_z07`/…), the element's discriminator value (raw code or
/// `enum_map`ped BO4E value, string or code object) selects the matching
/// variant, and the variant-owned fields are replaced by that variant's
/// requirements — fields the variant's group lacks do not apply.
///
/// If the discriminator is missing or matches no variant, all variants are
/// candidates and are combined leniently: codes are unioned, and a field keeps
/// its AHB status only if every candidate agrees on it (otherwise it is treated
/// as optional), so an unidentifiable element is never held to the required
/// fields of a variant it may not be.
pub fn effective_field_requirements<'a>(
    entity_req: &'a EntityRequirement,
    element: &Value,
) -> Cow<'a, [FieldRequirement]> {
    if entity_req.variants.is_empty() {
        return Cow::Borrowed(&entity_req.fields);
    }

    // Candidate variants, per discriminator field.
    let mut by_field: BTreeMap<&str, Vec<&EntityVariantRequirement>> = BTreeMap::new();
    for v in &entity_req.variants {
        by_field
            .entry(v.discriminator_field.as_str())
            .or_default()
            .push(v);
    }
    let mut candidates: Vec<&EntityVariantRequirement> = Vec::new();
    for (field, group) in by_field {
        let value = get_nested(element, field).and_then(code_field_value);
        let matched: Vec<&EntityVariantRequirement> = group
            .iter()
            .copied()
            .filter(|v| value.is_some_and(|s| v.code == s || v.bo4e_value.as_deref() == Some(s)))
            .collect();
        candidates.extend(if matched.is_empty() { group } else { matched });
    }

    // Fields governed by variants (in first-seen order).
    let mut owned: Vec<&str> = Vec::new();
    let mut owned_set: BTreeSet<&str> = BTreeSet::new();
    for v in &entity_req.variants {
        for f in &v.fields {
            if owned_set.insert(f.bo4e_name.as_str()) {
                owned.push(f.bo4e_name.as_str());
            }
        }
    }

    let mut combined: BTreeMap<&str, FieldRequirement> = BTreeMap::new();
    for name in owned {
        let reqs: Vec<&FieldRequirement> = candidates
            .iter()
            .filter_map(|v| v.fields.iter().find(|f| f.bo4e_name == name))
            .collect();
        let Some((first, rest)) = reqs.split_first() else {
            continue; // not applicable to any candidate variant
        };
        let mut field = (*first).clone();
        let mut statuses_agree = reqs.len() == candidates.len();
        for r in rest {
            if r.ahb_status != field.ahb_status {
                statuses_agree = false;
            }
            for cv in &r.valid_codes {
                if !field.valid_codes.iter().any(|c| c.code == cv.code) {
                    field.valid_codes.push(cv.clone());
                }
            }
        }
        if !statuses_agree {
            field.ahb_status = String::new();
        }
        combined.insert(name, field);
    }

    let mut result: Vec<FieldRequirement> = Vec::with_capacity(entity_req.fields.len());
    for f in &entity_req.fields {
        if owned_set.contains(f.bo4e_name.as_str()) {
            if let Some(c) = combined.remove(f.bo4e_name.as_str()) {
                result.push(c);
            }
        } else {
            result.push(f.clone());
        }
    }
    result.extend(combined.into_values());
    Cow::Owned(result)
}

/// Convert CodeValue vec to (code, meaning) tuples.
fn code_values_to_tuples(codes: &[CodeValue]) -> Vec<(String, String)> {
    codes
        .iter()
        .map(|cv| (cv.code.clone(), cv.meaning.clone()))
        .collect()
}

/// Convert PascalCase entity name to camelCase JSON key.
///
/// "Prozessdaten" → "prozessdaten"
/// "RuhendeMarktlokation" → "ruhendeMarktlokation"
/// "Marktlokation" → "marktlokation"
fn to_camel_case(s: &str) -> String {
    if s.is_empty() {
        return String::new();
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    let mut result = first.to_lowercase().to_string();
    result.extend(chars);
    result
}

/// Convert a snake_case field name to camelCase.
///
/// This mirrors what `#[serde(rename_all = "camelCase")]` does at runtime, allowing
/// the validator to find fields in JSON that was produced by typed structs even when
/// the requirement stores the field name as snake_case (as it comes from TOML).
///
/// Examples:
/// - `"code_codepflege"` → `"codeCodepflege"`
/// - `"vorgang_id"` → `"vorgangId"`
/// - `"marktlokation"` → `"marktlokation"` (unchanged — no underscores)
fn snake_to_camel_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut capitalize_next = false;
    for ch in s.chars() {
        if ch == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.extend(ch.to_uppercase());
            capitalize_next = false;
        } else {
            result.push(ch);
        }
    }
    result
}

/// Returns true if the AHB status indicates an unconditionally required field.
fn is_unconditionally_required(ahb_status: &str) -> bool {
    matches!(ahb_status, "X" | "Muss" | "Soll")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pid_requirements::{
        Bo4eRefType, Cardinality, CodeValue, EntityRequirement, FieldRequirement, PidRequirements,
    };
    use serde_json::json;

    fn sample_requirements() -> PidRequirements {
        PidRequirements {
            pid: "55001".to_string(),
            beschreibung: "Anmeldung verb. MaLo".to_string(),
            entities: vec![
                EntityRequirement {
                    entity: "Prozessdaten".to_string(),
                    ref_type: Bo4eRefType::Object {
                        type_name: "Prozessdaten".to_string(),

                        cardinality: Cardinality::REQUIRED,
                    },

                    ahb_status: "Muss".to_string(),
                    map_key: None,
                    scope: EntityScope::Transaction,
                    variants: vec![],
                    fields: vec![
                        FieldRequirement {
                            bo4e_name: "vorgangId".to_string(),
                            ahb_status: "X".to_string(),
                            field_type: "data".to_string(),
                            format: None,
                            enum_name: None,
                            valid_codes: vec![],
                            child_group: None,
                            ref_type: Bo4eRefType::Unknown,
                        },
                        FieldRequirement {
                            bo4e_name: "transaktionsgrund".to_string(),
                            ahb_status: "X".to_string(),
                            field_type: "code".to_string(),
                            format: None,
                            enum_name: Some("Transaktionsgrund".to_string()),
                            valid_codes: vec![
                                CodeValue {
                                    code: "E01".to_string(),
                                    meaning: "Ein-/Auszug (Einzug)".to_string(),
                                    enum_name: None,
                                    bo4e_value: None,
                                },
                                CodeValue {
                                    code: "E03".to_string(),
                                    meaning: "Wechsel".to_string(),
                                    enum_name: None,
                                    bo4e_value: None,
                                },
                            ],
                            child_group: None,
                            ref_type: Bo4eRefType::Unknown,
                        },
                    ],
                },
                EntityRequirement {
                    entity: "Marktlokation".to_string(),
                    ref_type: Bo4eRefType::Object {
                        type_name: "Marktlokation".to_string(),

                        cardinality: Cardinality::REQUIRED,
                    },

                    ahb_status: "Muss".to_string(),
                    map_key: None,
                    scope: EntityScope::Transaction,
                    variants: vec![],
                    fields: vec![
                        FieldRequirement {
                            bo4e_name: "marktlokationsId".to_string(),
                            ahb_status: "X".to_string(),
                            field_type: "data".to_string(),
                            format: None,
                            enum_name: None,
                            valid_codes: vec![],
                            child_group: None,
                            ref_type: Bo4eRefType::Unknown,
                        },
                        FieldRequirement {
                            bo4e_name: "haushaltskunde".to_string(),
                            ahb_status: "X".to_string(),
                            field_type: "code".to_string(),
                            format: None,
                            enum_name: Some("Haushaltskunde".to_string()),
                            valid_codes: vec![
                                CodeValue {
                                    code: "Z15".to_string(),
                                    meaning: "Ja".to_string(),
                                    enum_name: None,
                                    bo4e_value: None,
                                },
                                CodeValue {
                                    code: "Z18".to_string(),
                                    meaning: "Nein".to_string(),
                                    enum_name: None,
                                    bo4e_value: None,
                                },
                            ],
                            child_group: None,
                            ref_type: Bo4eRefType::Unknown,
                        },
                    ],
                },
                EntityRequirement {
                    entity: "Geschaeftspartner".to_string(),
                    ref_type: Bo4eRefType::Object {
                        type_name: "Geschaeftspartner".to_string(),

                        cardinality: Cardinality {
                            min: 1,
                            max: Some(7),
                        },
                    },

                    ahb_status: "Muss".to_string(),
                    map_key: None,
                    scope: EntityScope::Transaction,
                    variants: vec![],
                    fields: vec![FieldRequirement {
                        bo4e_name: "identifikation".to_string(),
                        ahb_status: "X".to_string(),
                        field_type: "data".to_string(),
                        format: None,
                        enum_name: None,
                        valid_codes: vec![],
                        child_group: None,
                        ref_type: Bo4eRefType::Unknown,
                    }],
                },
            ],
        }
    }

    #[test]
    fn test_validate_complete_json() {
        let reqs = sample_requirements();
        let json = json!({
            "prozessdaten": {
                "vorgangId": "ABC123",
                "transaktionsgrund": "E01"
            },
            "marktlokation": {
                "marktlokationsId": "51234567890",
                "haushaltskunde": "Z15"
            },
            "geschaeftspartner": [
                { "identifikation": "9900000000003" }
            ]
        });

        let errors = validate_pid_json(&json, &reqs);
        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
    }

    #[test]
    fn test_validate_missing_entity() {
        let reqs = sample_requirements();
        let json = json!({
            "prozessdaten": {
                "vorgangId": "ABC123",
                "transaktionsgrund": "E01"
            },
            "geschaeftspartner": [
                { "identifikation": "9900000000003" }
            ]
        });
        // Marktlokation is missing

        let errors = validate_pid_json(&json, &reqs);
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            PidValidationError::MissingEntity {
                entity,
                ahb_status,
                severity,
            } => {
                assert_eq!(entity, "Marktlokation");
                assert_eq!(ahb_status, "Muss");
                assert_eq!(severity, &Severity::Error);
            }
            other => panic!("Expected MissingEntity, got: {other:?}"),
        }

        // Display check
        let msg = errors[0].to_string();
        assert!(msg.contains("ERROR"));
        assert!(msg.contains("Marktlokation"));
        assert!(msg.contains("Muss"));
    }

    #[test]
    fn test_validate_missing_field() {
        let reqs = sample_requirements();
        let json = json!({
            "prozessdaten": {
                "transaktionsgrund": "E01"
                // vorgangId is missing
            },
            "marktlokation": {
                "marktlokationsId": "51234567890",
                "haushaltskunde": "Z15"
            },
            "geschaeftspartner": [
                { "identifikation": "9900000000003" }
            ]
        });

        let errors = validate_pid_json(&json, &reqs);
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            PidValidationError::MissingField {
                entity,
                field,
                ahb_status,
                severity,
                ..
            } => {
                assert_eq!(entity, "Prozessdaten");
                assert_eq!(field, "vorgangId");
                assert_eq!(ahb_status, "X");
                assert_eq!(severity, &Severity::Error);
            }
            other => panic!("Expected MissingField, got: {other:?}"),
        }

        let msg = errors[0].to_string();
        assert!(msg.contains("ERROR"));
        assert!(msg.contains("Prozessdaten.vorgangId"));
    }

    #[test]
    fn test_validate_invalid_code() {
        let reqs = sample_requirements();
        let json = json!({
            "prozessdaten": {
                "vorgangId": "ABC123",
                "transaktionsgrund": "E01"
            },
            "marktlokation": {
                "marktlokationsId": "51234567890",
                "haushaltskunde": "Z99"  // Invalid code
            },
            "geschaeftspartner": [
                { "identifikation": "9900000000003" }
            ]
        });

        let errors = validate_pid_json(&json, &reqs);
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            PidValidationError::InvalidCode {
                entity,
                field,
                value,
                valid_values,
            } => {
                assert_eq!(entity, "Marktlokation");
                assert_eq!(field, "haushaltskunde");
                assert_eq!(value, "Z99");
                assert_eq!(valid_values.len(), 2);
                assert!(valid_values.iter().any(|(c, _)| c == "Z15"));
                assert!(valid_values.iter().any(|(c, _)| c == "Z18"));
            }
            other => panic!("Expected InvalidCode, got: {other:?}"),
        }

        let msg = errors[0].to_string();
        assert!(msg.contains("INVALID"));
        assert!(msg.contains("Z99"));
        assert!(msg.contains("Z15"));
    }

    #[test]
    fn test_validate_array_entity() {
        let reqs = sample_requirements();
        let json = json!({
            "prozessdaten": {
                "vorgangId": "ABC123",
                "transaktionsgrund": "E01"
            },
            "marktlokation": {
                "marktlokationsId": "51234567890",
                "haushaltskunde": "Z15"
            },
            "geschaeftspartner": [
                { "identifikation": "9900000000003" },
                { }  // Missing identifikation in second element
            ]
        });

        let errors = validate_pid_json(&json, &reqs);
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            PidValidationError::MissingField { entity, field, .. } => {
                assert_eq!(entity, "Geschaeftspartner");
                assert_eq!(field, "identifikation");
            }
            other => panic!("Expected MissingField, got: {other:?}"),
        }
    }

    #[test]
    fn test_to_camel_case() {
        assert_eq!(to_camel_case("Prozessdaten"), "prozessdaten");
        assert_eq!(
            to_camel_case("RuhendeMarktlokation"),
            "ruhendeMarktlokation"
        );
        assert_eq!(to_camel_case("Marktlokation"), "marktlokation");
        assert_eq!(to_camel_case(""), "");
    }

    #[test]
    fn test_snake_to_camel_case() {
        assert_eq!(snake_to_camel_case("code_codepflege"), "codeCodepflege");
        assert_eq!(snake_to_camel_case("vorgang_id"), "vorgangId");
        assert_eq!(snake_to_camel_case("marktlokation"), "marktlokation");
        assert_eq!(snake_to_camel_case(""), "");
        assert_eq!(snake_to_camel_case("a_b_c"), "aBC");
    }

    /// A field stored as snake_case in requirements (e.g. from TOML) must be found
    /// in JSON that was produced by a typed struct using `#[serde(rename_all = "camelCase")]`.
    #[test]
    fn test_camel_case_fallback_for_snake_case_bo4e_name() {
        let reqs = PidRequirements {
            pid: "55077".to_string(),
            beschreibung: "Test camelCase fallback".to_string(),
            entities: vec![EntityRequirement {
                entity: "Zuordnung".to_string(),
                ref_type: Bo4eRefType::Object {
                    type_name: "Zuordnung".to_string(),

                    cardinality: Cardinality::REQUIRED,
                },

                ahb_status: "Muss".to_string(),
                map_key: None,
                scope: EntityScope::Transaction,
                variants: vec![],
                fields: vec![
                    FieldRequirement {
                        // snake_case as stored in TOML requirements
                        bo4e_name: "code_codepflege".to_string(),
                        ahb_status: "X".to_string(),
                        field_type: "data".to_string(),
                        format: None,
                        enum_name: None,
                        valid_codes: vec![],
                        child_group: None,
                        ref_type: Bo4eRefType::Unknown,
                    },
                    FieldRequirement {
                        bo4e_name: "codeliste".to_string(),
                        ahb_status: "X".to_string(),
                        field_type: "data".to_string(),
                        format: None,
                        enum_name: None,
                        valid_codes: vec![],
                        child_group: None,
                        ref_type: Bo4eRefType::Unknown,
                    },
                ],
            }],
        };

        // JSON produced by a typed struct with #[serde(rename_all = "camelCase")]:
        // code_codepflege → codeCodepflege
        let json_camel = json!({
            "zuordnung": {
                "codeCodepflege": "DE_BDEW",
                "codeliste": "6"
            }
        });

        let errors = validate_pid_json(&json_camel, &reqs);
        assert!(
            errors.is_empty(),
            "Expected no errors when field is present under camelCase key, got: {errors:?}"
        );

        // Also verify that snake_case key in JSON still works (backward compat).
        let json_snake = json!({
            "zuordnung": {
                "code_codepflege": "DE_BDEW",
                "codeliste": "6"
            }
        });

        let errors = validate_pid_json(&json_snake, &reqs);
        assert!(
            errors.is_empty(),
            "Expected no errors when field is present under snake_case key, got: {errors:?}"
        );

        // When the field is truly absent, a MissingField error must still be raised.
        let json_missing = json!({
            "zuordnung": {
                "codeliste": "6"
            }
        });

        let errors = validate_pid_json(&json_missing, &reqs);
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            PidValidationError::MissingField { field, .. } => {
                assert_eq!(field, "code_codepflege");
            }
            other => panic!("Expected MissingField, got: {other:?}"),
        }
    }

    #[test]
    fn test_is_unconditionally_required() {
        assert!(is_unconditionally_required("X"));
        assert!(is_unconditionally_required("Muss"));
        assert!(is_unconditionally_required("Soll"));
        assert!(!is_unconditionally_required("Kann"));
        assert!(!is_unconditionally_required("[1]"));
        assert!(!is_unconditionally_required(""));
    }

    #[test]
    fn test_validation_report_display() {
        let errors = vec![
            PidValidationError::MissingEntity {
                entity: "Marktlokation".to_string(),
                ahb_status: "Muss".to_string(),
                severity: Severity::Error,
            },
            PidValidationError::MissingField {
                entity: "Prozessdaten".to_string(),
                field: "vorgangId".to_string(),
                ahb_status: "X".to_string(),
                rust_type: None,
                valid_values: vec![],
                severity: Severity::Error,
            },
        ];
        let report = ValidationReport(errors);
        assert!(report.has_errors());
        assert_eq!(report.len(), 2);
        assert!(!report.is_empty());

        let display = report.to_string();
        assert!(display.contains("missing entity 'Marktlokation'"));
        assert!(display.contains("missing Prozessdaten.vorgangId"));
    }

    #[test]
    fn test_missing_field_with_type_and_values_display() {
        let err = PidValidationError::MissingField {
            entity: "Marktlokation".to_string(),
            field: "haushaltskunde".to_string(),
            ahb_status: "Muss".to_string(),
            rust_type: Some("Haushaltskunde".to_string()),
            valid_values: vec![
                ("Z15".to_string(), "Ja".to_string()),
                ("Z18".to_string(), "Nein".to_string()),
            ],
            severity: Severity::Error,
        };
        let msg = err.to_string();
        assert!(msg.contains("type: Haushaltskunde"));
        assert!(msg.contains("valid: Z15 (Ja), Z18 (Nein)"));
    }

    #[test]
    fn test_optional_fields_not_flagged() {
        let reqs = PidRequirements {
            pid: "99999".to_string(),
            beschreibung: "Test".to_string(),
            entities: vec![EntityRequirement {
                entity: "Test".to_string(),
                ref_type: Bo4eRefType::Object {
                    type_name: "Test".to_string(),

                    cardinality: Cardinality::OPTIONAL,
                },

                ahb_status: "Kann".to_string(),
                map_key: None,
                scope: EntityScope::Transaction,
                variants: vec![],
                fields: vec![FieldRequirement {
                    bo4e_name: "optionalField".to_string(),
                    ahb_status: "Kann".to_string(),
                    field_type: "data".to_string(),
                    format: None,
                    enum_name: None,
                    valid_codes: vec![],
                    child_group: None,
                    ref_type: Bo4eRefType::Unknown,
                }],
            }],
        };

        // Entity missing but optional — no error
        let errors = validate_pid_json(&json!({}), &reqs);
        assert!(errors.is_empty());

        // Entity present, field missing but optional — no error
        let errors = validate_pid_json(&json!({ "test": {} }), &reqs);
        assert!(errors.is_empty());
    }

    /// Regression test for issue #48: nested dot-path fields reported as missing
    /// even when present (e.g. `produktIdentifikation.funktion`).
    #[test]
    fn test_nested_dot_path_fields_not_falsely_missing() {
        let reqs = PidRequirements {
            pid: "55001".to_string(),
            beschreibung: "Test nested paths".to_string(),
            entities: vec![EntityRequirement {
                entity: "ProduktpaketDaten".to_string(),
                ref_type: Bo4eRefType::Object {
                    type_name: "ProduktpaketDaten".to_string(),

                    cardinality: Cardinality {
                        min: 1,
                        max: Some(99999),
                    },
                },

                ahb_status: "Muss".to_string(),
                map_key: None,
                scope: EntityScope::Transaction,
                variants: vec![],
                fields: vec![
                    FieldRequirement {
                        bo4e_name: "produktIdentifikation.funktion".to_string(),
                        ahb_status: "X".to_string(),
                        field_type: "code".to_string(),
                        format: None,
                        enum_name: Some("Produktidentifikation".to_string()),
                        valid_codes: vec![CodeValue {
                            code: "5".to_string(),
                            meaning: "Produktidentifikation".to_string(),
                            enum_name: None,
                            bo4e_value: None,
                        }],
                        child_group: None,
                        ref_type: Bo4eRefType::Unknown,
                    },
                    FieldRequirement {
                        bo4e_name: "produktMerkmal.code".to_string(),
                        ahb_status: "X".to_string(),
                        field_type: "code".to_string(),
                        format: None,
                        enum_name: None,
                        valid_codes: vec![],
                        child_group: None,
                        ref_type: Bo4eRefType::Unknown,
                    },
                ],
            }],
        };

        // Exact JSON from issue #48
        let json = json!({
            "produktpaketDaten": [{
                "produktIdentifikation": { "funktion": "5", "id": "9991000002082", "typ": "Z11" },
                "produktMerkmal": { "code": "ZH9" }
            }]
        });

        let errors = validate_pid_json(&json, &reqs);
        assert!(
            errors.is_empty(),
            "Nested dot-path fields should be found (issue #48), got: {errors:?}"
        );
    }

    #[test]
    fn test_nested_dot_path_truly_missing() {
        let reqs = PidRequirements {
            pid: "55001".to_string(),
            beschreibung: "Test nested paths missing".to_string(),
            entities: vec![EntityRequirement {
                entity: "ProduktpaketDaten".to_string(),
                ref_type: Bo4eRefType::Object {
                    type_name: "ProduktpaketDaten".to_string(),

                    cardinality: Cardinality {
                        min: 1,
                        max: Some(99999),
                    },
                },

                ahb_status: "Muss".to_string(),
                map_key: None,
                scope: EntityScope::Transaction,
                variants: vec![],
                fields: vec![FieldRequirement {
                    bo4e_name: "produktIdentifikation.funktion".to_string(),
                    ahb_status: "X".to_string(),
                    field_type: "data".to_string(),
                    format: None,
                    enum_name: None,
                    valid_codes: vec![],
                    child_group: None,
                    ref_type: Bo4eRefType::Unknown,
                }],
            }],
        };

        // Parent exists but nested field is missing
        let json = json!({
            "produktpaketDaten": [{
                "produktIdentifikation": { "id": "123" }
            }]
        });

        let errors = validate_pid_json(&json, &reqs);
        assert_eq!(errors.len(), 1, "Should report missing nested field");
        match &errors[0] {
            PidValidationError::MissingField { field, .. } => {
                assert_eq!(field, "produktIdentifikation.funktion");
            }
            other => panic!("Expected MissingField, got: {other:?}"),
        }
    }

    fn field(name: &str, status: &str, codes: &[(&str, &str)]) -> FieldRequirement {
        FieldRequirement {
            bo4e_name: name.to_string(),
            ahb_status: status.to_string(),
            field_type: if codes.is_empty() { "data" } else { "code" }.to_string(),
            format: None,
            enum_name: None,
            valid_codes: codes
                .iter()
                .map(|(code, mapped)| CodeValue {
                    code: code.to_string(),
                    meaning: String::new(),
                    enum_name: None,
                    bo4e_value: Some(mapped.to_string()),
                })
                .collect(),
            child_group: None,
            ref_type: Bo4eRefType::Unknown,
        }
    }

    /// Geschaeftspartner fed by two NAD variants: Z03 (address, no name) and
    /// Z07 (name, no address), shaped like PID 55042 (issue #104).
    fn multi_variant_requirements() -> PidRequirements {
        let z03 = ("Z03", "messlokationsadresse");
        let z07 = ("Z07", "kundeMsb");
        PidRequirements {
            pid: "55042".to_string(),
            beschreibung: String::new(),
            entities: vec![EntityRequirement {
                entity: "Geschaeftspartner".to_string(),
                ref_type: Bo4eRefType::Object {
                    type_name: "Geschaeftspartner".to_string(),
                    cardinality: Cardinality {
                        min: 1,
                        max: Some(99),
                    },
                },
                ahb_status: "Muss".to_string(),
                // Entity-level union, as built from the merged schema groups.
                fields: vec![
                    field("adresse.ort", "X", &[]),
                    field("name1", "X", &[]),
                    field("partnerrolle", "X", &[z03, z07]),
                ],
                map_key: None,
                scope: EntityScope::Transaction,
                variants: vec![
                    EntityVariantRequirement {
                        discriminator_field: "partnerrolle".to_string(),
                        code: "Z03".to_string(),
                        bo4e_value: Some("messlokationsadresse".to_string()),
                        source_paths: vec!["sg4.sg12_z03".to_string()],
                        fields: vec![
                            field("adresse.ort", "X", &[]),
                            field("partnerrolle", "X", &[z03]),
                        ],
                    },
                    EntityVariantRequirement {
                        discriminator_field: "partnerrolle".to_string(),
                        code: "Z07".to_string(),
                        bo4e_value: Some("kundeMsb".to_string()),
                        source_paths: vec!["sg4.sg12_z07".to_string()],
                        fields: vec![field("name1", "X", &[]), field("partnerrolle", "X", &[z07])],
                    },
                ],
            }],
        }
    }

    #[test]
    fn multi_variant_entity_uses_the_elements_own_variant() {
        let reqs = multi_variant_requirements();
        // Every spelling of the qualifier: raw code / enum_map name, string / object.
        let json = json!({
            "geschaeftspartner": [
                { "partnerrolle": "Z03", "adresse": { "ort": "Berlin" } },
                { "partnerrolle": "kundeMsb", "name1": "Muster" },
                { "partnerrolle": { "code": "messlokationsadresse", "meaning": "x" },
                  "adresse": { "ort": "Köln" } },
                { "partnerrolle": { "code": "Z07" }, "name1": "Beispiel" },
            ]
        });
        let errors = validate_pid_json(&json, &reqs);
        assert!(errors.is_empty(), "{}", ValidationReport(errors));
    }

    #[test]
    fn multi_variant_entity_reports_variant_required_fields() {
        let reqs = multi_variant_requirements();
        let json = json!({ "geschaeftspartner": [{ "partnerrolle": "kundeMsb" }] });
        let errors = validate_pid_json(&json, &reqs);
        assert_eq!(errors.len(), 1, "{}", ValidationReport(errors));
        assert!(matches!(
            &errors[0],
            PidValidationError::MissingField { field, .. } if field == "name1"
        ));
    }

    #[test]
    fn multi_variant_entity_unknown_qualifier_is_invalid_code_only() {
        let reqs = multi_variant_requirements();
        for bad in [json!("Z99"), json!("bogus"), json!({ "code": "Z99" })] {
            let json = json!({ "geschaeftspartner": [{ "partnerrolle": bad }] });
            let errors = validate_pid_json(&json, &reqs);
            // No variant matches: variant fields become optional, codes are unioned.
            assert_eq!(errors.len(), 1, "{bad}: {}", ValidationReport(errors));
            match &errors[0] {
                PidValidationError::InvalidCode {
                    field,
                    valid_values,
                    ..
                } => {
                    assert_eq!(field, "partnerrolle");
                    let codes: Vec<&str> = valid_values.iter().map(|(c, _)| c.as_str()).collect();
                    assert_eq!(codes, ["Z03", "Z07"]);
                }
                other => panic!("expected InvalidCode, got {other:?}"),
            }
        }
    }

    #[test]
    fn code_objects_and_enum_mapped_names_are_code_checked() {
        let f = field("partnerrolle", "X", &[("Z07", "kundeMsb")]);
        assert_eq!(invalid_code_value(&json!("Z07"), &f), None);
        assert_eq!(invalid_code_value(&json!("kundeMsb"), &f), None);
        assert_eq!(invalid_code_value(&json!({ "code": "kundeMsb" }), &f), None);
        assert_eq!(invalid_code_value(&json!({ "code": "Z07" }), &f), None);
        assert_eq!(
            invalid_code_value(&json!({ "code": "Z99", "meaning": null }), &f),
            Some("Z99".to_string())
        );
        assert_eq!(
            invalid_code_value(&json!("kundeLf"), &f),
            Some("kundeLf".to_string())
        );
        // Non-code values (numbers, objects without code) are not code-checked.
        assert_eq!(invalid_code_value(&json!(7), &f), None);
        assert_eq!(invalid_code_value(&json!({ "meaning": "x" }), &f), None);
    }
}