edifact-mapper 0.30.5

EDIFACT to BO4E bidirectional conversion 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
//! Condition-aware PID validation.
//!
//! Extends the basic [`validate_pid_json`](mig_bo4e::pid_validation::validate_pid_json)
//! by evaluating AHB condition expressions to determine whether fields are truly
//! required based on the actual EDIFACT data context.

use automapper_validation::eval::GroupScope;
use automapper_validation::{packages_allow_none, requiredness};
use automapper_validation::{
    refuses_presence, AbsentTarget, ConditionEvaluator, ConditionExprEvaluator, ConditionResult,
    EvaluationContext,
};
use mig_bo4e::pid_requirements::{
    CodeValue, EntityRequirement, FieldRequirement, FieldSegment, PidRequirements,
};
use mig_bo4e::pid_validation::{
    code_field_value, effective_field_requirements, fields_of_unrequired_absent_groups, get_nested,
    invalid_code_value, not_allowed_codes, PidValidationError, Severity,
};
use mig_types::segment::OwnedSegment;
use serde_json::Value;
use std::collections::HashMap;

use crate::element_scopes::{ElementKey, InstancePath, NestedKey};

/// Validate a BO4E JSON value against PID requirements with AHB condition awareness.
///
/// Unlike [`validate_pid_json`](mig_bo4e::pid_validation::validate_pid_json), this
/// evaluates AHB condition expressions (e.g., `[1]`, `[2] ∧ [3]`) using the provided
/// evaluator and context to determine whether conditional fields are actually required.
///
/// - `X`, `Muss`, `Soll` are always required (Error if missing)
/// - `Kann`, empty string are never required (skipped)
/// - Condition expressions are evaluated: True = Error, False = skip, Unknown = Warning
///
/// Something missing is judged with the message type's "Wenn vorhanden"
/// condition `False` (see [`AbsentTarget`]): an absent `Soll [166]` group is
/// not missing. In an entity fed by several segment groups, the fields of a
/// group the element has no data for are demanded only if that group's own
/// status evaluates to `True`.
///
/// Something present — an entity element, a list element, a code sent in a
/// segment of its own condition — is reported as
/// [`PidValidationError::NotAllowed`] (a warning) where its `Muss`/`X` status
/// has a condition that is false where it sits (see [`refuses_presence`]). Only
/// in its exact group instance, and only when the input carries the message's
/// own data (its BGM): the conditions of a message cannot be judged without it.
pub fn validate_with_conditions<E: ConditionEvaluator>(
    json: &Value,
    requirements: &PidRequirements,
    expr_eval: &ConditionExprEvaluator<'_, E>,
    ctx: &EvaluationContext,
) -> Vec<PidValidationError> {
    validate(json, requirements, expr_eval, ctx, None, None)
}

fn validate<E: ConditionEvaluator>(
    json: &Value,
    requirements: &PidRequirements,
    expr_eval: &ConditionExprEvaluator<'_, E>,
    ctx: &EvaluationContext,
    scopes: Option<&HashMap<ElementKey, InstancePath>>,
    nested: Option<&HashMap<NestedKey, InstancePath>>,
) -> Vec<PidValidationError> {
    // What is missing is judged with "Wenn vorhanden" false (see
    // [`AbsentTarget`]), what is present with it true (see [`refuses_presence`]).
    let present = expr_eval;
    let absent = AbsentTarget(expr_eval.evaluator());
    let expr_eval = &ConditionExprEvaluator::new(&absent);
    let mut errors = Vec::new();

    for entity_req in &requirements.entities {
        let key = to_camel_case(&entity_req.entity);
        // The input is one transaction. Where the transaction repeats, a
        // message-level value's condition may read the others ("Wenn SG27
        // LIN++Z64 vorhanden" for QUOTES 15004's Meldepunkt), which the input
        // does not hold: its value is not judged then.
        let judge_values = !(requirements.transaktion_wiederholbar
            && entity_req.scope == mig_bo4e::pid_requirements::EntityScope::Message);

        match json.get(&key) {
            None => {
                if let Some(severity) =
                    evaluate_ahb_requirement(&entity_req.ahb_status, expr_eval, ctx)
                {
                    errors.push(PidValidationError::MissingEntity {
                        entity: entity_req.entity.clone(),
                        ahb_status: entity_req.ahb_status.clone(),
                        severity,
                    });
                }
            }
            Some(val) => {
                // An array is one element per repetition, whatever the schema
                // says the group allows: the merged SG6 of UTILMD Strom 55043
                // counts MaxRep 1 though its RFF+Z50 variant repeats per MaLo.
                if let Some(arr) = val.as_array() {
                    if let Some((once, _)) = automapper_validation::once_per_transaction(
                        expr_eval.evaluator().message_type(),
                    ) {
                        errors.extend(repeated_in_transaction(entity_req, arr, once));
                    }
                    for (index, element) in arr.iter().enumerate() {
                        let path = scope_of(scopes, &key, Some(index));
                        let at = nested_scope_of(nested, &key, Some(index));
                        in_scope(ctx, path.as_deref(), |ctx| {
                            validate_entity_fields_with_conditions(
                                element,
                                entity_req,
                                expr_eval,
                                present,
                                ctx,
                                &at,
                                judge_values,
                                &mut errors,
                            )
                        });
                    }
                } else {
                    // A single object: one repetition.
                    let path = scope_of(scopes, &key, None);
                    let at = nested_scope_of(nested, &key, None);
                    in_scope(ctx, path.as_deref(), |ctx| {
                        validate_entity_fields_with_conditions(
                            val,
                            entity_req,
                            expr_eval,
                            present,
                            ctx,
                            &at,
                            judge_values,
                            &mut errors,
                        )
                    });
                }
            }
        }
    }

    errors
}

/// The groups an entity's elements come from that their AHB allows once per
/// transaction (`once`, see [`automapper_validation::binds_once`]) but that the
/// elements fill more often. An element is counted for each group it has data
/// of its own from, for its variant, or for the entity's own status.
fn repeated_in_transaction(
    entity_req: &EntityRequirement,
    elements: &[Value],
    once: u32,
) -> Vec<PidValidationError> {
    let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
    for element in elements {
        let statuses = element_statuses(entity_req, element);
        for status in statuses {
            if automapper_validation::binds_once(status, once) {
                *counts.entry(status).or_insert(0) += 1;
            }
        }
    }
    counts
        .into_iter()
        .filter(|(_, count)| *count > 1)
        .map(
            |(status, count)| PidValidationError::RepeatedInTransaction {
                entity: entity_req.entity.clone(),
                count,
                ahb_status: status.to_string(),
            },
        )
        .collect()
}

/// The scope of one entity element, as the borrowed path a [`GroupScope`] takes.
fn scope_of<'s>(
    scopes: Option<&'s HashMap<ElementKey, InstancePath>>,
    key: &str,
    index: Option<usize>,
) -> Option<Vec<(&'s str, usize)>> {
    scopes?
        .get(&(key.to_string(), index))
        .map(|path| path.iter().map(|(g, i)| (g.as_str(), *i)).collect())
}

/// Where the elements of an entity element's nested lists sit: the instance
/// path of the list element at a position (`[("zuordnungen", 3)]`).
fn nested_scope_of<'s>(
    nested: Option<&'s HashMap<NestedKey, InstancePath>>,
    key: &str,
    index: Option<usize>,
) -> impl Fn(&[(String, usize)]) -> Option<&'s InstancePath> + 's {
    let element: ElementKey = (key.to_string(), index);
    move |position: &[(String, usize)]| nested?.get(&(element.clone(), position.to_vec()))
}

/// Run `f` with `ctx` narrowed to `path`, or with `ctx` itself without one.
fn in_scope<R>(
    ctx: &EvaluationContext,
    path: Option<&[(&str, usize)]>,
    f: impl FnOnce(&EvaluationContext) -> R,
) -> R {
    match path {
        Some(path) => f(&ctx.with_scope(GroupScope { path })),
        None => f(ctx),
    }
}

/// [`validate_with_conditions`], evaluating each entity element in the group
/// instance it becomes, and each element of its nested lists in its own
/// (see [`crate::element_scopes`]).
pub fn validate_with_conditions_in_scopes<E: ConditionEvaluator>(
    json: &Value,
    requirements: &PidRequirements,
    expr_eval: &ConditionExprEvaluator<'_, E>,
    ctx: &EvaluationContext,
    scopes: &HashMap<ElementKey, InstancePath>,
    nested: &HashMap<NestedKey, InstancePath>,
) -> Vec<PidValidationError> {
    validate(
        json,
        requirements,
        expr_eval,
        ctx,
        Some(scopes),
        Some(nested),
    )
}

/// Validate fields within a single entity using condition-aware evaluation.
#[allow(clippy::too_many_arguments)]
fn validate_entity_fields_with_conditions<'s, E: ConditionEvaluator, P: ConditionEvaluator>(
    entity_json: &Value,
    entity_req: &EntityRequirement,
    expr_eval: &ConditionExprEvaluator<'_, E>,
    present: &ConditionExprEvaluator<'_, P>,
    ctx: &EvaluationContext,
    nested_at: &dyn Fn(&[(String, usize)]) -> Option<&'s InstancePath>,
    judge_values: bool,
    errors: &mut Vec<PidValidationError>,
) {
    // What the element carries is judged where it sits; without an exact
    // instance a "dieser SG8" condition cannot be told, and without the
    // message's own data (BGM, NAD) its conditions cannot, so nothing is
    // refused then.
    if ctx.scope.is_some() && judges_presence(ctx) {
        let forbidden = |status: &str| not_allowed(status, present, ctx);
        // The element itself: the status of every group it has data from (an
        // entity fed by several groups: data only that group writes), or the
        // entity's.
        // An entity fed by the variants of one group (QUOTES SG28 CCI+++E13 …
        // CCI+++Z76 as `VorgangZuordnung`) is judged by the element's variant.
        let statuses = element_statuses(entity_req, entity_json);
        let refused: Vec<&str> = statuses.into_iter().filter(|s| forbidden(s)).collect();
        for status in &refused {
            errors.push(PidValidationError::NotAllowed {
                entity: entity_req.entity.clone(),
                field: String::new(),
                value: None,
                ahb_status: status.to_string(),
                severity: Severity::Warning,
            });
        }
        // A code sent in a segment of its own condition (SG10 CAV+ZB4), and a
        // field of a segment of its own condition: FTX+ACB `Muss [23]`,
        // DTM+Z07 `Muss [358]` under another answer. The field's status joins
        // its segment's condition and its own; a value its own condition
        // refuses is the value check's business, so only a status the
        // element's alone does not refuse reports its segment.
        if refused.is_empty() {
            let fields = effective_field_requirements(entity_req, entity_json);
            errors.extend(not_allowed_codes(
                &entity_req.entity,
                "",
                &fields,
                entity_json,
                &forbidden,
            ));
            for field_req in fields.iter() {
                let present =
                    get_nested(entity_json, &field_req.bo4e_name).is_some_and(|v| !v.is_null());
                if present
                    && field_req.ahb_status != field_req.element_status
                    && forbidden(&field_req.ahb_status)
                    && !forbidden(&field_req.element_status)
                {
                    errors.push(PidValidationError::NotAllowed {
                        entity: entity_req.entity.clone(),
                        field: field_req.bo4e_name.clone(),
                        value: None,
                        ahb_status: field_req.ahb_status.clone(),
                        severity: Severity::Warning,
                    });
                }
            }
        }
    }
    // Multi-variant entities (e.g. Geschaeftspartner from several SG12 groups) are
    // checked against the variant selected by the element's qualifier.
    let fields = effective_field_requirements(entity_req, entity_json);
    // Unknown counts as not required, as for a group condition in `EdifactValidator`.
    let exempt = fields_of_unrequired_absent_groups(entity_req, entity_json, |status| {
        evaluate_ahb_requirement(status, expr_eval, ctx) == Some(Severity::Error)
    });
    // A value is judged against its element's condition only where the
    // groups it sits in apply — the EDIFACT validator skips a field whose
    // parent group's condition does not hold or cannot be told.
    let group_applies = element_statuses(entity_req, entity_json)
        .iter()
        .all(|status| present.evaluate_status(status, ctx) == ConditionResult::True);
    for field_req in fields.iter() {
        // Dot paths (e.g. "adresse.ort") address nested objects; null = not provided.
        match get_nested(entity_json, &field_req.bo4e_name).filter(|v| !v.is_null()) {
            None if exempt.contains(field_req.bo4e_name.as_str()) => {}
            None => {
                if let Some(severity) =
                    evaluate_ahb_requirement(&field_req.ahb_status, expr_eval, ctx)
                {
                    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,
                    });
                }
            }
            Some(val) => {
                // Code validation happens unconditionally — valid codes don't depend
                // on conditions. Plain strings and `{code, …}` objects are both
                // checked, in raw-code and enum_map-translated spelling.
                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),
                    });
                } else if group_applies
                    && judge_values
                    && breaks_its_condition(field_req, val, present, ctx)
                {
                    errors.push(PidValidationError::ConditionNotSatisfied {
                        entity: entity_req.entity.clone(),
                        field: field_req.bo4e_name.clone(),
                        value: code_field_value(val).unwrap_or_default().to_string(),
                        ahb_status: field_req.element_status.clone(),
                    });
                }
                errors.extend(mig_bo4e::pid_validation::too_long(
                    &entity_req.entity,
                    &field_req.bo4e_name,
                    val,
                    field_req,
                ));
                errors.extend(mig_bo4e::pid_validation::not_a_number(
                    &entity_req.entity,
                    &field_req.bo4e_name,
                    val,
                    field_req,
                ));
            }
        }
    }
    mig_bo4e::pid_validation::validate_nested_lists(
        &entity_req.entity,
        entity_json,
        &entity_req.nested,
        "",
        // A list element's parts are judged in its own group instance ("im
        // selben CCI" reads that element's SG10), the list in the element's.
        &|status, position| match nested_at(position).filter(|_| judges_presence(ctx)) {
            Some(path) => {
                let path: Vec<(&str, usize)> = path.iter().map(|(g, i)| (g.as_str(), *i)).collect();
                evaluate_ahb_requirement(
                    status,
                    expr_eval,
                    &ctx.with_scope(GroupScope { path: &path }),
                )
            }
            None => evaluate_ahb_requirement(status, expr_eval, ctx),
        },
        &|variant| variant_holds(ctx, variant),
        &|status, position| match nested_at(position).filter(|_| judges_presence(ctx)) {
            Some(path) => {
                let path: Vec<(&str, usize)> = path.iter().map(|(g, i)| (g.as_str(), *i)).collect();
                not_allowed(status, present, &ctx.with_scope(GroupScope { path: &path }))
            }
            None => false,
        },
        errors,
    );
}

/// The group statuses an entity element is judged by: those of the groups it
/// has data of its own from (an entity fed by several groups), of its variant
/// (an entity fed by the variants of one group, QUOTES SG28 CCI+++E13 …
/// CCI+++Z76 as `VorgangZuordnung`), or the entity's.
fn element_statuses<'r>(entity_req: &'r EntityRequirement, entity_json: &Value) -> Vec<&'r str> {
    let variants = mig_bo4e::pid_validation::variant_statuses(entity_req, entity_json);
    if entity_req.groups.is_empty() && !variants.is_empty() {
        variants
    } else if entity_req.groups.is_empty() {
        vec![entity_req.ahb_status.as_str()]
    } else {
        entity_req
            .groups
            .iter()
            .filter(|g| {
                g.fields.iter().any(|f| {
                    entity_req
                        .groups
                        .iter()
                        .filter(|other| other.source_path != g.source_path)
                        .all(|other| !other.fields.contains(f))
                        && get_nested(entity_json, f).is_some_and(|v| !v.is_null())
                })
            })
            .map(|g| g.ahb_status.as_str())
            .collect()
    }
}

/// Whether the input carries the message's own data: its BGM. Without it a
/// condition on the message ("Wenn BGM+E03 vorhanden") reads false.
fn judges_presence(ctx: &EvaluationContext) -> bool {
    !ctx.find_segments("BGM").is_empty()
}

/// Whether something present under `status` is not allowed where `ctx` is; see
/// [`refuses_presence`].
fn not_allowed<E: ConditionEvaluator>(
    status: &str,
    eval: &ConditionExprEvaluator<'_, E>,
    ctx: &EvaluationContext,
) -> bool {
    refuses_presence(status, eval.evaluator(), ctx, &Default::default())
}

/// Evaluate an AHB status string to determine whether a field is required.
///
/// Returns:
/// - `Some(Severity::Error)` if unconditionally required or condition evaluates to True
/// - `Some(Severity::Warning)` if condition evaluates to Unknown
/// - `None` if not required (Kann/empty) or condition evaluates to False
fn evaluate_ahb_requirement<E: ConditionEvaluator>(
    ahb_status: &str,
    expr_eval: &ConditionExprEvaluator<'_, E>,
    ctx: &EvaluationContext,
) -> Option<Severity> {
    match ahb_status.trim() {
        "X" | "Muss" | "Soll" => Some(Severity::Error),
        "Kann" | "K" | "" => None,
        // "Kann [n]" / "K [n]": optional whatever the condition says.
        status if status.starts_with("Kann") || status.starts_with("K ") => None,
        // Several lines ("Muss [96] ∧ [688]\nSoll [46] ∧ [688]"): as written.
        status if status.contains('\n') => severity_of(expr_eval.evaluate_status(status, ctx)),
        status => {
            // What is missing cannot fail a format or a note: only the rest
            // decides ([`requiredness`]). A package that needs no code
            // (`S [9P0..1]`) requires nothing.
            let Ok(Some(expr)) = automapper_validation::ConditionParser::parse(status) else {
                return severity_of(expr_eval.evaluate_status(status, ctx));
            };
            if packages_allow_none(&expr) {
                return None;
            }
            match requiredness(&expr) {
                Some(expr) => severity_of(expr_eval.evaluate(&expr, ctx)),
                None if matches!(status_keyword(status), "X" | "Muss" | "M" | "Soll" | "S") => {
                    Some(Severity::Error)
                }
                None => None,
            }
        }
    }
}

fn severity_of(result: ConditionResult) -> Option<Severity> {
    match result {
        ConditionResult::True => Some(Severity::Error),
        ConditionResult::False => None,
        ConditionResult::Unknown => Some(Severity::Warning),
    }
}

/// The requirement keyword of a status: `X`, `Muss`, `M`, `Soll`, `S`, `Kann`.
fn status_keyword(status: &str) -> &str {
    let s = status.trim_start();
    &s[..s.find(|c: char| !c.is_alphabetic()).unwrap_or(s.len())]
}

/// Whether the present value `val` breaks its own element's condition — the
/// AHB's statement of what the value must be: `[360]` "nur Antwortcodes aus
/// dem Cluster Zustimmung" with A50, `[914]` "> 0" with `O5D2DXBG1A`. The
/// condition is read with the value resolved, in the segment it came from,
/// as the EDIFACT validator reads it (AHB003 FieldConditionNotSatisfied).
///
/// Only for a `Muss`/`X` element status of one line, without packages, whose
/// field the requirements did not relax (a field merged from several sources
/// carries no single element status).
fn breaks_its_condition<E: ConditionEvaluator>(
    field_req: &FieldRequirement,
    val: &Value,
    eval: &ConditionExprEvaluator<'_, E>,
    ctx: &EvaluationContext,
) -> bool {
    // Only where everything the element sits in applies: its enclosing groups
    // and its segment (`parent_group_ahb_status`). The EDIFACT validator skips
    // the field otherwise (`should_skip_for_parent_group`); the group or
    // segment that should not be there is reported apart.
    let context = field_req.context_status.trim();
    if context.contains('\n')
        || (context.contains('[') && eval.evaluate_status(context, ctx) != ConditionResult::True)
    {
        return false;
    }
    let Some(value) = code_field_value(val) else {
        return false;
    };
    // The value sent: a name the mapping translated back to its code.
    let raw = field_req
        .valid_codes
        .iter()
        .find(|cv| cv.bo4e_value.as_deref() == Some(value))
        .map_or(value, |cv| cv.code.as_str());
    let status = status_of_the_code_sent(field_req, raw);
    let package = status.split('[').skip(1).any(|term| {
        term.trim_start_matches(|c: char| c.is_ascii_digit())
            .starts_with('P')
    });
    // A list target (`werte[].text`) has a segment per element; which one
    // this value came from is not known here.
    if field_req.bo4e_name.contains("[]")
        || status.contains('\n')
        || !status.contains('[')
        || package
        // As the EDIFACT validator reads a status word (`StatusKind`); the
        // AHB parser writes the documents' abbreviations (`M`) out in full.
        || !matches!(status_keyword(status), "X" | "Muss")
        || !matches!(
            status_keyword(&field_req.ahb_status),
            "X" | "Muss" | "M" | "Soll" | "S"
        )
    {
        return false;
    }
    let segment = field_req
        .segment
        .as_ref()
        .and_then(|at| segment_of(at, ctx));
    let at_value = EvaluationContext {
        resolved_value: Some(raw),
        resolved_segment: segment.as_ref().map(|s| s.elements.as_slice()),
        ..*ctx
    };
    eval.evaluate_status(status, &at_value) == ConditionResult::False
}

/// The status a present value is judged by: the element's, or — where the AHB
/// gives the status per code and the schema took the first code's for the
/// element — the status of the code sent. UTILMD 55010's Transaktionsgrund
/// lists E01 `X [192]` and E03 `X`; an E03 is not judged by `[192]`. 55643's
/// SEQ+Z20 RFF lists MG `X [204]` and Z14 `X` in a `Muss [665]` segment; a Z14
/// is not judged by `[204]`. The codes' own statuses, not the conditions they
/// are sent under ([`CodeValue::ahb_status`], which joins the segment's). As
/// the EDIFACT validator reads it (`governing_status`).
///
/// [`CodeValue::ahb_status`]: mig_bo4e::pid_requirements::CodeValue::ahb_status
fn status_of_the_code_sent<'r>(field_req: &'r FieldRequirement, raw: &str) -> &'r str {
    let status = field_req.element_status.trim();
    let first = field_req
        .valid_codes
        .first()
        .and_then(|cv| cv.code_status.as_deref());
    if !first.is_some_and(|s| s.trim() == status) {
        return status;
    }
    field_req
        .valid_codes
        .iter()
        .find(|cv| cv.code == raw)
        .map_or(status, |cv| cv.code_status.as_deref().unwrap_or("").trim())
}

/// The segment `at` names in the element's group instance — its own segments
/// first, then the groups nested in it — or, without a scope, the message's.
fn segment_of(at: &FieldSegment, ctx: &EvaluationContext) -> Option<OwnedSegment> {
    let selected = |s: &OwnedSegment| {
        at.codes.is_empty()
            || at
                .codes
                .iter()
                .any(|c| s.get_component(at.site.0, at.site.1) == c)
    };
    let pick =
        |segments: Vec<OwnedSegment>| segments.into_iter().filter(selected).nth(at.occurrence);
    match (ctx.scope, ctx.navigator()) {
        (Some(scope), Some(nav)) => pick(nav.find_segments_in_instance(&at.tag, scope.path))
            .or_else(|| pick(nav.find_segments_in_subtree(&at.tag, scope.path))),
        _ => pick(ctx.find_segments(&at.tag).into_iter().cloned().collect()),
    }
}

/// Convert PascalCase entity name to camelCase JSON key.
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 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()
}

/// Whether the group instance the element sits in is `variant` — its entry
/// segment (55070's SG4 IDE) carries one of the variant's qualifiers. `None`
/// without a scope reaching that group.
fn variant_holds(
    ctx: &EvaluationContext,
    variant: &mig_bo4e::pid_requirements::VariantQualifier,
) -> Option<bool> {
    let scope = ctx.scope?;
    let level = scope
        .path
        .iter()
        .position(|(group, _)| group.eq_ignore_ascii_case(&variant.group))?;
    let entry = ctx
        .find_segments_at(&scope.path[..=level], &variant.segment)
        .into_iter()
        .next()?;
    Some(
        variant
            .codes
            .iter()
            .any(|code| code == entry.get_element(0)),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn optional_statuses_are_never_required() {
        use automapper_validation::MapExternalProvider;

        struct NoConditions;
        impl ConditionEvaluator for NoConditions {
            fn evaluate(&self, _: u32, _: &EvaluationContext) -> ConditionResult {
                ConditionResult::True
            }
            fn is_external(&self, _: u32) -> bool {
                false
            }
            fn message_type(&self) -> &str {
                "UTILMD"
            }
            fn format_version(&self) -> &str {
                "FV2604"
            }
        }

        let evaluator = NoConditions;
        let expr_eval = ConditionExprEvaluator::new(&evaluator);
        let external = MapExternalProvider::new(Default::default());
        let ctx = EvaluationContext::new("55042", &external, &[]);
        for status in ["K", "Kann", "", "Kann [1]", "K [1]"] {
            assert_eq!(
                evaluate_ahb_requirement(status, &expr_eval, &ctx),
                None,
                "{status:?} must be optional"
            );
        }
        assert_eq!(
            evaluate_ahb_requirement("X", &expr_eval, &ctx),
            Some(Severity::Error)
        );
    }

    #[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(""), "");
    }
}