Skip to main content

mig_bo4e/
engine.rs

1//! Mapping engine — loads TOML definitions and provides bidirectional conversion.
2//!
3//! Supports nested group paths (e.g., "SG4.SG5") for navigating the assembled tree
4//! and provides `map_forward` / `map_reverse` for full entity conversion.
5
6use std::collections::{BTreeMap, HashMap, HashSet};
7use std::path::Path;
8
9use mig_assembly::assembler::{
10    AssembledGroup, AssembledGroupInstance, AssembledSegment, AssembledTree,
11};
12use mig_types::schema::mig::MigSchema;
13use mig_types::segment::OwnedSegment;
14
15use crate::definition::{FieldMapping, MappingDefinition};
16use crate::error::MappingError;
17use crate::segment_structure::SegmentStructure;
18
19/// The mapping engine holds all loaded mapping definitions
20/// and provides methods for bidirectional conversion.
21pub struct MappingEngine {
22    definitions: Vec<MappingDefinition>,
23    segment_structure: Option<SegmentStructure>,
24    code_lookup: Option<crate::code_lookup::CodeLookup>,
25    /// Transaction-root SG id (e.g. "SG4" for UTILMD), when the engine is
26    /// operating at transaction scope. Child entities whose parent group
27    /// equals this id are left at the top level of the forward-mapped JSON
28    /// rather than being nested — SG4 is the transaction envelope, so
29    /// entities inside it (Marktlokation, Geschaeftspartner, …) are peers of
30    /// the transaction metadata, not sub-objects of it.
31    ///
32    /// Nesting still applies to other parent groups: e.g. Kontakt (SG2.SG3)
33    /// remains nested under Marktteilnehmer (SG2) because SG2 is a
34    /// message-level group, not the transaction root.
35    transaction_group: Option<String>,
36    /// PID currently being processed (e.g., "55002"). Used to suppress codelist
37    /// decoration of self-referential PID-identifier fields (e.g., RFF+Z13's
38    /// d1154 in PID 55002 has only "55002" as an allowed value).
39    current_pid: Option<String>,
40    /// The shared code-list tables a definition's `code_list` names. One `Arc`
41    /// per mappings tree, shared by every engine built from it -- a format
42    /// version builds a couple of thousand engines and the tables are the same
43    /// for all of them.
44    code_lists: std::sync::Arc<crate::code_lists::CodeLists>,
45    /// Forward mapping writes each code as it stands on the wire instead of
46    /// through its rule's table (see [`MappingEngine::with_raw_codes`]).
47    raw_codes: bool,
48}
49
50impl MappingEngine {
51    /// Create an empty engine with no definitions (for unit testing).
52    pub fn new_empty() -> Self {
53        Self {
54            definitions: Vec::new(),
55            segment_structure: None,
56            code_lookup: None,
57            transaction_group: None,
58            current_pid: None,
59            raw_codes: false,
60            code_lists: std::sync::Arc::new(crate::code_lists::CodeLists::default()),
61        }
62    }
63
64    /// Load all TOML mapping files from a directory.
65    pub fn load(dir: &Path) -> Result<Self, MappingError> {
66        let mut definitions = Vec::new();
67
68        let mut entries: Vec<_> = std::fs::read_dir(dir)?.filter_map(|e| e.ok()).collect();
69        entries.sort_by_key(|e| e.file_name());
70
71        for entry in entries {
72            let path = entry.path();
73            if path.extension().map(|e| e == "toml").unwrap_or(false) {
74                let content = std::fs::read_to_string(&path)?;
75                let def = MappingDefinition::from_toml_str(&content).map_err(|message| {
76                    MappingError::TomlParse {
77                        file: path.display().to_string(),
78                        message,
79                    }
80                })?;
81                definitions.push(def);
82            }
83        }
84
85        // Emission order comes from `meta.order` where a definition states it,
86        // and from the filename otherwise — which is what every file relies on
87        // today, via the `_30_12_` prefix convention. `sort_by_key` is stable,
88        // so definitions without the key keep their filename order exactly, and
89        // `u32::MAX` puts them after any that opt in.
90        definitions.sort_by_key(|d| d.meta.order.unwrap_or(u32::MAX));
91
92        Ok(Self {
93            definitions,
94            segment_structure: None,
95            code_lookup: None,
96            transaction_group: None,
97            current_pid: None,
98            raw_codes: false,
99            code_lists: crate::code_lists::CodeLists::discover(dir),
100        })
101    }
102
103    /// Load message-level and transaction-level TOML mappings from separate directories.
104    ///
105    /// Returns `(message_engine, transaction_engine)` where:
106    /// - `message_engine` maps SG2/SG3/root-level definitions (shared across PIDs)
107    /// - `transaction_engine` maps SG4+ definitions (PID-specific)
108    pub fn load_split(
109        message_dir: &Path,
110        transaction_dir: &Path,
111    ) -> Result<(Self, Self), MappingError> {
112        let msg_engine = Self::load(message_dir)?;
113        let tx_engine = Self::load(transaction_dir)?;
114        Ok((msg_engine, tx_engine))
115    }
116
117    /// Load TOML mapping files from multiple directories into a single engine.
118    ///
119    /// Useful for combining message-level and transaction-level mappings
120    /// when a single engine with all definitions is needed.
121    pub fn load_merged(dirs: &[&Path]) -> Result<Self, MappingError> {
122        let mut definitions = Vec::new();
123        for dir in dirs {
124            let engine = Self::load(dir)?;
125            definitions.extend(engine.definitions);
126        }
127        Ok(Self {
128            definitions,
129            segment_structure: None,
130            code_lookup: None,
131            transaction_group: None,
132            current_pid: None,
133            raw_codes: false,
134            code_lists: crate::code_lists::CodeLists::discover(
135                dirs.first().copied().unwrap_or(Path::new("")),
136            ),
137        })
138    }
139
140    /// Load transaction-level mappings with common template inheritance.
141    ///
142    /// 1. Loads all `.toml` from `common_dir`
143    /// 2. Filters: keeps only definitions whose `source_path` exists in the PID schema
144    /// 3. Loads all `.toml` from `pid_dir`
145    /// 4. For each PID definition, if a common definition has matching
146    ///    `(source_group, discriminator)`, replaces the common one (file-level replacement)
147    /// 5. Merges both sets: common first, then PID additions
148    pub fn load_with_common(
149        common_dir: &Path,
150        pid_dir: &Path,
151        schema_index: &crate::pid_schema_index::PidSchemaIndex,
152    ) -> Result<Self, MappingError> {
153        let mut common_defs = Self::load(common_dir)?.definitions;
154
155        // Filter common defs by schema — keep only groups that exist in this PID
156        common_defs.retain(|d| {
157            d.meta
158                .source_path
159                .as_deref()
160                .map(|sp| schema_index.has_group(sp))
161                .unwrap_or(true)
162        });
163
164        let pid_defs = Self::load(pid_dir)?.definitions;
165
166        // Build set of PID override keys: (source_group_normalized, discriminator)
167        // Normalizations applied:
168        // 1. Strip positional indices from source_group: "SG4.SG5:1" → "SG4.SG5"
169        // 2. Strip occurrence indices from discriminator: "RFF.c506.d1153=TN#0" → "RFF.c506.d1153=TN"
170        let normalize_sg = |sg: &str| -> String {
171            sg.split('.')
172                .map(|part| part.split(':').next().unwrap_or(part))
173                .collect::<Vec<_>>()
174                .join(".")
175        };
176        let pid_keys: HashSet<(String, Option<String>)> = pid_defs
177            .iter()
178            .flat_map(|d| {
179                let sg = normalize_sg(&d.meta.source_group);
180                let disc = d.meta.discriminator.clone();
181                let mut keys = vec![(sg.clone(), disc.clone())];
182                // If discriminator has occurrence index (#N), also add base form
183                if let Some(ref disc_str) = disc {
184                    if let Some(base) = disc_str.rsplit_once('#') {
185                        if base.1.chars().all(|c| c.is_ascii_digit()) {
186                            keys.push((sg, Some(base.0.to_string())));
187                        }
188                    }
189                }
190                keys
191            })
192            .collect();
193
194        // Remove common defs that are overridden by PID defs
195        common_defs.retain(|d| {
196            let key = (
197                normalize_sg(&d.meta.source_group),
198                d.meta.discriminator.clone(),
199            );
200            !pid_keys.contains(&key)
201        });
202
203        // Combine: common first, then PID
204        let mut definitions = common_defs;
205        definitions.extend(pid_defs);
206
207        Ok(Self {
208            definitions,
209            segment_structure: None,
210            code_lookup: None,
211            transaction_group: None,
212            current_pid: None,
213            raw_codes: false,
214            code_lists: crate::code_lists::CodeLists::discover(pid_dir),
215        })
216    }
217
218    /// Load common definitions only (no per-PID dir), filtered by schema index.
219    ///
220    /// Used for PIDs that have no per-PID directory but can use shared common/ definitions.
221    pub fn load_common_only(
222        common_dir: &Path,
223        schema_index: &crate::pid_schema_index::PidSchemaIndex,
224    ) -> Result<Self, MappingError> {
225        let mut common_defs = Self::load(common_dir)?.definitions;
226
227        // Filter common defs by schema — keep only groups that exist in this PID
228        common_defs.retain(|d| {
229            d.meta
230                .source_path
231                .as_deref()
232                .map(|sp| schema_index.has_group(sp))
233                .unwrap_or(true)
234        });
235
236        Ok(Self {
237            definitions: common_defs,
238            segment_structure: None,
239            code_lookup: None,
240            transaction_group: None,
241            current_pid: None,
242            raw_codes: false,
243            code_lists: crate::code_lists::CodeLists::discover(common_dir),
244        })
245    }
246
247    /// Load message + transaction engines with common template inheritance.
248    ///
249    /// Returns `(message_engine, transaction_engine)` where the transaction engine
250    /// inherits shared templates from `common_dir`, filtered by the PID schema.
251    pub fn load_split_with_common(
252        message_dir: &Path,
253        common_dir: &Path,
254        transaction_dir: &Path,
255        schema_index: &crate::pid_schema_index::PidSchemaIndex,
256    ) -> Result<(Self, Self), MappingError> {
257        let msg_engine = Self::load(message_dir)?;
258        let tx_engine = Self::load_with_common(common_dir, transaction_dir, schema_index)?;
259        Ok((msg_engine, tx_engine))
260    }
261
262    /// Create an engine from an already-parsed list of definitions.
263    /// Whether any definition names a shared code list.
264    fn names_a_code_list(definitions: &[MappingDefinition]) -> bool {
265        definitions.iter().any(|d| {
266            d.fields.values().any(|f| {
267                matches!(f, FieldMapping::Structured(s)
268                    if s.code_list.is_some() || s.also_code_list.is_some())
269            })
270        })
271    }
272
273    /// The table a structured mapping translates through: its own inline
274    /// `enum_map`, or the shared list its `code_list` names.
275    ///
276    /// Returning a reference rather than resolving at load time is what keeps
277    /// the tables out of the compiled cache: a definition serialises the name,
278    /// not 94 entries, in each of the files that use it.
279    fn table<'a>(
280        &'a self,
281        inline: Option<&'a BTreeMap<String, String>>,
282        named: Option<&str>,
283    ) -> Option<&'a BTreeMap<String, String>> {
284        self.code_lists.resolve(inline, named)
285    }
286
287    /// Attach shared code lists to an engine built from cached definitions.
288    pub fn with_code_lists(
289        mut self,
290        code_lists: std::sync::Arc<crate::code_lists::CodeLists>,
291    ) -> Self {
292        self.code_lists = code_lists;
293        self
294    }
295
296    /// The shared tables this engine resolves `code_list` names against.
297    pub fn code_lists(&self) -> &std::sync::Arc<crate::code_lists::CodeLists> {
298        &self.code_lists
299    }
300
301    /// Build from cached definitions, with the shared tables their `code_list`
302    /// names resolve against.
303    pub fn from_definitions_with_code_lists(
304        code_lists: std::sync::Arc<crate::code_lists::CodeLists>,
305        definitions: Vec<MappingDefinition>,
306    ) -> Self {
307        // The assertion belongs here too, not only in `from_definitions`:
308        // `DataBundle::load` called *this* constructor with an empty `Arc` for
309        // months of work, so checking only the other one meant the check could
310        // not see the one path that actually shipped.
311        debug_assert!(
312            !(code_lists.is_empty() && Self::names_a_code_list(&definitions)),
313            "definitions name a shared code list but the supplied tables are \
314             empty — whatever produced them (a bundle, a cache) is not carrying \
315             them, and every code they translate will reach the output raw"
316        );
317        // Built directly rather than through `from_definitions`, whose debug
318        // assertion is precisely "nobody supplied the tables" -- routing the
319        // correct call through it would fire on every translated definition.
320        Self {
321            definitions,
322            segment_structure: None,
323            code_lookup: None,
324            transaction_group: None,
325            current_pid: None,
326            raw_codes: false,
327            code_lists,
328        }
329    }
330
331    pub fn from_definitions(definitions: Vec<MappingDefinition>) -> Self {
332        // A definition that names a code list is useless without the tables:
333        // the name resolves to nothing and the EDIFACT code reaches the output
334        // raw, which reads as "the guide lists no codes here" rather than as
335        // the wiring mistake it is. It has happened twice -- once in the API,
336        // once in the test harness -- so say so where it happens instead of
337        // letting a wrong value travel.
338        debug_assert!(
339            !Self::names_a_code_list(&definitions),
340            "definitions name a shared code list but none were supplied — build \
341             this engine with `from_definitions_with_code_lists`, or the codes \
342             they translate will reach the output untranslated"
343        );
344        Self {
345            definitions,
346            segment_structure: None,
347            code_lookup: None,
348            transaction_group: None,
349            current_pid: None,
350            raw_codes: false,
351            code_lists: std::sync::Arc::new(crate::code_lists::CodeLists::default()),
352        }
353    }
354
355    /// Save definitions to a cache file.
356    ///
357    /// Only the `definitions` are serialized — `segment_structure` and `code_lookup`
358    /// must be re-attached after loading from cache. Paths in the definitions are
359    /// already resolved to numeric indices, so no `PathResolver` is needed at load time.
360    pub fn save_cached(&self, path: &Path) -> Result<(), MappingError> {
361        let encoded =
362            serde_json::to_vec(&self.definitions).map_err(|e| MappingError::CacheWrite {
363                path: path.display().to_string(),
364                message: e.to_string(),
365            })?;
366        if let Some(parent) = path.parent() {
367            std::fs::create_dir_all(parent)?;
368        }
369        std::fs::write(path, encoded)?;
370        Ok(())
371    }
372
373    /// Load from cache if available, otherwise fall back to TOML directory.
374    ///
375    /// When loading from cache, PathResolver is NOT needed (paths pre-resolved).
376    /// When falling back to TOML, the caller should chain `.with_path_resolver()`.
377    pub fn load_cached_or_toml(cache_path: &Path, toml_dir: &Path) -> Result<Self, MappingError> {
378        if cache_path.exists() {
379            Self::load_cached(cache_path)
380        } else {
381            Self::load(toml_dir)
382        }
383    }
384
385    /// Load definitions from a cache file.
386    ///
387    /// Returns an engine with only `definitions` populated. Attach `segment_structure`
388    /// and `code_lookup` via the builder methods if needed.
389    pub fn load_cached(path: &Path) -> Result<Self, MappingError> {
390        let bytes = std::fs::read(path)?;
391        let definitions: Vec<MappingDefinition> =
392            serde_json::from_slice(&bytes).map_err(|e| MappingError::CacheRead {
393                path: path.display().to_string(),
394                message: e.to_string(),
395            })?;
396        Ok(Self {
397            definitions,
398            segment_structure: None,
399            code_lookup: None,
400            transaction_group: None,
401            current_pid: None,
402            raw_codes: false,
403            code_lists: crate::code_lists::CodeLists::discover(path),
404        })
405    }
406
407    /// Attach a MIG-derived segment structure for trailing element padding.
408    ///
409    /// When set, `map_reverse` pads each segment's elements up to the
410    /// MIG-defined count, ensuring trailing empty elements are preserved.
411    pub fn with_segment_structure(mut self, ss: SegmentStructure) -> Self {
412        self.segment_structure = Some(ss);
413        self
414    }
415
416    /// Attach a code lookup for enriching code-type field values.
417    ///
418    /// When set, fields that map to code-type elements in the PID schema
419    /// are emitted as `{"code": "Z15", "meaning": "Ja"}` objects instead of plain strings.
420    pub fn with_code_lookup(mut self, cl: crate::code_lookup::CodeLookup) -> Self {
421        self.code_lookup = Some(cl);
422        self
423    }
424
425    /// Declare which PID this engine is currently processing.
426    ///
427    /// When combined with [`with_code_lookup`](Self::with_code_lookup), code
428    /// fields whose only allowed value equals the PID itself (Class C in the
429    /// 2026-04-28 audit — e.g., RFF+Z13's d1154 in PID 55002 enumerates only
430    /// `55002`) are emitted as plain strings instead of being decorated with
431    /// `{code, meaning, enum}` and a dedup-suffixed enum name.
432    pub fn with_pid(mut self, pid: impl Into<String>) -> Self {
433        self.current_pid = Some(pid.into());
434        self
435    }
436
437    /// Write codes as they stand on the wire in the forward direction.
438    ///
439    /// By default a code with a table (`enum_map`, `code_list`) is written as
440    /// its name — `NAD+Z65` as `"partnerrolle": "kundeDesLf"` — and an
441    /// `also_target` field receives the second value the code carries. Names
442    /// belong to the release that wrote them; codes do not. With raw codes each
443    /// element is written once, as its code, and no `also_target` field is
444    /// derived; enrichment still adds the `meaning`. The reverse direction
445    /// accepts raw codes, so the output renders the same message.
446    pub fn with_raw_codes(mut self, raw: bool) -> Self {
447        self.raw_codes = raw;
448        self
449    }
450
451    /// Attach a path resolver to normalize EDIFACT ID paths to numeric indices.
452    ///
453    /// This allows TOML mapping files to use named paths like `loc.c517.d3225`
454    /// instead of numeric indices like `loc.1.0`. Resolution happens once at
455    /// load time — the engine hot path is completely unchanged.
456    pub fn with_path_resolver(mut self, resolver: crate::path_resolver::PathResolver) -> Self {
457        for def in &mut self.definitions {
458            def.normalize_paths(&resolver);
459        }
460        self
461    }
462
463    /// Declare the transaction-root SG id (e.g. `"SG4"` for UTILMD).
464    ///
465    /// When set, entities whose parent group equals this id are not nested
466    /// into their parent in the forward-mapped JSON. See the
467    /// [`transaction_group`](Self#structfield.transaction_group-1) field doc
468    /// on `MappingEngine` for the full rationale.
469    pub fn with_transaction_group(mut self, tx: impl Into<String>) -> Self {
470        self.transaction_group = Some(tx.into());
471        self
472    }
473
474    /// Add definitions to an already-built engine, keeping everything else it
475    /// carries (code lookup, segment structure, PID, transaction group).
476    ///
477    /// Used to widen a message-level engine into one flat engine over a whole
478    /// variant — what APERAK and CONTRL are converted with, since they have no
479    /// message/transaction split in the v2 `convert` route. A definition whose
480    /// `(entity, source_group, source_path, discriminator, parent_field)` the
481    /// engine already has is skipped, so the same rule reached through two
482    /// PIDs is added once.
483    ///
484    /// The definitions are taken as they are; run them through
485    /// [`with_path_resolver`](Self::with_path_resolver) first if their paths
486    /// are still named.
487    pub fn extend_definitions(mut self, defs: impl IntoIterator<Item = MappingDefinition>) -> Self {
488        fn key(d: &MappingDefinition) -> (String, String, String, String, String) {
489            (
490                d.meta.entity.clone(),
491                d.meta.source_group.clone(),
492                d.meta.source_path.clone().unwrap_or_default(),
493                d.meta.discriminator.clone().unwrap_or_default(),
494                d.meta.parent_field.clone().unwrap_or_default(),
495            )
496        }
497        let mut seen: std::collections::HashSet<_> = self.definitions.iter().map(key).collect();
498        for def in defs {
499            if seen.insert(key(&def)) {
500                self.definitions.push(def);
501            }
502        }
503        self
504    }
505
506    /// Get all loaded definitions.
507    pub fn definitions(&self) -> &[MappingDefinition] {
508        &self.definitions
509    }
510
511    /// Find a definition by entity name.
512    /// The entity's own definition. `parent_field` children (which carry their
513    /// parent's entity name and are mapped inside the parent's instance) are
514    /// skipped — they are not a definition *of* the entity.
515    pub fn definition_for_entity(&self, entity: &str) -> Option<&MappingDefinition> {
516        self.definitions.iter().find(|d| {
517            d.meta.entity == entity
518                && d.meta.parent_field.is_none()
519                && !is_bound_child(&self.definitions, d)
520        })
521    }
522
523    // ── Forward mapping: tree → BO4E ──
524
525    /// Extract a field value from an assembled tree using a mapping path.
526    ///
527    /// `group_path` supports dotted notation for nested groups (e.g., "SG4.SG5").
528    /// Parent groups default to repetition 0; `repetition` applies to the leaf group.
529    ///
530    /// Path format: "segment.composite.data_element" e.g., "loc.c517.d3225"
531    pub fn extract_field(
532        &self,
533        tree: &AssembledTree,
534        group_path: &str,
535        path: &str,
536        repetition: usize,
537    ) -> Option<String> {
538        let instance = Self::resolve_group_instance(tree, group_path, repetition)?;
539        Self::extract_from_instance(instance, path)
540    }
541
542    /// Navigate a potentially nested group path to find a group instance.
543    ///
544    /// For "SG4.SG5", finds SG4\[0\] then SG5 at the given repetition within it.
545    /// For "SG8", finds SG8 at the given repetition in the top-level groups.
546    ///
547    /// Supports intermediate repetition with colon syntax: "SG4.SG8:1.SG10"
548    /// means SG4\[0\] → SG8\[1\] → SG10\[repetition\]. Without a colon suffix,
549    /// intermediate groups default to repetition 0.
550    pub fn resolve_group_instance<'a>(
551        tree: &'a AssembledTree,
552        group_path: &str,
553        repetition: usize,
554    ) -> Option<&'a AssembledGroupInstance> {
555        let parts: Vec<&str> = group_path.split('.').collect();
556
557        let (first_id, first_rep) = parse_group_spec(parts[0]);
558        let first_group = tree.groups.iter().find(|g| g.group_id == first_id)?;
559
560        if parts.len() == 1 {
561            // Single part — use the explicit rep from spec or the `repetition` param
562            let rep = first_rep.unwrap_or(repetition);
563            return first_group.repetitions.get(rep);
564        }
565
566        // Navigate through groups; intermediate parts default to rep 0
567        // unless explicitly specified via `:N` suffix
568        let mut current_instance = first_group.repetitions.get(first_rep.unwrap_or(0))?;
569
570        for (i, part) in parts[1..].iter().enumerate() {
571            let (group_id, explicit_rep) = parse_group_spec(part);
572            let child_group = current_instance
573                .child_groups
574                .iter()
575                .find(|g| g.group_id == group_id)?;
576
577            if i == parts.len() - 2 {
578                // Last part — use explicit rep, or fall back to `repetition`
579                let rep = explicit_rep.unwrap_or(repetition);
580                return child_group.repetitions.get(rep);
581            }
582            // Intermediate — use explicit rep or 0
583            current_instance = child_group.repetitions.get(explicit_rep.unwrap_or(0))?;
584        }
585
586        None
587    }
588
589    /// Navigate the assembled tree using a source_path with qualifier suffixes.
590    ///
591    /// Source paths like `"sg4.sg8_z98.sg10"` encode qualifiers inline:
592    /// `sg8_z98` means "find the SG8 repetition whose entry segment has qualifier Z98".
593    /// Parts without underscores (e.g., `sg4`, `sg10`) use the first repetition.
594    ///
595    /// Returns `None` if any part of the path can't be resolved.
596    pub fn resolve_by_source_path<'a>(
597        tree: &'a AssembledTree,
598        source_path: &str,
599    ) -> Option<&'a AssembledGroupInstance> {
600        let parts: Vec<&str> = source_path.split('.').collect();
601        if parts.is_empty() {
602            return None;
603        }
604
605        let (first_id, first_qualifier) = parse_source_path_part(parts[0]);
606        let first_group = tree
607            .groups
608            .iter()
609            .find(|g| g.group_id.eq_ignore_ascii_case(first_id))?;
610
611        let mut current_instance = if let Some(q) = first_qualifier {
612            find_rep_by_entry_qualifier(&first_group.repetitions, q)?
613        } else {
614            first_group.repetitions.first()?
615        };
616
617        if parts.len() == 1 {
618            return Some(current_instance);
619        }
620
621        for part in &parts[1..] {
622            let (group_id, qualifier) = parse_source_path_part(part);
623            let child_group = current_instance
624                .child_groups
625                .iter()
626                .find(|g| g.group_id.eq_ignore_ascii_case(group_id))?;
627
628            current_instance = if let Some(q) = qualifier {
629                find_rep_by_entry_qualifier(&child_group.repetitions, q)?
630            } else {
631                child_group.repetitions.first()?
632            };
633        }
634
635        Some(current_instance)
636    }
637
638    /// Resolve ALL matching instances for a source_path, returning a Vec.
639    ///
640    /// Like `resolve_by_source_path` but returns all repetitions matching
641    /// at any level, not just the first.  For example, if there are two SG5
642    /// reps with LOC+Z17, `resolve_all_by_source_path(tree, "sg4.sg5_z17")`
643    /// returns both.  For deeper paths like "sg4.sg8_zf3.sg10", if there are
644    /// two SG8 reps with ZF3, it returns SG10 children from both.
645    pub fn resolve_all_by_source_path<'a>(
646        tree: &'a AssembledTree,
647        source_path: &str,
648    ) -> Vec<&'a AssembledGroupInstance> {
649        let parts: Vec<&str> = source_path.split('.').collect();
650        if parts.is_empty() {
651            return vec![];
652        }
653
654        // First part: match against top-level groups
655        let (first_id, first_qualifier) = parse_source_path_part(parts[0]);
656        let first_group = match tree
657            .groups
658            .iter()
659            .find(|g| g.group_id.eq_ignore_ascii_case(first_id))
660        {
661            Some(g) => g,
662            None => return vec![],
663        };
664
665        let mut current_instances: Vec<&AssembledGroupInstance> = if let Some(q) = first_qualifier {
666            find_all_reps_by_entry_qualifier(&first_group.repetitions, q)
667        } else {
668            first_group.repetitions.iter().collect()
669        };
670
671        // Navigate remaining parts, branching at each level when multiple
672        // instances match a qualifier (e.g., two SG8 reps with ZF3).
673        for part in &parts[1..] {
674            let (group_id, qualifier) = parse_source_path_part(part);
675            let mut next_instances = Vec::new();
676
677            for instance in &current_instances {
678                if let Some(child_group) = instance
679                    .child_groups
680                    .iter()
681                    .find(|g| g.group_id.eq_ignore_ascii_case(group_id))
682                {
683                    if let Some(q) = qualifier {
684                        next_instances.extend(find_all_reps_by_entry_qualifier(
685                            &child_group.repetitions,
686                            q,
687                        ));
688                    } else {
689                        next_instances.extend(child_group.repetitions.iter());
690                    }
691                }
692            }
693
694            current_instances = next_instances;
695        }
696
697        current_instances
698    }
699
700    /// Like `resolve_all_by_source_path` but also returns the direct parent
701    /// rep index that each leaf instance came from. The "direct parent" is the
702    /// group one level above the leaf in the path.
703    ///
704    /// For `"sg2.sg3"`: parent is the SG2 rep index.
705    /// For `"sg17.sg36.sg40"`: parent is the SG36 rep index (not SG17).
706    ///
707    /// For single-level paths, all indices are 0.
708    ///
709    /// Compute child rep indices for the leaf group in a source_path.
710    /// E.g., for "sg29.sg30", returns the position of each matched SG30 rep
711    /// within its parent SG29's SG30 child group.
712    fn compute_child_indices(
713        tree: &AssembledTree,
714        source_path: &str,
715        indexed: &[(usize, &AssembledGroupInstance)],
716    ) -> Vec<usize> {
717        let parts: Vec<&str> = source_path.split('.').collect();
718        if parts.len() < 2 {
719            return vec![];
720        }
721        // Navigate to the parent level and find the child group
722        let (first_id, first_qualifier) = parse_source_path_part(parts[0]);
723        let first_group = match tree
724            .groups
725            .iter()
726            .find(|g| g.group_id.eq_ignore_ascii_case(first_id))
727        {
728            Some(g) => g,
729            None => return vec![],
730        };
731        let parent_reps: Vec<&AssembledGroupInstance> = if let Some(q) = first_qualifier {
732            find_all_reps_by_entry_qualifier(&first_group.repetitions, q)
733        } else {
734            first_group.repetitions.iter().collect()
735        };
736        // For 2-level paths (sg29.sg30), find the child group in the parent
737        let (child_id, _child_qualifier) = parse_source_path_part(parts[parts.len() - 1]);
738        let mut result = Vec::new();
739        for (_, inst) in indexed {
740            // Find which rep index this instance is at in the child group
741            let mut found = false;
742            for parent in &parent_reps {
743                if let Some(child_group) = parent
744                    .child_groups
745                    .iter()
746                    .find(|g| g.group_id.eq_ignore_ascii_case(child_id))
747                {
748                    if let Some(pos) = child_group
749                        .repetitions
750                        .iter()
751                        .position(|r| std::ptr::eq(r, *inst))
752                    {
753                        result.push(pos);
754                        found = true;
755                        break;
756                    }
757                }
758            }
759            if !found {
760                result.push(usize::MAX); // fallback
761            }
762        }
763        result
764    }
765
766    /// Returns `Vec<(parent_rep_index, &AssembledGroupInstance)>`.
767    pub fn resolve_all_with_parent_indices<'a>(
768        tree: &'a AssembledTree,
769        source_path: &str,
770    ) -> Vec<(usize, &'a AssembledGroupInstance)> {
771        let parts: Vec<&str> = source_path.split('.').collect();
772        if parts.is_empty() {
773            return vec![];
774        }
775
776        // First part: match against top-level groups
777        let (first_id, first_qualifier) = parse_source_path_part(parts[0]);
778        let first_group = match tree
779            .groups
780            .iter()
781            .find(|g| g.group_id.eq_ignore_ascii_case(first_id))
782        {
783            Some(g) => g,
784            None => return vec![],
785        };
786
787        // If single-level path, just return instances with index 0
788        if parts.len() == 1 {
789            let instances: Vec<&AssembledGroupInstance> = if let Some(q) = first_qualifier {
790                find_all_reps_by_entry_qualifier(&first_group.repetitions, q)
791            } else {
792                first_group.repetitions.iter().collect()
793            };
794            return instances.into_iter().map(|i| (0, i)).collect();
795        }
796
797        // Multi-level: navigate tracking (parent_rep_idx, instance) at each level.
798        // At intermediate levels, parent_rep_idx is updated to the current rep's
799        // position within its group. At the leaf level, the parent_rep_idx from
800        // the previous level is preserved — giving us the DIRECT parent index.
801        let first_reps: Vec<(usize, &AssembledGroupInstance)> = if let Some(q) = first_qualifier {
802            let matching = find_all_reps_by_entry_qualifier(&first_group.repetitions, q);
803            let mut result = Vec::new();
804            for m in matching {
805                let idx = first_group
806                    .repetitions
807                    .iter()
808                    .position(|r| std::ptr::eq(r, m))
809                    .unwrap_or(0);
810                result.push((idx, m));
811            }
812            result
813        } else {
814            first_group.repetitions.iter().enumerate().collect()
815        };
816
817        let mut current: Vec<(usize, &AssembledGroupInstance)> = first_reps;
818        let remaining = &parts[1..];
819
820        for (level, part) in remaining.iter().enumerate() {
821            let is_leaf = level == remaining.len() - 1;
822            let (group_id, qualifier) = parse_source_path_part(part);
823            let mut next: Vec<(usize, &AssembledGroupInstance)> = Vec::new();
824
825            for (prev_parent_idx, instance) in &current {
826                if let Some(child_group) = instance
827                    .child_groups
828                    .iter()
829                    .find(|g| g.group_id.eq_ignore_ascii_case(group_id))
830                {
831                    let matching: Vec<(usize, &AssembledGroupInstance)> = if let Some(q) = qualifier
832                    {
833                        let filtered =
834                            find_all_reps_by_entry_qualifier(&child_group.repetitions, q);
835                        filtered
836                            .into_iter()
837                            .map(|m| {
838                                let idx = child_group
839                                    .repetitions
840                                    .iter()
841                                    .position(|r| std::ptr::eq(r, m))
842                                    .unwrap_or(0);
843                                (idx, m)
844                            })
845                            .collect()
846                    } else {
847                        child_group.repetitions.iter().enumerate().collect()
848                    };
849
850                    for (rep_idx, child_rep) in matching {
851                        if is_leaf {
852                            // At the leaf: keep the parent index from the previous level
853                            next.push((*prev_parent_idx, child_rep));
854                        } else {
855                            // At intermediate: pass down the current rep index
856                            next.push((rep_idx, child_rep));
857                        }
858                    }
859                }
860            }
861
862            current = next;
863        }
864
865        current
866    }
867
868    /// Extract a field from a group instance by path.
869    ///
870    /// Supports qualifier-based segment selection with `tag[qualifier]` syntax:
871    /// - `"dtm.0.1"` → first DTM segment, elements\[0\]\[1\]
872    /// - `"dtm[92].0.1"` → DTM where elements\[0\]\[0\] == "92", then elements\[0\]\[1\]
873    pub fn extract_from_instance(instance: &AssembledGroupInstance, path: &str) -> Option<String> {
874        let parts: Vec<&str> = path.split('.').collect();
875        if parts.is_empty() {
876            return None;
877        }
878
879        // Parse segment tag, optional qualifier, and occurrence index:
880        // "dtm[92]" → ("DTM", Some("92"), 0), "rff[Z34,1]" → ("RFF", Some("Z34"), 1)
881        let (segment_tag, qualifier, occurrence) = parse_tag_qualifier(parts[0]);
882
883        let segment = if let Some(q) = qualifier {
884            instance
885                .segments
886                .iter()
887                .filter(|s| {
888                    s.tag.eq_ignore_ascii_case(&segment_tag)
889                        && s.elements
890                            .first()
891                            .and_then(|e| e.first())
892                            .map(|v| v.as_str())
893                            == Some(q)
894                })
895                .nth(occurrence)?
896        } else {
897            instance
898                .segments
899                .iter()
900                .filter(|s| s.tag.eq_ignore_ascii_case(&segment_tag))
901                .nth(occurrence)?
902        };
903
904        Self::resolve_field_path(segment, &parts[1..])
905    }
906
907    /// Extract ALL matching values from a group instance for a collect-all path.
908    ///
909    /// Used with wildcard occurrence syntax `tag[qualifier,*]` to collect values
910    /// from every segment matching the qualifier, not just the Nth one.
911    /// Returns a `Vec<String>` of all extracted values in segment order.
912    pub fn extract_all_from_instance(instance: &AssembledGroupInstance, path: &str) -> Vec<String> {
913        let parts: Vec<&str> = path.split('.').collect();
914        if parts.is_empty() {
915            return vec![];
916        }
917
918        let (segment_tag, qualifier, _) = parse_tag_qualifier(parts[0]);
919
920        let matching_segments: Vec<&AssembledSegment> = if let Some(q) = qualifier {
921            instance
922                .segments
923                .iter()
924                .filter(|s| {
925                    s.tag.eq_ignore_ascii_case(&segment_tag)
926                        && s.elements
927                            .first()
928                            .and_then(|e| e.first())
929                            .map(|v| v.as_str())
930                            == Some(q)
931                })
932                .collect()
933        } else {
934            instance
935                .segments
936                .iter()
937                .filter(|s| s.tag.eq_ignore_ascii_case(&segment_tag))
938                .collect()
939        };
940
941        matching_segments
942            .into_iter()
943            .filter_map(|seg| Self::resolve_field_path(seg, &parts[1..]))
944            .collect()
945    }
946
947    /// Map all fields in a definition from the assembled tree to a BO4E JSON object.
948    ///
949    /// `group_path` is the definition's `source_group` (may be dotted, e.g., "SG4.SG5").
950    /// An empty `source_group` maps root-level segments (BGM, DTM, etc.).
951    /// Returns a flat JSON object with target field names as keys.
952    pub fn map_forward(
953        &self,
954        tree: &AssembledTree,
955        def: &MappingDefinition,
956        repetition: usize,
957    ) -> serde_json::Value {
958        self.map_forward_inner(tree, def, repetition, true)
959    }
960
961    /// Inner implementation with enrichment control.
962    fn map_forward_inner(
963        &self,
964        tree: &AssembledTree,
965        def: &MappingDefinition,
966        repetition: usize,
967        enrich_codes: bool,
968    ) -> serde_json::Value {
969        let mut result = serde_json::Map::new();
970
971        // Root-level mapping: source_group is empty → use tree's own segments.
972        // Include all root segments (both pre-group and post-group, e.g., summary
973        // MOA after UNS+S in REMADV) plus any inter_group_segments (e.g., UNS+S
974        // consumed between groups by the assembler).
975        if def.meta.source_group.is_empty() {
976            let mut all_root_segs = tree.segments.clone();
977            for segs in tree.inter_group_segments.values() {
978                all_root_segs.extend(segs.iter().cloned());
979            }
980            let root_instance = AssembledGroupInstance {
981                segments: all_root_segs,
982                child_groups: vec![],
983                entry_mig_number: None,
984                variant_mig_numbers: vec![],
985                skipped_segments: Vec::new(),
986                skipped_positions: Vec::new(),
987            };
988            self.extract_fields_from_instance(&root_instance, def, &mut result, enrich_codes);
989            return serde_json::Value::Object(result);
990        }
991
992        // Try source_path-based resolution when:
993        //   1. source_path has qualifier suffixes (e.g., "sg4.sg8_z98.sg10")
994        //   2. source_group has no explicit :N indices (those take priority)
995        // This allows definitions without positional indices to navigate via
996        // entry-segment qualifiers (e.g., SEQ qualifier Z98).
997        let instance = if let Some(ref sp) = def.meta.source_path {
998            if has_source_path_qualifiers(sp) && !def.meta.source_group.contains(':') {
999                Self::resolve_by_source_path(tree, sp).or_else(|| {
1000                    Self::resolve_group_instance(tree, &def.meta.source_group, repetition)
1001                })
1002            } else {
1003                Self::resolve_group_instance(tree, &def.meta.source_group, repetition)
1004            }
1005        } else {
1006            Self::resolve_group_instance(tree, &def.meta.source_group, repetition)
1007        };
1008
1009        if let Some(instance) = instance {
1010            // repeat_on_tag: iterate over all segments of that tag, producing an array
1011            if let Some(ref tag) = def.meta.repeat_on_tag {
1012                let matching: Vec<_> = instance
1013                    .segments
1014                    .iter()
1015                    .filter(|s| s.tag.eq_ignore_ascii_case(tag))
1016                    .collect();
1017
1018                if matching.len() > 1 {
1019                    let mut arr = Vec::new();
1020                    for seg in &matching {
1021                        let sub_instance = AssembledGroupInstance {
1022                            segments: vec![(*seg).clone()],
1023                            child_groups: vec![],
1024                            entry_mig_number: None,
1025                            variant_mig_numbers: vec![],
1026                            skipped_segments: Vec::new(),
1027                            skipped_positions: Vec::new(),
1028                        };
1029                        let mut elem_result = serde_json::Map::new();
1030                        self.extract_fields_from_instance(
1031                            &sub_instance,
1032                            def,
1033                            &mut elem_result,
1034                            enrich_codes,
1035                        );
1036                        if !elem_result.is_empty() {
1037                            arr.push(serde_json::Value::Object(elem_result));
1038                        }
1039                    }
1040                    if !arr.is_empty() {
1041                        return serde_json::Value::Array(arr);
1042                    }
1043                }
1044            }
1045
1046            self.extract_fields_from_instance(instance, def, &mut result, enrich_codes);
1047        }
1048
1049        serde_json::Value::Object(result)
1050    }
1051
1052    /// Extract all fields from an instance into a result map.
1053    ///
1054    /// When a `code_lookup` is configured, code-type fields are emitted as
1055    /// `{"code": "E01", "meaning": "..."}` objects. Data-type fields remain plain strings.
1056    fn extract_fields_from_instance(
1057        &self,
1058        instance: &AssembledGroupInstance,
1059        def: &MappingDefinition,
1060        result: &mut serde_json::Map<String, serde_json::Value>,
1061        enrich_codes: bool,
1062    ) {
1063        for (path, field_mapping) in &def.fields {
1064            let (target, enum_map) = match field_mapping {
1065                FieldMapping::Simple(t) => (t.as_str(), None),
1066                FieldMapping::Structured(s) => (
1067                    s.target.as_str(),
1068                    self.table(s.enum_map.as_ref(), s.code_list.as_deref()),
1069                ),
1070                FieldMapping::Nested(_) => continue,
1071            };
1072            if target.is_empty() {
1073                continue;
1074            }
1075            if let Some((list, sub)) = list_target(target) {
1076                self.extract_list_field(
1077                    instance,
1078                    def,
1079                    path,
1080                    list,
1081                    sub,
1082                    enum_map,
1083                    enrich_codes,
1084                    result,
1085                );
1086                continue;
1087            }
1088            if let Some(val) = Self::extract_from_instance(instance, path) {
1089                // Dual decomposition: one EDIFACT code also feeds a second BO4E
1090                // field (e.g. the NAD qualifier carries both partnerrolle and
1091                // datenqualitaet). Without this the code cannot be recovered in
1092                // reverse, because several codes share the primary value.
1093                if let FieldMapping::Structured(s) = field_mapping {
1094                    if let (false, Some(also), Some(also_map)) = (
1095                        self.raw_codes,
1096                        s.also_target.as_deref(),
1097                        self.table(s.also_enum_map.as_ref(), s.also_code_list.as_deref()),
1098                    ) {
1099                        if let Some(also_val) = also_map.get(&val) {
1100                            set_nested_value(result, also, also_val.clone());
1101                        }
1102                    }
1103                }
1104
1105                let mapped_val = match enum_map {
1106                    Some(map) if !self.raw_codes => {
1107                        map.get(&val).cloned().unwrap_or_else(|| val.clone())
1108                    }
1109                    _ => val.clone(),
1110                };
1111
1112                // Enrich code fields with meaning from PID schema
1113                if enrich_codes {
1114                    if let (Some(ref code_lookup), Some(ref source_path)) =
1115                        (&self.code_lookup, &def.meta.source_path)
1116                    {
1117                        let parts: Vec<&str> = path.split('.').collect();
1118                        let (seg_tag, path_qualifier, _occ) = parse_tag_qualifier(parts[0]);
1119                        let (element_idx, component_idx) =
1120                            Self::parse_element_component(&parts[1..]);
1121                        let disc_qualifier = Self::discriminator_qualifier_for_tag(def, &seg_tag);
1122                        let q = disc_qualifier.as_deref();
1123
1124                        if let Some(codes) = code_lookup.enrichment_codes(
1125                            source_path,
1126                            &seg_tag,
1127                            path_qualifier,
1128                            q,
1129                            element_idx,
1130                            component_idx,
1131                        ) {
1132                            // Class C: PID self-reference — emit a plain string,
1133                            // skipping {code, meaning, enum} decoration when the
1134                            // schema's only allowed value at this position is the
1135                            // PID itself.
1136                            if let Some(ref pid) = self.current_pid {
1137                                if codes.len() == 1 && codes.contains_key(pid.as_str()) {
1138                                    set_nested_value(result, target, mapped_val);
1139                                    continue;
1140                                }
1141                            }
1142
1143                            // Look up the original EDIFACT value for enrichment,
1144                            // since schema codes use raw values (e.g., "293")
1145                            // not enum_map targets (e.g., "BDEW").
1146                            let enrichment = codes.get(&val);
1147                            let meaning = enrichment
1148                                .map(|e| serde_json::Value::String(e.meaning.clone()))
1149                                .unwrap_or(serde_json::Value::Null);
1150
1151                            let mut obj = serde_json::Map::new();
1152                            obj.insert("code".into(), serde_json::json!(mapped_val));
1153                            obj.insert("meaning".into(), meaning);
1154                            if let Some(enum_key) = enrichment.and_then(|e| e.enum_key.as_ref()) {
1155                                obj.insert("enum".into(), serde_json::json!(enum_key));
1156                            }
1157                            let enriched = serde_json::Value::Object(obj);
1158                            set_nested_value_json(result, target, enriched);
1159                            continue;
1160                        }
1161                    }
1162                }
1163
1164                set_nested_value(result, target, mapped_val);
1165            }
1166        }
1167
1168        // Also for `parent_field` children: they can be parents of deeper
1169        // `parent_field` definitions (SG15 → SG17 → SG18).
1170        if !instance.child_groups.is_empty() {
1171            self.extract_nested_children(instance, def, result, enrich_codes);
1172        }
1173    }
1174
1175    /// Forward half of a list target (`werte[].code`): one element of the array
1176    /// per segment the path matches — `cav[*,*]` every CAV, `cav[Z30,*]` every
1177    /// CAV+Z30 — in wire order. A positional slot (`cav[*,1]` → `wert2`) names
1178    /// a position, and the SG10 CAVs are identified by their code, not their
1179    /// place: an absent first CAV moved the second into the first's field, and
1180    /// CAVs beyond the last slot were dropped. The list keeps every CAV with
1181    /// its own code.
1182    #[allow(clippy::too_many_arguments)]
1183    fn extract_list_field(
1184        &self,
1185        instance: &AssembledGroupInstance,
1186        def: &MappingDefinition,
1187        path: &str,
1188        list: &str,
1189        sub: &str,
1190        enum_map: Option<&std::collections::BTreeMap<String, String>>,
1191        enrich_codes: bool,
1192        result: &mut serde_json::Map<String, serde_json::Value>,
1193    ) {
1194        let parts: Vec<&str> = path.split('.').collect();
1195        if parts.len() < 2 {
1196            return;
1197        }
1198        let (seg_tag, qualifier, _) = parse_tag_qualifier(parts[0]);
1199        let segments: Vec<&AssembledSegment> = instance
1200            .segments
1201            .iter()
1202            .filter(|s| {
1203                s.tag.eq_ignore_ascii_case(&seg_tag)
1204                    && qualifier.map_or(true, |q| {
1205                        s.elements
1206                            .first()
1207                            .and_then(|e| e.first())
1208                            .map(|v| v.as_str())
1209                            == Some(q)
1210                    })
1211            })
1212            .collect();
1213        if segments.is_empty() {
1214            return;
1215        }
1216        let items = result
1217            .entry(list.to_string())
1218            .or_insert_with(|| serde_json::Value::Array(Vec::new()));
1219        let Some(items) = items.as_array_mut() else {
1220            return;
1221        };
1222        while items.len() < segments.len() {
1223            items.push(serde_json::Value::Object(serde_json::Map::new()));
1224        }
1225        let codes = if enrich_codes {
1226            match (&self.code_lookup, &def.meta.source_path) {
1227                (Some(lookup), Some(source_path)) => {
1228                    let (element_idx, component_idx) = Self::parse_element_component(&parts[1..]);
1229                    let disc = Self::discriminator_qualifier_for_tag(def, &seg_tag);
1230                    lookup
1231                        .enrichment_codes(
1232                            source_path,
1233                            &seg_tag,
1234                            qualifier,
1235                            disc.as_deref(),
1236                            element_idx,
1237                            component_idx,
1238                        )
1239                        .cloned()
1240                }
1241                _ => None,
1242            }
1243        } else {
1244            None
1245        };
1246        for (item, segment) in items.iter_mut().zip(segments) {
1247            let Some(val) = Self::resolve_field_path(segment, &parts[1..]) else {
1248                continue;
1249            };
1250            let mapped = match enum_map {
1251                Some(map) if !self.raw_codes => {
1252                    map.get(&val).cloned().unwrap_or_else(|| val.clone())
1253                }
1254                _ => val.clone(),
1255            };
1256            let value = match &codes {
1257                Some(codes) => {
1258                    let enrichment = codes.get(&val);
1259                    let mut obj = serde_json::Map::new();
1260                    obj.insert("code".into(), serde_json::json!(mapped));
1261                    obj.insert(
1262                        "meaning".into(),
1263                        enrichment
1264                            .map(|e| serde_json::Value::String(e.meaning.clone()))
1265                            .unwrap_or(serde_json::Value::Null),
1266                    );
1267                    if let Some(enum_key) = enrichment.and_then(|e| e.enum_key.as_ref()) {
1268                        obj.insert("enum".into(), serde_json::json!(enum_key));
1269                    }
1270                    serde_json::Value::Object(obj)
1271                }
1272                None => serde_json::Value::String(mapped),
1273            };
1274            if let Some(obj) = item.as_object_mut() {
1275                set_nested_value_json(obj, sub, value);
1276            }
1277        }
1278    }
1279
1280    /// Forward half of `[meta] parent_field`: map the child groups of `instance`
1281    /// (the parent group repetition `def` was just extracted from) into array
1282    /// fields of the same object. Placement is instance-local — a child can only
1283    /// land in the object produced from the group repetition that contains it.
1284    fn extract_nested_children(
1285        &self,
1286        instance: &AssembledGroupInstance,
1287        def: &MappingDefinition,
1288        result: &mut serde_json::Map<String, serde_json::Value>,
1289        enrich_codes: bool,
1290    ) {
1291        for child in self
1292            .definitions
1293            .iter()
1294            .filter(|c| is_nested_child_of(c, def))
1295        {
1296            if nested_parent_qualifier(child).is_some_and(|q| !entry_qualifier_matches(instance, q))
1297            {
1298                continue;
1299            }
1300            let (leaf_id, leaf_qualifier) = nested_child_leaf(child);
1301            let Some(group) = instance
1302                .child_groups
1303                .iter()
1304                .find(|g| g.group_id.eq_ignore_ascii_case(&leaf_id))
1305            else {
1306                continue;
1307            };
1308            let reps: Vec<&AssembledGroupInstance> = match leaf_qualifier {
1309                Some(q) => find_all_reps_by_entry_qualifier(&group.repetitions, q),
1310                None => group.repetitions.iter().collect(),
1311            };
1312
1313            let mut items: Vec<serde_json::Value> = Vec::new();
1314            let mut push_item = |sub: &AssembledGroupInstance| {
1315                let mut obj = serde_json::Map::new();
1316                self.extract_fields_from_instance(sub, child, &mut obj, enrich_codes);
1317                if !obj.is_empty() {
1318                    items.push(serde_json::Value::Object(obj));
1319                }
1320            };
1321            for rep in reps {
1322                let repeat_tag = child
1323                    .meta
1324                    .repeat_on_tag
1325                    .as_deref()
1326                    .filter(|tag| rep.segments.iter().any(|s| s.tag.eq_ignore_ascii_case(tag)));
1327                let Some(tag) = repeat_tag else {
1328                    push_item(rep);
1329                    continue;
1330                };
1331                // One element per repeating segment; the group's other segments
1332                // (e.g. the CTA entry segment) are visible to every element.
1333                let shared: Vec<AssembledSegment> = rep
1334                    .segments
1335                    .iter()
1336                    .filter(|s| !s.tag.eq_ignore_ascii_case(tag))
1337                    .cloned()
1338                    .collect();
1339                for seg in rep
1340                    .segments
1341                    .iter()
1342                    .filter(|s| s.tag.eq_ignore_ascii_case(tag))
1343                {
1344                    let mut segments = shared.clone();
1345                    segments.push(seg.clone());
1346                    push_item(&AssembledGroupInstance {
1347                        segments,
1348                        child_groups: vec![],
1349                        entry_mig_number: None,
1350                        variant_mig_numbers: vec![],
1351                        skipped_segments: Vec::new(),
1352                        skipped_positions: Vec::new(),
1353                    });
1354                }
1355            }
1356            if items.is_empty() {
1357                continue;
1358            }
1359            let field = child.meta.parent_field.as_deref().unwrap_or_default();
1360            match result.get_mut(field) {
1361                Some(serde_json::Value::Array(existing)) => existing.extend(items),
1362                _ => {
1363                    result.insert(field.to_string(), serde_json::Value::Array(items));
1364                }
1365            }
1366        }
1367
1368        // Bound children write into this same object (see `is_bound_child_of`).
1369        for child in self
1370            .definitions
1371            .iter()
1372            .filter(|c| is_bound_child_of(c, def))
1373        {
1374            for rep in bound_child_reps(instance, child) {
1375                self.extract_fields_from_instance(rep, child, result, enrich_codes);
1376            }
1377        }
1378    }
1379
1380    /// Reverse half of `[meta] parent_field`: emit the elements of
1381    /// `bo4e_value[parent_field]` as child group(s) of `instance`, the parent
1382    /// group repetition just rebuilt from that same object.
1383    fn reverse_nested_children(
1384        &self,
1385        bo4e_value: &serde_json::Value,
1386        def: &MappingDefinition,
1387        instance: &mut AssembledGroupInstance,
1388    ) {
1389        let mut handled_fields: Vec<&str> = Vec::new();
1390        for child in self
1391            .definitions
1392            .iter()
1393            .filter(|c| is_nested_child_of(c, def))
1394        {
1395            let field = child.meta.parent_field.as_deref().unwrap_or_default();
1396            if handled_fields.contains(&field) {
1397                continue;
1398            }
1399            if nested_parent_qualifier(child)
1400                .is_some_and(|q| !rebuilt_entry_qualifier_matches(instance, def, q))
1401            {
1402                continue;
1403            }
1404            let elements: Vec<&serde_json::Value> = match bo4e_value.get(field) {
1405                Some(serde_json::Value::Array(arr)) => arr.iter().collect(),
1406                Some(serde_json::Value::Null) | None => continue,
1407                Some(other) => vec![other],
1408            };
1409
1410            let mut reps: Vec<AssembledGroupInstance> = Vec::new();
1411            if let Some(tag) = child.meta.repeat_on_tag.as_deref() {
1412                // All elements share one group repetition: the non-repeating
1413                // segments (entry segment) once, then one repeating segment each.
1414                let mut merged: Option<AssembledGroupInstance> = None;
1415                for element in elements {
1416                    let sub = self.map_reverse_single(element, child);
1417                    if sub.segments.is_empty() {
1418                        continue;
1419                    }
1420                    match merged.as_mut() {
1421                        None => merged = Some(sub),
1422                        Some(m) => m.segments.extend(
1423                            sub.segments
1424                                .into_iter()
1425                                .filter(|s| s.tag.eq_ignore_ascii_case(tag)),
1426                        ),
1427                    }
1428                }
1429                reps.extend(merged);
1430            } else {
1431                for element in elements {
1432                    let mut sub = self.map_reverse_single(element, child);
1433                    if sub.segments.is_empty() {
1434                        continue;
1435                    }
1436                    // Grandchildren nested in this element (multi-level nesting).
1437                    self.reverse_nested_children(element, child, &mut sub);
1438                    reps.push(sub);
1439                }
1440            }
1441            if reps.is_empty() {
1442                continue;
1443            }
1444            handled_fields.push(field);
1445
1446            let (leaf_id, _) = nested_child_leaf(child);
1447            push_child_reps(instance, leaf_id, reps);
1448        }
1449
1450        // Bound children are rebuilt from this same object, one repetition
1451        // each, under the repetition just rebuilt from it.
1452        for child in self
1453            .definitions
1454            .iter()
1455            .filter(|c| is_bound_child_of(c, def))
1456        {
1457            let mut sub = self.map_reverse_single(bo4e_value, child);
1458            if sub.segments.is_empty() {
1459                continue;
1460            }
1461            self.reverse_nested_children(bo4e_value, child, &mut sub);
1462            let (leaf_id, _) = nested_child_leaf(child);
1463            push_child_reps(instance, leaf_id, vec![sub]);
1464        }
1465    }
1466
1467    /// Extract the discriminator's qualifier value from a definition's `[meta]`.
1468    ///
1469    /// `discriminator` strings look like `"RFF.0.0=Z13"` (numeric, post path-resolution)
1470    /// or `"RFF.c506.d1153=TN"` (named, pre-resolution). The qualifier is the
1471    /// substring after the first `=`. Returns `None` when no discriminator is set
1472    /// or the format is unexpected.
1473    pub(crate) fn discriminator_qualifier(def: &MappingDefinition) -> Option<String> {
1474        def.meta
1475            .discriminator
1476            .as_deref()
1477            .and_then(|d| d.split_once('=').map(|(_, v)| v.to_string()))
1478    }
1479
1480    /// The discriminator value when the discriminator selects on `segment_tag`
1481    /// itself (`RFF.0.0=Z13` for an RFF field). A discriminator on another segment
1482    /// (`SEQ.0.0=Z98` for a CCI field) says nothing about which variant of
1483    /// `segment_tag` a field reads.
1484    pub(crate) fn discriminator_qualifier_for_tag(
1485        def: &MappingDefinition,
1486        segment_tag: &str,
1487    ) -> Option<String> {
1488        let (lhs, value) = def.meta.discriminator.as_deref()?.split_once('=')?;
1489        let disc_tag = lhs.split('.').next().unwrap_or(lhs);
1490        disc_tag
1491            .eq_ignore_ascii_case(segment_tag)
1492            .then(|| value.to_string())
1493    }
1494
1495    /// Map a PID struct field's segments to BO4E JSON.
1496    ///
1497    /// `segments` are the `OwnedSegment`s from a PID wrapper field.
1498    /// Converts to `AssembledSegment` format for compatibility with existing
1499    /// field extraction logic, then applies the definition's field mappings.
1500    pub fn map_forward_from_segments(
1501        &self,
1502        segments: &[OwnedSegment],
1503        def: &MappingDefinition,
1504    ) -> serde_json::Value {
1505        let assembled_segments: Vec<AssembledSegment> = segments
1506            .iter()
1507            .map(|s| AssembledSegment {
1508                tag: s.id.clone(),
1509                elements: s.elements.clone(),
1510                mig_number: None,
1511                segment_number: Some(s.segment_number),
1512            })
1513            .collect();
1514
1515        let instance = AssembledGroupInstance {
1516            segments: assembled_segments,
1517            child_groups: vec![],
1518            entry_mig_number: None,
1519            variant_mig_numbers: vec![],
1520            skipped_segments: Vec::new(),
1521            skipped_positions: Vec::new(),
1522        };
1523
1524        let mut result = serde_json::Map::new();
1525        self.extract_fields_from_instance(&instance, def, &mut result, true);
1526        serde_json::Value::Object(result)
1527    }
1528
1529    // ── Reverse mapping: BO4E → tree ──
1530
1531    /// Map a BO4E JSON object back to an assembled group instance.
1532    ///
1533    /// Uses the definition's field mappings to populate segment elements.
1534    /// Fields with `default` values are used when no BO4E value is present
1535    /// (useful for fixed qualifiers like LOC qualifier "Z16").
1536    ///
1537    /// Supports:
1538    /// - Named paths: `"d3227"` → element\[0\]\[0\], `"c517.d3225"` → element\[1\]\[0\]
1539    /// - Numeric index: `"0"` → element\[0\]\[0\], `"1.2"` → element\[1\]\[2\]
1540    /// - Qualifier selection: `"dtm[92].0.1"` → DTM segment with qualifier "92"
1541    pub fn map_reverse(
1542        &self,
1543        bo4e_value: &serde_json::Value,
1544        def: &MappingDefinition,
1545    ) -> AssembledGroupInstance {
1546        // repeat_on_tag + array input: reverse each element independently, merge segments
1547        if def.meta.repeat_on_tag.is_some() {
1548            if let Some(arr) = bo4e_value.as_array() {
1549                let mut all_segments = Vec::new();
1550                for elem in arr {
1551                    let sub = self.map_reverse_single(elem, def);
1552                    all_segments.extend(sub.segments);
1553                }
1554                return AssembledGroupInstance {
1555                    segments: all_segments,
1556                    child_groups: vec![],
1557                    entry_mig_number: None,
1558                    variant_mig_numbers: vec![],
1559                    skipped_segments: Vec::new(),
1560                    skipped_positions: Vec::new(),
1561                };
1562            }
1563        }
1564        let mut instance = self.map_reverse_single(bo4e_value, def);
1565        if def.meta.parent_field.is_some() {
1566            return instance;
1567        }
1568        if !instance.segments.is_empty() {
1569            self.reverse_nested_children(bo4e_value, def, &mut instance);
1570            return instance;
1571        }
1572        // Nothing of the parent's own but its constants: still a repetition
1573        // when a child group of it carries data (a `MarktlokationDaten` holding
1574        // only `haushaltskunde`). The child needs its parent's entry segment,
1575        // which the phantom check would otherwise drop with the constants.
1576        let mut children = AssembledGroupInstance {
1577            segments: vec![],
1578            child_groups: vec![],
1579            entry_mig_number: None,
1580            variant_mig_numbers: vec![],
1581            skipped_segments: Vec::new(),
1582            skipped_positions: Vec::new(),
1583        };
1584        self.reverse_nested_children(bo4e_value, def, &mut children);
1585        if children.child_groups.is_empty() {
1586            return instance;
1587        }
1588        let mut instance = self.map_reverse_single_inner(bo4e_value, def, true);
1589        if !instance.segments.is_empty() {
1590            instance.child_groups = children.child_groups;
1591        }
1592        instance
1593    }
1594
1595    fn map_reverse_single(
1596        &self,
1597        bo4e_value: &serde_json::Value,
1598        def: &MappingDefinition,
1599    ) -> AssembledGroupInstance {
1600        self.map_reverse_single_inner(bo4e_value, def, false)
1601    }
1602
1603    /// `keep_constants`: emit the definition's constants even when none of its
1604    /// data fields resolved (the parent of a child group with data).
1605    fn map_reverse_single_inner(
1606        &self,
1607        bo4e_value: &serde_json::Value,
1608        def: &MappingDefinition,
1609        keep_constants: bool,
1610    ) -> AssembledGroupInstance {
1611        // Collect (segment_key, element_index, component_index, value) tuples.
1612        // segment_key includes qualifier for disambiguation: "DTM" or "DTM[92]".
1613        let mut field_values: Vec<(String, String, usize, usize, String)> =
1614            Vec::with_capacity(def.fields.len());
1615
1616        // Track whether any field with a non-empty target resolved to an actual
1617        // BO4E value.  When a definition has data fields but none resolved to
1618        // values, only defaults (qualifiers) would be emitted — producing phantom
1619        // segments for groups not present in the original EDIFACT message.
1620        // Definitions with ONLY qualifier/default fields (no data targets) are
1621        // "container" definitions (e.g., SEQ entry segments) and are always kept.
1622        let mut has_real_data = false;
1623        let mut has_data_fields = false;
1624        // Per-segment phantom tracking: segments with data fields but no resolved
1625        // data are phantoms — their entries should be removed from field_values.
1626        let mut seg_has_data_field: HashSet<String> = HashSet::new();
1627        let mut seg_has_real_data: HashSet<String> = HashSet::new();
1628        let mut injected_qualifiers: HashSet<String> = HashSet::new();
1629        // List-target fields (`werte[].code`), emitted after the loop item by
1630        // item so the segments come out in the list's order.
1631        type ListField<'a> = (
1632            &'a str,
1633            &'a str,
1634            String,
1635            Option<String>,
1636            usize,
1637            usize,
1638            Option<&'a std::collections::BTreeMap<String, String>>,
1639        );
1640        let mut list_fields: Vec<ListField<'_>> = Vec::new();
1641
1642        for (path, field_mapping) in &def.fields {
1643            let (target, default, enum_map, when_filled, also_target, also_enum_map) =
1644                match field_mapping {
1645                    FieldMapping::Simple(t) => (t.as_str(), None, None, None, None, None),
1646                    FieldMapping::Structured(s) => (
1647                        s.target.as_str(),
1648                        s.default.as_ref(),
1649                        self.table(s.enum_map.as_ref(), s.code_list.as_deref()),
1650                        s.when_filled.as_ref(),
1651                        s.also_target.as_deref(),
1652                        self.table(s.also_enum_map.as_ref(), s.also_code_list.as_deref()),
1653                    ),
1654                    FieldMapping::Nested(_) => continue,
1655                };
1656
1657            let parts: Vec<&str> = path.split('.').collect();
1658            if parts.len() < 2 {
1659                continue;
1660            }
1661
1662            let (seg_tag, qualifier, _occ) = parse_tag_qualifier(parts[0]);
1663            // Use the raw first part as segment key to group fields by segment instance.
1664            // Indexed qualifiers like "RFF[Z34,1]" produce a distinct key from "RFF[Z34]".
1665            let seg_key = parts[0].to_uppercase();
1666            let sub_path = &parts[1..];
1667
1668            // Determine (element_idx, component_idx) from path
1669            let (element_idx, component_idx) = if let Ok(ei) = sub_path[0].parse::<usize>() {
1670                let ci = if sub_path.len() > 1 {
1671                    sub_path[1].parse::<usize>().unwrap_or(0)
1672                } else {
1673                    0
1674                };
1675                (ei, ci)
1676            } else {
1677                match sub_path.len() {
1678                    1 => (0, 0),
1679                    2 => (1, 0),
1680                    _ => continue,
1681                }
1682            };
1683
1684            if let Some((list, sub)) = list_target(target) {
1685                list_fields.push((
1686                    list,
1687                    sub,
1688                    seg_tag.clone(),
1689                    qualifier.map(str::to_string),
1690                    element_idx,
1691                    component_idx,
1692                    enum_map,
1693                ));
1694                continue;
1695            }
1696
1697            // Try BO4E value first, fall back to default
1698            let val = if target.is_empty() {
1699                match (default, when_filled) {
1700                    // has when_filled → conditional injection
1701                    (Some(d), Some(fields)) => {
1702                        let any_filled = fields.iter().any(|f| field_is_filled(bo4e_value, f));
1703                        if any_filled {
1704                            // A successful when_filled check confirms real data
1705                            // exists — prevent phantom suppression.
1706                            has_real_data = true;
1707                            Some(d.clone())
1708                        } else {
1709                            None
1710                        }
1711                    }
1712                    // no when_filled → unconditional (backward compat)
1713                    (Some(d), None) => Some(d.clone()),
1714                    (None, _) => None,
1715                }
1716            } else {
1717                has_data_fields = true;
1718                seg_has_data_field.insert(seg_key.clone());
1719                let bo4e_val = self.populate_field(bo4e_value, target);
1720                if bo4e_val.is_some() {
1721                    has_real_data = true;
1722                    seg_has_real_data.insert(seg_key.clone());
1723                }
1724                // Apply reverse enum_map: BO4E value → EDIFACT value
1725                let mapped_val = match (bo4e_val, enum_map) {
1726                    (Some(v), Some(map)) => {
1727                        // Dual decomposition (`also_target`): one EDIFACT code was
1728                        // split across two BO4E fields, so neither alone identifies
1729                        // it. Find the code both maps agree on; several codes share
1730                        // a `partnerrolle` and are told apart only by the second
1731                        // field. Falls back to the single-map lookup when the
1732                        // second field is absent or no code matches both.
1733                        let joint = match (also_target, also_enum_map) {
1734                            (Some(also), Some(also_map)) => {
1735                                self.populate_field(bo4e_value, also).and_then(|also_v| {
1736                                    map.iter()
1737                                        .find(|(code, bo4e_v)| {
1738                                            *bo4e_v == &v && also_map.get(*code) == Some(&also_v)
1739                                        })
1740                                        .map(|(code, _)| code.clone())
1741                                })
1742                            }
1743                            _ => None,
1744                        };
1745                        joint
1746                            .or_else(|| {
1747                                // Reverse lookup: find EDIFACT key for BO4E value
1748                                map.iter()
1749                                    .find(|(_, bo4e_v)| *bo4e_v == &v)
1750                                    .map(|(edifact_k, _)| edifact_k.clone())
1751                            })
1752                            .or(Some(v))
1753                    }
1754                    (v, _) => v,
1755                };
1756                mapped_val.or_else(|| default.cloned())
1757            };
1758
1759            if let Some(val) = val {
1760                field_values.push((
1761                    seg_key.clone(),
1762                    seg_tag.clone(),
1763                    element_idx,
1764                    component_idx,
1765                    val,
1766                ));
1767            }
1768
1769            // If there's a qualifier, also inject it at elements[0][0]
1770            if let Some(q) = qualifier {
1771                if injected_qualifiers.insert(seg_key.clone()) {
1772                    field_values.push((seg_key, seg_tag, 0, 0, q.to_string()));
1773                }
1774            }
1775        }
1776
1777        // Reverse half of list targets: element i of the array becomes the i-th
1778        // segment (`CAV[*,i]`, or `CAV[Q,i]` with the qualifier written back).
1779        let longest = list_fields
1780            .iter()
1781            .filter_map(|(list, ..)| bo4e_value.get(*list).and_then(|v| v.as_array()))
1782            .map(|a| a.len())
1783            .max()
1784            .unwrap_or(0);
1785        if !list_fields.is_empty() {
1786            has_data_fields = true;
1787        }
1788        for i in 0..longest {
1789            for (list, sub, seg_tag, qualifier, element_idx, component_idx, enum_map) in
1790                &list_fields
1791            {
1792                let key = match qualifier {
1793                    Some(q) => format!("{seg_tag}[{q},{i}]"),
1794                    None => format!("{seg_tag}[*,{i}]"),
1795                };
1796                seg_has_data_field.insert(key.clone());
1797                let Some(item) = bo4e_value
1798                    .get(*list)
1799                    .and_then(|v| v.as_array())
1800                    .and_then(|a| a.get(i))
1801                else {
1802                    continue;
1803                };
1804                let Some(value) = self.populate_field(item, sub) else {
1805                    continue;
1806                };
1807                let value = match enum_map {
1808                    Some(map) => map
1809                        .iter()
1810                        .find(|(_, name)| **name == value)
1811                        .map(|(code, _)| code.clone())
1812                        .unwrap_or(value),
1813                    None => value,
1814                };
1815                has_real_data = true;
1816                seg_has_real_data.insert(key.clone());
1817                field_values.push((
1818                    key.clone(),
1819                    seg_tag.clone(),
1820                    *element_idx,
1821                    *component_idx,
1822                    value,
1823                ));
1824                if let Some(q) = qualifier {
1825                    if injected_qualifiers.insert(key.clone()) {
1826                        field_values.push((key, seg_tag.clone(), 0, 0, q.clone()));
1827                    }
1828                }
1829            }
1830        }
1831
1832        // Per-segment phantom prevention for qualified segments: remove entries
1833        // for segments using tag[qualifier] syntax (e.g., FTX[ACB], DTM[Z07])
1834        // that have data fields but none resolved to actual BO4E values.  This
1835        // prevents phantom segments when a definition maps multiple segment types
1836        // and optional qualified segments are not in the original message.
1837        // Unqualified segments (plain tags like SEQ, IDE) are always kept — they
1838        // are typically entry/mandatory segments of their group.
1839        field_values.retain(|(seg_key, _, _, _, _)| {
1840            if !seg_key.contains('[') {
1841                return true; // unqualified segments always kept
1842            }
1843            !seg_has_data_field.contains(seg_key) || seg_has_real_data.contains(seg_key)
1844        });
1845
1846        // If the definition has data fields but none resolved to actual BO4E values,
1847        // return an empty instance to prevent phantom segments for groups not
1848        // present in the original EDIFACT message.  Definitions with only
1849        // qualifier/default fields (has_data_fields=false) are always kept.
1850        if has_data_fields && !has_real_data && !keep_constants {
1851            return AssembledGroupInstance {
1852                segments: vec![],
1853                child_groups: vec![],
1854                entry_mig_number: None,
1855                variant_mig_numbers: vec![],
1856                skipped_segments: Vec::new(),
1857                skipped_positions: Vec::new(),
1858            };
1859        }
1860
1861        // Build segments with elements/components in correct positions.
1862        // Group by segment_key to create separate segments for "DTM[92]" vs "DTM[93]".
1863        let mut segments: Vec<AssembledSegment> = Vec::with_capacity(field_values.len());
1864        let mut seen_keys: HashMap<String, usize> = HashMap::new();
1865
1866        for (seg_key, seg_tag, element_idx, component_idx, val) in &field_values {
1867            let seg = if let Some(&pos) = seen_keys.get(seg_key) {
1868                &mut segments[pos]
1869            } else {
1870                let pos = segments.len();
1871                seen_keys.insert(seg_key.clone(), pos);
1872                segments.push(AssembledSegment {
1873                    tag: seg_tag.clone(),
1874                    elements: vec![],
1875                    mig_number: None,
1876                    segment_number: None,
1877                });
1878                &mut segments[pos]
1879            };
1880
1881            while seg.elements.len() <= *element_idx {
1882                seg.elements.push(vec![]);
1883            }
1884            while seg.elements[*element_idx].len() <= *component_idx {
1885                seg.elements[*element_idx].push(String::new());
1886            }
1887            seg.elements[*element_idx][*component_idx] = val.clone();
1888        }
1889
1890        // Pad intermediate empty elements: any [] between position 0 and the last
1891        // populated position becomes [""] so the EDIFACT renderer emits the `+` separator.
1892        for seg in &mut segments {
1893            let last_populated = seg.elements.iter().rposition(|e| !e.is_empty());
1894            if let Some(last_idx) = last_populated {
1895                for i in 0..last_idx {
1896                    if seg.elements[i].is_empty() {
1897                        seg.elements[i] = vec![String::new()];
1898                    }
1899                }
1900            }
1901        }
1902
1903        // MIG-aware trailing padding: extend each segment to the MIG-defined element count.
1904        if let Some(ref ss) = self.segment_structure {
1905            for seg in &mut segments {
1906                if let Some(expected) = ss.element_count(&seg.tag) {
1907                    while seg.elements.len() < expected {
1908                        seg.elements.push(vec![String::new()]);
1909                    }
1910                }
1911            }
1912        }
1913
1914        AssembledGroupInstance {
1915            segments,
1916            child_groups: vec![],
1917            entry_mig_number: None,
1918            variant_mig_numbers: vec![],
1919            skipped_segments: Vec::new(),
1920            skipped_positions: Vec::new(),
1921        }
1922    }
1923
1924    /// Resolve a field path within a segment to extract a value.
1925    ///
1926    /// Two path conventions are supported:
1927    ///
1928    /// **Named paths** (backward compatible):
1929    /// - 1-part `"d3227"` → elements\[0\]\[0\]
1930    /// - 2-part `"c517.d3225"` → elements\[1\]\[0\]
1931    ///
1932    /// **Numeric index paths** (for multi-component access):
1933    /// - `"0"` → elements\[0\]\[0\]
1934    /// - `"1.0"` → elements\[1\]\[0\]
1935    /// - `"1.2"` → elements\[1\]\[2\]
1936    fn resolve_field_path(segment: &AssembledSegment, path: &[&str]) -> Option<String> {
1937        if path.is_empty() {
1938            return None;
1939        }
1940
1941        // Numeric paths only: index-based resolution.
1942        if let Ok(element_idx) = path[0].parse::<usize>() {
1943            let component_idx = if path.len() > 1 {
1944                path[1].parse::<usize>().unwrap_or(0)
1945            } else {
1946                0
1947            };
1948            return segment
1949                .elements
1950                .get(element_idx)?
1951                .get(component_idx)
1952                .filter(|v| !v.is_empty())
1953                .cloned();
1954        }
1955
1956        // Non-numeric path[0] indicates an EDIFACT ID path that the PathResolver
1957        // failed to normalize (e.g. composite/element absent from any loaded PID
1958        // schema). Returning None lets the field be omitted from output instead
1959        // of silently guessing element index 1, which previously surfaced
1960        // unrelated data (e.g. NAD c819.d3229 read as c082.d3039 / rollencodenummer).
1961        None
1962    }
1963
1964    /// Parse element and component indices from path parts after the segment tag.
1965    /// E.g., ["2"] -> (2, 0), ["0", "3"] -> (0, 3), ["1", "0"] -> (1, 0)
1966    pub(crate) fn parse_element_component(parts: &[&str]) -> (usize, usize) {
1967        if parts.is_empty() {
1968            return (0, 0);
1969        }
1970        let element_idx = parts[0].parse::<usize>().unwrap_or(0);
1971        let component_idx = if parts.len() > 1 {
1972            parts[1].parse::<usize>().unwrap_or(0)
1973        } else {
1974            0
1975        };
1976        (element_idx, component_idx)
1977    }
1978
1979    /// Extract a value from a BO4E JSON object by target field name.
1980    /// Supports dotted paths like "nested.field_name".
1981    pub fn populate_field(
1982        &self,
1983        bo4e_value: &serde_json::Value,
1984        target_field: &str,
1985    ) -> Option<String> {
1986        let mut current = bo4e_value;
1987        for part in target_field.split('.') {
1988            current = current.get(part)?;
1989        }
1990        // Handle enriched code objects: {"code": "Z15", "meaning": "..."}
1991        if let Some(code) = current.get("code").and_then(|v| v.as_str()) {
1992            return Some(code.to_string());
1993        }
1994        current.as_str().map(|s| s.to_string())
1995    }
1996
1997    /// Build a segment from BO4E values using the reverse mapping.
1998    pub fn build_segment_from_bo4e(
1999        &self,
2000        bo4e_value: &serde_json::Value,
2001        segment_tag: &str,
2002        target_field: &str,
2003    ) -> AssembledSegment {
2004        let value = self.populate_field(bo4e_value, target_field);
2005        let elements = if let Some(val) = value {
2006            vec![vec![val]]
2007        } else {
2008            vec![]
2009        };
2010        AssembledSegment {
2011            tag: segment_tag.to_uppercase(),
2012            elements,
2013            mig_number: None,
2014            segment_number: None,
2015        }
2016    }
2017
2018    // ── Multi-entity forward mapping ──
2019
2020    /// Parse a discriminator string (e.g., "SEQ.0.0=Z79") and find the matching
2021    /// repetition index within the given group path.
2022    ///
2023    /// Discriminator format: `"TAG.element_idx.component_idx=expected_value"`
2024    /// Scans all repetitions of the leaf group and returns the first rep index
2025    /// where the entry segment matches.
2026    pub fn resolve_repetition(
2027        tree: &AssembledTree,
2028        group_path: &str,
2029        discriminator: &str,
2030    ) -> Option<usize> {
2031        let (spec, expected) = discriminator.split_once('=')?;
2032        let parts: Vec<&str> = spec.split('.').collect();
2033        if parts.len() != 3 {
2034            return None;
2035        }
2036        let tag = parts[0];
2037        let element_idx: usize = parts[1].parse().ok()?;
2038        let component_idx: usize = parts[2].parse().ok()?;
2039
2040        // Navigate to the parent and get the leaf group with all its repetitions
2041        let path_parts: Vec<&str> = group_path.split('.').collect();
2042
2043        let leaf_group = if path_parts.len() == 1 {
2044            let (group_id, _) = parse_group_spec(path_parts[0]);
2045            tree.groups.iter().find(|g| g.group_id == group_id)?
2046        } else {
2047            // Navigate to the parent instance, then find the leaf group
2048            let parent_parts = &path_parts[..path_parts.len() - 1];
2049            let mut current_instance = {
2050                let (first_id, first_rep) = parse_group_spec(parent_parts[0]);
2051                let first_group = tree.groups.iter().find(|g| g.group_id == first_id)?;
2052                first_group.repetitions.get(first_rep.unwrap_or(0))?
2053            };
2054            for part in &parent_parts[1..] {
2055                let (group_id, explicit_rep) = parse_group_spec(part);
2056                let child_group = current_instance
2057                    .child_groups
2058                    .iter()
2059                    .find(|g| g.group_id == group_id)?;
2060                current_instance = child_group.repetitions.get(explicit_rep.unwrap_or(0))?;
2061            }
2062            let (leaf_id, _) = parse_group_spec(path_parts.last()?);
2063            current_instance
2064                .child_groups
2065                .iter()
2066                .find(|g| g.group_id == leaf_id)?
2067        };
2068
2069        // Scan all repetitions for the matching discriminator
2070        let expected_values: Vec<&str> = expected.split('|').collect();
2071        for (rep_idx, instance) in leaf_group.repetitions.iter().enumerate() {
2072            let matches = instance.segments.iter().any(|s| {
2073                s.tag.eq_ignore_ascii_case(tag)
2074                    && s.elements
2075                        .get(element_idx)
2076                        .and_then(|e| e.get(component_idx))
2077                        .map(|v| expected_values.iter().any(|ev| v == ev))
2078                        .unwrap_or(false)
2079            });
2080            if matches {
2081                return Some(rep_idx);
2082            }
2083        }
2084
2085        None
2086    }
2087
2088    /// Like `resolve_repetition`, but returns ALL matching rep indices instead of just the first.
2089    ///
2090    /// This is used for multi-Zeitscheibe support where multiple SG6 reps may match
2091    /// the same discriminator (e.g., multiple RFF+Z49 time slices).
2092    pub fn resolve_all_repetitions(
2093        tree: &AssembledTree,
2094        group_path: &str,
2095        discriminator: &str,
2096    ) -> Vec<usize> {
2097        let Some((spec, expected)) = discriminator.split_once('=') else {
2098            return Vec::new();
2099        };
2100        let parts: Vec<&str> = spec.split('.').collect();
2101        if parts.len() != 3 {
2102            return Vec::new();
2103        }
2104        let tag = parts[0];
2105        let element_idx: usize = match parts[1].parse() {
2106            Ok(v) => v,
2107            Err(_) => return Vec::new(),
2108        };
2109        let component_idx: usize = match parts[2].parse() {
2110            Ok(v) => v,
2111            Err(_) => return Vec::new(),
2112        };
2113
2114        // Navigate to the parent and get the leaf group with all its repetitions
2115        let path_parts: Vec<&str> = group_path.split('.').collect();
2116
2117        let leaf_group = if path_parts.len() == 1 {
2118            let (group_id, _) = parse_group_spec(path_parts[0]);
2119            match tree.groups.iter().find(|g| g.group_id == group_id) {
2120                Some(g) => g,
2121                None => return Vec::new(),
2122            }
2123        } else {
2124            let parent_parts = &path_parts[..path_parts.len() - 1];
2125            let mut current_instance = {
2126                let (first_id, first_rep) = parse_group_spec(parent_parts[0]);
2127                let first_group = match tree.groups.iter().find(|g| g.group_id == first_id) {
2128                    Some(g) => g,
2129                    None => return Vec::new(),
2130                };
2131                match first_group.repetitions.get(first_rep.unwrap_or(0)) {
2132                    Some(i) => i,
2133                    None => return Vec::new(),
2134                }
2135            };
2136            for part in &parent_parts[1..] {
2137                let (group_id, explicit_rep) = parse_group_spec(part);
2138                let child_group = match current_instance
2139                    .child_groups
2140                    .iter()
2141                    .find(|g| g.group_id == group_id)
2142                {
2143                    Some(g) => g,
2144                    None => return Vec::new(),
2145                };
2146                current_instance = match child_group.repetitions.get(explicit_rep.unwrap_or(0)) {
2147                    Some(i) => i,
2148                    None => return Vec::new(),
2149                };
2150            }
2151            let (leaf_id, _) = match path_parts.last() {
2152                Some(p) => parse_group_spec(p),
2153                None => return Vec::new(),
2154            };
2155            match current_instance
2156                .child_groups
2157                .iter()
2158                .find(|g| g.group_id == leaf_id)
2159            {
2160                Some(g) => g,
2161                None => return Vec::new(),
2162            }
2163        };
2164
2165        // Parse optional occurrence index from expected value: "TN#1" → ("TN", Some(1))
2166        let (expected_raw, occurrence) = parse_discriminator_occurrence(expected);
2167
2168        // Collect ALL matching rep indices
2169        let expected_values: Vec<&str> = expected_raw.split('|').collect();
2170        let mut result = Vec::new();
2171        for (rep_idx, instance) in leaf_group.repetitions.iter().enumerate() {
2172            let matches = instance.segments.iter().any(|s| {
2173                s.tag.eq_ignore_ascii_case(tag)
2174                    && s.elements
2175                        .get(element_idx)
2176                        .and_then(|e| e.get(component_idx))
2177                        .map(|v| expected_values.iter().any(|ev| v == ev))
2178                        .unwrap_or(false)
2179            });
2180            if matches {
2181                result.push(rep_idx);
2182            }
2183        }
2184
2185        // If occurrence index specified, return only that match
2186        if let Some(occ) = occurrence {
2187            result.into_iter().nth(occ).into_iter().collect()
2188        } else {
2189            result
2190        }
2191    }
2192
2193    /// Resolve a discriminated instance using source_path for parent navigation.
2194    ///
2195    /// Like `resolve_repetition` + `resolve_group_instance`, but navigates to the
2196    /// parent group via source_path qualifier suffixes. Returns the matching instance
2197    /// directly (not just a rep index) to avoid re-navigation in `map_forward_inner`.
2198    ///
2199    /// For example, `source_path = "sg4.sg8_z98.sg10"` with `discriminator = "CCI.2.0=ZB3"`
2200    /// navigates to the SG8 instance with SEQ qualifier Z98, then finds the SG10 rep
2201    /// where CCI element 2 component 0 equals "ZB3".
2202    /// Map all definitions against a tree, returning a JSON object with entity names as keys.
2203    ///
2204    /// For each definition:
2205    /// - Has discriminator → find matching rep via `resolve_repetition`, map single instance
2206    /// - Root-level (empty source_group) → map rep 0 as single object
2207    /// - No discriminator, 1 rep in tree → map as single object
2208    /// - No discriminator, multiple reps in tree → map ALL reps into a JSON array
2209    ///
2210    /// When multiple definitions share the same `entity` name, their fields are
2211    /// deep-merged into a single JSON object. This allows related TOML files
2212    /// (e.g., LOC location + SEQ info + SG10 characteristics) to contribute
2213    /// fields to the same BO4E entity.
2214    pub fn map_all_forward(&self, tree: &AssembledTree) -> serde_json::Value {
2215        self.map_all_forward_inner(tree, true).0
2216    }
2217
2218    /// Like [`map_all_forward`](Self::map_all_forward) but with explicit
2219    /// `enrich_codes` control (when `false`, code fields are plain strings
2220    /// instead of `{"code": …, "meaning": …}` objects).
2221    pub fn map_all_forward_enriched(
2222        &self,
2223        tree: &AssembledTree,
2224        enrich_codes: bool,
2225    ) -> serde_json::Value {
2226        self.map_all_forward_inner(tree, enrich_codes).0
2227    }
2228
2229    /// Inner implementation with enrichment control.
2230    ///
2231    /// Returns `(json_value, nesting_info)`, where `nesting_info` maps entity
2232    /// keys to the parent rep index for each child element (used by the reverse
2233    /// mapper to distribute nested group children among their parent reps).
2234    fn map_all_forward_inner(
2235        &self,
2236        tree: &AssembledTree,
2237        enrich_codes: bool,
2238    ) -> (
2239        serde_json::Value,
2240        std::collections::HashMap<String, Vec<usize>>,
2241    ) {
2242        self.map_all_forward_inner_with_tx(tree, enrich_codes, self.transaction_group.as_deref())
2243    }
2244
2245    /// Like `map_all_forward_inner` but with an explicit transaction-group
2246    /// override. Used by `map_interchange`, which knows the tx group even when
2247    /// the caller-supplied tx_engine wasn't built with `with_transaction_group`.
2248    fn map_all_forward_inner_with_tx(
2249        &self,
2250        tree: &AssembledTree,
2251        enrich_codes: bool,
2252        tx_group_override: Option<&str>,
2253    ) -> (
2254        serde_json::Value,
2255        std::collections::HashMap<String, Vec<usize>>,
2256    ) {
2257        let mut result = serde_json::Map::new();
2258        let mut nesting_info: std::collections::HashMap<String, Vec<usize>> =
2259            std::collections::HashMap::new();
2260        // Source groups that have written each entity key so far.
2261        let mut contributors: std::collections::HashMap<String, Vec<String>> =
2262            std::collections::HashMap::new();
2263
2264        for def in &self.definitions {
2265            // `parent_field` and bound children are mapped inside their parent's
2266            // instance (see `extract_nested_children`), never as top-level entities.
2267            if def.meta.parent_field.is_some() || is_bound_child(&self.definitions, def) {
2268                continue;
2269            }
2270            let entity = &def.meta.entity;
2271
2272            let bo4e = if let Some(ref disc) = def.meta.discriminator {
2273                // Has discriminator — resolve to matching rep(s).
2274                // Use source_path navigation when qualifiers are present
2275                // (e.g., "sg4.sg8_z98.sg10" navigates to Z98's SG10 reps,
2276                //  "sg4.sg5_z17" finds all LOC+Z17 when there are multiple).
2277                let use_source_path = def
2278                    .meta
2279                    .source_path
2280                    .as_ref()
2281                    .is_some_and(|sp| has_source_path_qualifiers(sp));
2282                if use_source_path {
2283                    // Navigate via source_path, then filter by discriminator.
2284                    let sp = def.meta.source_path.as_deref().unwrap();
2285                    let all_instances = Self::resolve_all_by_source_path(tree, sp);
2286                    // Apply discriminator filter to resolved instances (respects #N occurrence)
2287                    let instances: Vec<_> = if let Some(matcher) = DiscriminatorMatcher::parse(disc)
2288                    {
2289                        matcher.filter_instances(all_instances)
2290                    } else {
2291                        all_instances
2292                    };
2293                    let extract = |instance: &AssembledGroupInstance| {
2294                        let mut r = serde_json::Map::new();
2295                        self.extract_fields_from_instance(instance, def, &mut r, enrich_codes);
2296                        serde_json::Value::Object(r)
2297                    };
2298                    match instances.len() {
2299                        0 => None,
2300                        1 => Some(extract(instances[0])),
2301                        _ => Some(serde_json::Value::Array(
2302                            instances.iter().map(|i| extract(i)).collect(),
2303                        )),
2304                    }
2305                } else {
2306                    let reps = Self::resolve_all_repetitions(tree, &def.meta.source_group, disc);
2307                    match reps.len() {
2308                        0 => None,
2309                        1 => Some(self.map_forward_inner(tree, def, reps[0], enrich_codes)),
2310                        _ => Some(serde_json::Value::Array(
2311                            reps.iter()
2312                                .map(|&rep| self.map_forward_inner(tree, def, rep, enrich_codes))
2313                                .collect(),
2314                        )),
2315                    }
2316                }
2317            } else if def.meta.source_group.is_empty() {
2318                // Root-level mapping — always single object
2319                Some(self.map_forward_inner(tree, def, 0, enrich_codes))
2320            } else if def.meta.source_path.as_ref().is_some_and(|sp| {
2321                has_source_path_qualifiers(sp) || def.meta.source_group.contains('.')
2322            }) {
2323                // Multi-level source path — navigate via source_path to collect all
2324                // instances across all parent repetitions. Handles both qualified
2325                // paths (e.g., "sg4.sg8_zd7.sg10") and unqualified paths (e.g.,
2326                // "sg17.sg36.sg40") where multiple parent reps each have children.
2327                let sp = def.meta.source_path.as_deref().unwrap();
2328                let mut indexed = Self::resolve_all_with_parent_indices(tree, sp);
2329
2330                // When the LAST part of source_path has no qualifier (e.g., "sg29.sg30"),
2331                // exclude reps that match a qualified sibling definition's qualifier
2332                // (e.g., "sg29.sg30_z35"). This prevents double-extraction when both
2333                // qualified and unqualified definitions target the same group.
2334                if let Some(last_part) = sp.rsplit('.').next() {
2335                    if !last_part.contains('_') {
2336                        // Collect qualifiers from sibling definitions that share the
2337                        // same base group name. E.g., for "sg29.sg30", only match
2338                        // "sg29.sg30_z35" (same base "sg30"), NOT "sg29.sg31_z35".
2339                        let base_prefix = if let Some(parent) = sp.rsplit_once('.') {
2340                            format!("{}.", parent.0)
2341                        } else {
2342                            String::new()
2343                        };
2344                        let sibling_qualifiers: Vec<String> = self
2345                            .definitions
2346                            .iter()
2347                            .filter_map(|d| d.meta.source_path.as_deref())
2348                            .filter(|other_sp| {
2349                                *other_sp != sp
2350                                    && other_sp.starts_with(&base_prefix)
2351                                    && other_sp.split('.').count() == sp.split('.').count()
2352                            })
2353                            .filter_map(|other_sp| {
2354                                let other_last = other_sp.rsplit('.').next()?;
2355                                // Only match siblings with the same base group name
2356                                // e.g., "sg30_z35" has base "sg30", must match "sg30"
2357                                let (base, q) = other_last.split_once('_')?;
2358                                if base == last_part {
2359                                    Some(q.to_string())
2360                                } else {
2361                                    None
2362                                }
2363                            })
2364                            .collect();
2365
2366                        if !sibling_qualifiers.is_empty() {
2367                            indexed.retain(|(_, inst)| {
2368                                let entry_qual = inst
2369                                    .segments
2370                                    .first()
2371                                    .and_then(|seg| seg.elements.first())
2372                                    .and_then(|el| el.first())
2373                                    .map(|v| v.to_lowercase());
2374                                // Keep reps whose entry qualifier does NOT match
2375                                // any sibling's qualifier
2376                                !entry_qual.is_some_and(|q| {
2377                                    sibling_qualifiers.iter().any(|sq| {
2378                                        sq.split('_').any(|part| part.eq_ignore_ascii_case(&q))
2379                                    })
2380                                })
2381                            });
2382                        }
2383                    }
2384                }
2385                let extract = |instance: &AssembledGroupInstance| {
2386                    let mut r = serde_json::Map::new();
2387                    self.extract_fields_from_instance(instance, def, &mut r, enrich_codes);
2388                    serde_json::Value::Object(r)
2389                };
2390                // Track parent rep indices for nesting reconstruction.
2391                // Key by source_path (not entity or source_group) so that definitions
2392                // at different depths or with different qualifiers don't collide.
2393                // e.g., "sg5.sg8_z41.sg9" vs "sg5.sg8_z42.sg9" are distinct keys.
2394                if def.meta.source_group.contains('.') && !indexed.is_empty() {
2395                    if let Some(sp) = &def.meta.source_path {
2396                        let parent_indices: Vec<usize> =
2397                            indexed.iter().map(|(idx, _)| *idx).collect();
2398                        nesting_info.entry(sp.clone()).or_insert(parent_indices);
2399
2400                        // Also store child rep indices (position within the leaf group)
2401                        // for depth-1 reverse placement. Key: "{sp}#child".
2402                        let child_key = format!("{sp}#child");
2403                        if let std::collections::hash_map::Entry::Vacant(e) =
2404                            nesting_info.entry(child_key)
2405                        {
2406                            let child_indices: Vec<usize> =
2407                                Self::compute_child_indices(tree, sp, &indexed);
2408                            if !child_indices.is_empty() {
2409                                e.insert(child_indices);
2410                            }
2411                        }
2412                    }
2413                }
2414                match indexed.len() {
2415                    0 => None,
2416                    1 => Some(extract(indexed[0].1)),
2417                    _ => Some(serde_json::Value::Array(
2418                        indexed.iter().map(|(_, i)| extract(i)).collect(),
2419                    )),
2420                }
2421            } else {
2422                let num_reps = Self::count_repetitions(tree, &def.meta.source_group);
2423                if num_reps <= 1 {
2424                    Some(self.map_forward_inner(tree, def, 0, enrich_codes))
2425                } else {
2426                    // Multiple reps, no discriminator — map all into array
2427                    let mut items = Vec::with_capacity(num_reps);
2428                    for rep in 0..num_reps {
2429                        items.push(self.map_forward_inner(tree, def, rep, enrich_codes));
2430                    }
2431                    Some(serde_json::Value::Array(items))
2432                }
2433            };
2434
2435            if let Some(bo4e) = bo4e {
2436                let key = to_camel_case(entity);
2437                match def.meta.target_list.as_deref() {
2438                    Some(list_field) => append_to_list_field(&mut result, &key, list_field, bo4e),
2439                    None => {
2440                        // Keep both on a shape mismatch only for sibling groups:
2441                        // no earlier contributor of this entity is this group's
2442                        // ancestor or descendant (see `merge_entity`).
2443                        let group = def
2444                            .meta
2445                            .source_path
2446                            .clone()
2447                            .unwrap_or_else(|| def.meta.source_group.to_lowercase());
2448                        let seen = contributors.entry(key.clone()).or_default();
2449                        let nested = seen.iter().any(|other: &String| {
2450                            group.starts_with(&format!("{other}."))
2451                                || other.starts_with(&format!("{group}."))
2452                        });
2453                        seen.push(group);
2454                        merge_entity(&mut result, &key, bo4e, !nested);
2455                    }
2456                }
2457            }
2458        }
2459
2460        // Post-process: nest child entities under their parent entities.
2461        // E.g., Kontakt (source_group="SG2.SG3") moves under Marktteilnehmer (source_group="SG2").
2462        // Children whose parent group is the transaction root (e.g. SG4 for UTILMD) are
2463        // left at the top level — see MappingEngine::transaction_group.
2464        nest_child_entities_in_result(
2465            &mut result,
2466            &self.definitions,
2467            &nesting_info,
2468            tx_group_override,
2469        );
2470
2471        (serde_json::Value::Object(result), nesting_info)
2472    }
2473
2474    /// Reverse-map a BO4E entity map back to an AssembledTree.
2475    ///
2476    /// For each definition:
2477    /// 1. Look up entity in input by `meta.entity` name
2478    /// 2. If entity value is an array, map each element as a separate group repetition
2479    /// 3. Place results by `source_group`: `""` → root segments, `"SGn"` → groups
2480    ///
2481    /// This is the inverse of `map_all_forward()`.
2482    pub fn map_all_reverse(
2483        &self,
2484        entities: &serde_json::Value,
2485        nesting_info: Option<&std::collections::HashMap<String, Vec<usize>>>,
2486    ) -> AssembledTree {
2487        self.map_all_reverse_with_mig(entities, nesting_info, None)
2488    }
2489
2490    /// [`map_all_reverse`](Self::map_all_reverse) with the PID-filtered MIG,
2491    /// which decides the parent of a nested child entity the BO4E JSON does
2492    /// not link to a parent (see the nesting step below).
2493    pub fn map_all_reverse_with_mig(
2494        &self,
2495        entities: &serde_json::Value,
2496        nesting_info: Option<&std::collections::HashMap<String, Vec<usize>>>,
2497        mig: Option<&MigSchema>,
2498    ) -> AssembledTree {
2499        let mut root_segments: Vec<AssembledSegment> = Vec::new();
2500        let mut groups: Vec<AssembledGroup> = Vec::new();
2501        // Track parent rep indices for child entities extracted from map-keyed
2502        // or array parents.  Used as fallback when nesting_info is empty.
2503        let mut inferred_nesting: std::collections::HashMap<String, Vec<usize>> =
2504            std::collections::HashMap::new();
2505
2506        for def in &self.definitions {
2507            // `parent_field` and bound children are reversed with their parent
2508            // object (see `reverse_nested_children`).
2509            if def.meta.parent_field.is_some() || is_bound_child(&self.definitions, def) {
2510                continue;
2511            }
2512            let entity_key = to_camel_case(&def.meta.entity);
2513
2514            // Look up entity value — first at top level, then nested under parent.
2515            // `_extracted` keeps the owned value alive for the borrow below.
2516            let _extracted: Option<serde_json::Value>;
2517            let entity_value = if let Some(list_field) = def.meta.target_list.as_deref() {
2518                // `target_list`: this definition's data is not the entity object,
2519                // it is the elements of a list field on it. Handing the array
2520                // straight to the array branch below turns each element back into
2521                // one group repetition, which is the exact inverse of the forward
2522                // "one repetition -> one element" rule.
2523                match entities.get(&entity_key).and_then(|e| e.get(list_field)) {
2524                    Some(v) if v.is_array() => {
2525                        _extracted = None;
2526                        v
2527                    }
2528                    _ => continue,
2529                }
2530            } else if let Some(v) = entities.get(&entity_key) {
2531                _extracted = None;
2532                v
2533            } else if def.meta.source_group.contains('.') {
2534                // Child entity not at top level — try extracting from parent entity
2535                match extract_child_from_parent_with_indices(entities, &self.definitions, def) {
2536                    Some((v, parent_indices)) => {
2537                        // Record inferred parent rep indices for nesting distribution
2538                        if let Some(sp) = def.meta.source_path.as_deref() {
2539                            inferred_nesting
2540                                .entry(sp.to_string())
2541                                .or_insert(parent_indices);
2542                        }
2543                        _extracted = Some(v);
2544                        _extracted.as_ref().unwrap()
2545                    }
2546                    None => continue,
2547                }
2548            } else {
2549                continue;
2550            };
2551
2552            // Support map-keyed entities from typed PID format.
2553            // E.g., geschaeftspartner: {"Z04": {name1: "..."}} with discriminator NAD.0.0=Z04.
2554            // Extract inner value using discriminator's qualifier value as key,
2555            // and inject the qualifier into the inner object so companion fields find it.
2556            //
2557            // Also handles non-discriminated maps (e.g., marktteilnehmer: {"MS": {...}, "MR": {...}})
2558            // by converting them to arrays of inner values.
2559            let unwrapped: Option<serde_json::Value>;
2560            let entity_value = if entity_value.is_object() && !entity_value.is_array() {
2561                if let Some(disc_value) = def
2562                    .meta
2563                    .discriminator
2564                    .as_deref()
2565                    .and_then(|d| d.split_once('='))
2566                    .map(|(_, v)| v)
2567                {
2568                    // Discriminated definition: try to extract map key matching qualifier
2569                    if let Some(inner) = entity_value.get(disc_value) {
2570                        let mut injected = inner.clone();
2571                        // Find the field that maps to the discriminator's EDIFACT path
2572                        // and inject the map key as that field's value (e.g., nadQualifier = "Z04")
2573                        if let Some(qualifier_field) =
2574                            find_qualifier_companion_field(&self.definitions, &def.meta.entity)
2575                        {
2576                            if let Some(obj) = injected.as_object_mut() {
2577                                let entry = obj
2578                                    .entry(qualifier_field)
2579                                    .or_insert(serde_json::Value::Null);
2580                                if entry.is_null() {
2581                                    *entry = serde_json::Value::String(disc_value.to_string());
2582                                }
2583                            }
2584                        }
2585                        unwrapped = Some(injected);
2586                        unwrapped.as_ref().unwrap()
2587                    } else {
2588                        entity_value
2589                    }
2590                } else if is_map_keyed_object(entity_value) {
2591                    // Non-discriminated definition: convert map to array
2592                    // e.g., marktteilnehmer: {"MS": {...}, "MR": {...}} → [{...}, {...}]
2593                    // Inject each map key into its inner object using the companion field
2594                    // that maps to the discriminator path (if identifiable from other defs).
2595                    let map = entity_value.as_object().unwrap();
2596                    let arr: Vec<serde_json::Value> = map
2597                        .iter()
2598                        .map(|(key, val)| {
2599                            let mut item = val.clone();
2600                            // Try to find a qualifier companion field from peer definitions
2601                            // that share this entity name and have a discriminator
2602                            if let Some(obj) = item.as_object_mut() {
2603                                if let Some(qualifier_field) = find_qualifier_companion_field(
2604                                    &self.definitions,
2605                                    &def.meta.entity,
2606                                ) {
2607                                    let entry = obj
2608                                        .entry(qualifier_field)
2609                                        .or_insert(serde_json::Value::Null);
2610                                    if entry.is_null() {
2611                                        *entry = serde_json::Value::String(key.clone());
2612                                    }
2613                                }
2614                            }
2615                            item
2616                        })
2617                        .collect();
2618                    unwrapped = Some(serde_json::Value::Array(arr));
2619                    unwrapped.as_ref().unwrap()
2620                } else {
2621                    entity_value
2622                }
2623            } else {
2624                entity_value
2625            };
2626
2627            // Determine target group from source_group (use leaf part after last dot)
2628            let leaf_group = def
2629                .meta
2630                .source_group
2631                .rsplit('.')
2632                .next()
2633                .unwrap_or(&def.meta.source_group);
2634
2635            if def.meta.source_group.is_empty() {
2636                // Root-level: reverse into root segments
2637                let instance = self.map_reverse(entity_value, def);
2638                root_segments.extend(instance.segments);
2639            } else if entity_value.is_array() {
2640                // Array entity: each element becomes a group repetition
2641                let arr = entity_value.as_array().unwrap();
2642                let reps: Vec<_> = arr.iter().map(|item| self.map_reverse(item, def)).collect();
2643
2644                // Merge into existing group or create new one
2645                if let Some(existing) = groups.iter_mut().find(|g| g.group_id == leaf_group) {
2646                    existing.repetitions.extend(reps);
2647                } else {
2648                    groups.push(AssembledGroup {
2649                        group_id: leaf_group.to_string(),
2650                        repetitions: reps,
2651                    });
2652                }
2653            } else {
2654                // Single object: one repetition
2655                let instance = self.map_reverse(entity_value, def);
2656
2657                if let Some(existing) = groups.iter_mut().find(|g| g.group_id == leaf_group) {
2658                    existing.repetitions.push(instance);
2659                } else {
2660                    groups.push(AssembledGroup {
2661                        group_id: leaf_group.to_string(),
2662                        repetitions: vec![instance],
2663                    });
2664                }
2665            }
2666        }
2667
2668        // Post-process: move nested groups under their parent repetitions.
2669        // Definitions with multi-level source_group (e.g., "SG2.SG3") produce
2670        // top-level groups that must be nested inside their parent group.
2671        // Children are distributed sequentially among parent reps (child[i] → parent[i])
2672        // matching the forward mapper's extraction order.
2673        let nested_specs: Vec<(String, String)> = self
2674            .definitions
2675            .iter()
2676            .filter(|def| def.meta.parent_field.is_none())
2677            .filter_map(|def| {
2678                let parts: Vec<&str> = def.meta.source_group.split('.').collect();
2679                if parts.len() > 1 {
2680                    Some((parts[0].to_string(), parts[parts.len() - 1].to_string()))
2681                } else {
2682                    None
2683                }
2684            })
2685            .collect();
2686        for (parent_id, child_id) in &nested_specs {
2687            // Only nest if both parent and child exist at the top level
2688            let has_parent = groups.iter().any(|g| g.group_id == *parent_id);
2689            let has_child = groups.iter().any(|g| g.group_id == *child_id);
2690            if has_parent && has_child {
2691                let child_idx = groups.iter().position(|g| g.group_id == *child_id).unwrap();
2692                let child_group = groups.remove(child_idx);
2693                let parent = groups
2694                    .iter_mut()
2695                    .find(|g| g.group_id == *parent_id)
2696                    .unwrap();
2697                // Distribute child reps among parent reps using nesting info
2698                // if available, falling back to all-under-first when not.
2699                // Nesting info is keyed by source_path (e.g., "sg2.sg3").
2700                let child_source_path = self
2701                    .definitions
2702                    .iter()
2703                    .find(|d| {
2704                        let parts: Vec<&str> = d.meta.source_group.split('.').collect();
2705                        d.meta.parent_field.is_none()
2706                            && parts.len() > 1
2707                            && parts[parts.len() - 1] == *child_id
2708                    })
2709                    .and_then(|d| d.meta.source_path.as_deref());
2710                let distribution = child_source_path.and_then(|key| {
2711                    nesting_info
2712                        .and_then(|ni| ni.get(key))
2713                        .or_else(|| inferred_nesting.get(key))
2714                });
2715                // Without a link from the JSON, the parent follows from the MIG:
2716                // the first repetition (in MIG variant order) whose variant
2717                // defines this child group — e.g. the SG2 NAD+MS repetition for
2718                // the sender's SG3 contact. Not "the first array element": BO4E
2719                // carries no ordering information.
2720                let unlinked_target = mig
2721                    .and_then(|m| {
2722                        mig_assembly::repetition_order::preferred_parent_repetition(
2723                            parent,
2724                            &m.segment_groups,
2725                            child_id,
2726                        )
2727                    })
2728                    .unwrap_or(0);
2729                for (i, child_rep) in child_group.repetitions.into_iter().enumerate() {
2730                    let target_idx = distribution
2731                        .and_then(|dist| dist.get(i))
2732                        .copied()
2733                        .unwrap_or(unlinked_target);
2734
2735                    if let Some(target_rep) = parent.repetitions.get_mut(target_idx) {
2736                        if let Some(existing) = target_rep
2737                            .child_groups
2738                            .iter_mut()
2739                            .find(|g| g.group_id == *child_id)
2740                        {
2741                            existing.repetitions.push(child_rep);
2742                        } else {
2743                            target_rep.child_groups.push(AssembledGroup {
2744                                group_id: child_id.clone(),
2745                                repetitions: vec![child_rep],
2746                            });
2747                        }
2748                    }
2749                }
2750            }
2751        }
2752
2753        let post_group_start = root_segments.len();
2754        AssembledTree {
2755            segments: root_segments,
2756            groups,
2757            post_group_start,
2758            inter_group_segments: std::collections::BTreeMap::new(),
2759        }
2760    }
2761
2762    /// Count the number of repetitions available for a group path in the tree.
2763    fn count_repetitions(tree: &AssembledTree, group_path: &str) -> usize {
2764        let parts: Vec<&str> = group_path.split('.').collect();
2765
2766        let (first_id, first_rep) = parse_group_spec(parts[0]);
2767        let first_group = match tree.groups.iter().find(|g| g.group_id == first_id) {
2768            Some(g) => g,
2769            None => return 0,
2770        };
2771
2772        if parts.len() == 1 {
2773            return first_group.repetitions.len();
2774        }
2775
2776        // Navigate to parent, then count leaf group reps
2777        let mut current_instance = match first_group.repetitions.get(first_rep.unwrap_or(0)) {
2778            Some(i) => i,
2779            None => return 0,
2780        };
2781
2782        for (i, part) in parts[1..].iter().enumerate() {
2783            let (group_id, explicit_rep) = parse_group_spec(part);
2784            let child_group = match current_instance
2785                .child_groups
2786                .iter()
2787                .find(|g| g.group_id == group_id)
2788            {
2789                Some(g) => g,
2790                None => return 0,
2791            };
2792
2793            if i == parts.len() - 2 {
2794                // Last part — return rep count
2795                return child_group.repetitions.len();
2796            }
2797            current_instance = match child_group.repetitions.get(explicit_rep.unwrap_or(0)) {
2798                Some(i) => i,
2799                None => return 0,
2800            };
2801        }
2802
2803        0
2804    }
2805
2806    /// Translate an assembled tree into BO4E, without code enrichment.
2807    ///
2808    /// This is the translation proper: every code field is a plain string, as it
2809    /// appears in the EDIFACT message. Enrichment (`{code, meaning, enum}`) is a
2810    /// display concern and is applied separately by [`Self::enrich_bo4e_types`],
2811    /// so a caller that does not need it never pays for it and never has to
2812    /// strip it back out.
2813    pub fn translate_edifact_to_bo4e(
2814        msg_engine: &MappingEngine,
2815        tx_engine: &MappingEngine,
2816        tree: &AssembledTree,
2817        transaction_group: &str,
2818    ) -> crate::model::MappedMessage {
2819        Self::map_interchange_inner(msg_engine, tx_engine, tree, transaction_group, false)
2820    }
2821
2822    /// Decorate code fields of an already-translated message in place.
2823    ///
2824    /// Replaces the plain string at each code position with
2825    /// `{"code": …, "meaning": …, "enum": …}`. Needs a [`CodeLookup`] on the
2826    /// engines; without one this is a no-op, which is why CI — which never
2827    /// attaches a lookup — sees the unenriched shape.
2828    ///
2829    /// Works from the mapping definitions rather than from the EDIFACT tree: a
2830    /// definition knows both where a value came from (`source_path` plus the
2831    /// segment/element coordinates of the field) and where it went (`target`),
2832    /// which is all the lookup needs. The original EDIFACT value is recovered by
2833    /// inverting `enum_map` the same way the reverse mapper does, including the
2834    /// `also_target` disambiguation for codes that share a primary value.
2835    pub fn enrich_bo4e_types(
2836        msg_engine: &MappingEngine,
2837        tx_engine: &MappingEngine,
2838        mapped: &mut crate::model::MappedMessage,
2839    ) {
2840        msg_engine.enrich_entities(&mut mapped.stammdaten);
2841        for tx in &mut mapped.transaktionen {
2842            tx_engine.enrich_entities(&mut tx.stammdaten);
2843        }
2844
2845        // The metadata slots hold mapped entities too. The forward pass splits
2846        // them out of `stammdaten`, so walking `stammdaten` alone no longer
2847        // reaches them — and their code fields would silently stay plain.
2848        msg_engine.enrich_named_entity(
2849            &mut mapped.nachricht_meta,
2850            crate::model::MSG_METADATA_ENTITY,
2851        );
2852        for tx in &mut mapped.transaktionen {
2853            tx_engine
2854                .enrich_named_entity(&mut tx.transaktionsdaten, crate::model::TX_METADATA_ENTITY);
2855        }
2856    }
2857
2858    /// Apply the code sites of one named entity to a value holding that entity.
2859    ///
2860    /// The entity-map walk keys on the enclosing object's field name; a metadata
2861    /// slot has no such name, so the entity is named explicitly here.
2862    fn enrich_named_entity(&self, value: &mut serde_json::Value, entity_key: &str) {
2863        if self.code_lookup.is_none() || value.is_null() {
2864            return;
2865        }
2866        let sites = self.code_sites();
2867        if let Some(entity_sites) = sites.get(entity_key) {
2868            Self::apply_sites(self, value, entity_sites);
2869        }
2870    }
2871
2872    /// Apply this engine's code enrichment to one entity map.
2873    ///
2874    /// Entities are located by key at any depth, because the forward pass moves
2875    /// them after extraction: `nest_child_entities_in_result` puts children
2876    /// under their parents.
2877    fn enrich_entities(&self, value: &mut serde_json::Value) {
2878        if self.code_lookup.is_none() {
2879            return;
2880        }
2881        let sites: HashMap<String, Vec<CodeSite<'_>>> = self.code_sites();
2882        if sites.is_empty() {
2883            return;
2884        }
2885        Self::walk_and_enrich(self, value, &sites);
2886    }
2887
2888    /// Every code-field position this engine's definitions write to, grouped by
2889    /// the entity key the value ends up under.
2890    fn code_sites(&self) -> HashMap<String, Vec<CodeSite<'_>>> {
2891        let Some(ref code_lookup) = self.code_lookup else {
2892            return HashMap::new();
2893        };
2894        let mut sites: HashMap<String, Vec<CodeSite<'_>>> = HashMap::new();
2895
2896        for def in &self.definitions {
2897            let Some(ref source_path) = def.meta.source_path else {
2898                continue;
2899            };
2900            let entity_key = to_camel_case(&def.meta.entity);
2901
2902            for (path, field_mapping) in &def.fields {
2903                let (target, enum_map, also_target, also_enum_map) = match field_mapping {
2904                    FieldMapping::Simple(t) => (t.as_str(), None, None, None),
2905                    FieldMapping::Structured(s) => (
2906                        s.target.as_str(),
2907                        self.table(s.enum_map.as_ref(), s.code_list.as_deref()),
2908                        s.also_target.as_deref(),
2909                        self.table(s.also_enum_map.as_ref(), s.also_code_list.as_deref()),
2910                    ),
2911                    FieldMapping::Nested(_) => continue,
2912                };
2913                if target.is_empty() {
2914                    continue;
2915                }
2916
2917                let parts: Vec<&str> = path.split('.').collect();
2918                let (seg_tag, path_qualifier, _occ) = parse_tag_qualifier(parts[0]);
2919                let (element_idx, component_idx) = Self::parse_element_component(&parts[1..]);
2920                // Same predicate, and the same two qualifiers, as the pre-split
2921                // path in `extract_fields_from_instance`: the field key's own
2922                // qualifier selects the schema variant, the discriminator's only
2923                // where the key has none. Asking with one merged qualifier — as
2924                // this did — calls `cav[Z30]`'s device number a code field and
2925                // decorates it, which the pre-split path never did.
2926                let disc_qualifier = Self::discriminator_qualifier_for_tag(def, &seg_tag);
2927                if code_lookup
2928                    .enrichment_codes(
2929                        source_path,
2930                        &seg_tag,
2931                        path_qualifier,
2932                        disc_qualifier.as_deref(),
2933                        element_idx,
2934                        component_idx,
2935                    )
2936                    .is_none()
2937                {
2938                    continue;
2939                }
2940
2941                sites.entry(entity_key.clone()).or_default().push(CodeSite {
2942                    target,
2943                    parent_field: def.meta.parent_field.as_deref(),
2944                    source_path,
2945                    seg_tag,
2946                    path_qualifier: path_qualifier.map(str::to_string),
2947                    disc_qualifier,
2948                    element_idx,
2949                    component_idx,
2950                    enum_map,
2951                    also_target,
2952                    also_enum_map,
2953                });
2954            }
2955        }
2956        sites
2957    }
2958
2959    /// Descend through the result, enriching every object that sits under a key
2960    /// naming an entity this engine maps.
2961    fn walk_and_enrich(
2962        engine: &MappingEngine,
2963        value: &mut serde_json::Value,
2964        sites: &HashMap<String, Vec<CodeSite<'_>>>,
2965    ) {
2966        match value {
2967            serde_json::Value::Object(map) => {
2968                for (key, child) in map.iter_mut() {
2969                    if let Some(entity_sites) = sites.get(key.as_str()) {
2970                        Self::apply_sites(engine, child, entity_sites);
2971                    }
2972                    Self::walk_and_enrich(engine, child, sites);
2973                }
2974            }
2975            serde_json::Value::Array(items) => {
2976                for item in items.iter_mut() {
2977                    Self::walk_and_enrich(engine, item, sites);
2978                }
2979            }
2980            _ => {}
2981        }
2982    }
2983
2984    /// Apply one entity's code sites to an entity value (an object, or an array
2985    /// of them when the group repeats).
2986    fn apply_sites(engine: &MappingEngine, value: &mut serde_json::Value, sites: &[CodeSite<'_>]) {
2987        match value {
2988            serde_json::Value::Array(items) => {
2989                for item in items.iter_mut() {
2990                    Self::apply_sites(engine, item, sites);
2991                }
2992            }
2993            serde_json::Value::Object(_) => {
2994                for site in sites {
2995                    match site.parent_field {
2996                        None => engine.enrich_one(value, site),
2997                        Some(field) => {
2998                            if let Some(nested) = value.get_mut(field) {
2999                                Self::apply_nested_site(engine, nested, site);
3000                            }
3001                        }
3002                    }
3003                }
3004            }
3005            _ => {}
3006        }
3007    }
3008
3009    /// Apply one nested site to every element of the `parent_field` array.
3010    fn apply_nested_site(
3011        engine: &MappingEngine,
3012        value: &mut serde_json::Value,
3013        site: &CodeSite<'_>,
3014    ) {
3015        match value {
3016            serde_json::Value::Array(items) => {
3017                for item in items.iter_mut() {
3018                    Self::apply_nested_site(engine, item, site);
3019                }
3020            }
3021            serde_json::Value::Object(_) => engine.enrich_one(value, site),
3022            _ => {}
3023        }
3024    }
3025
3026    /// Enrich a single position, if it currently holds a plain string.
3027    fn enrich_one(&self, entity: &mut serde_json::Value, site: &CodeSite<'_>) {
3028        // A list target (`werte[].code`) enriches the key in every element.
3029        if let Some((list, sub)) = list_target(site.target) {
3030            if let Some(items) = entity.get_mut(list).and_then(|v| v.as_array_mut()) {
3031                let element_site = CodeSite {
3032                    target: sub,
3033                    ..site.clone()
3034                };
3035                for item in items {
3036                    self.enrich_one(item, &element_site);
3037                }
3038            }
3039            return;
3040        }
3041        let Some(ref code_lookup) = self.code_lookup else {
3042            return;
3043        };
3044        // Already an object means another definition enriched this position.
3045        let Some(mapped_val) = Self::read_plain_string(entity, site.target) else {
3046            return;
3047        };
3048
3049        // Recover the EDIFACT value: the schema's codes are raw ("293"), while
3050        // the JSON holds the enum_map target ("BDEW").
3051        let raw = match site.enum_map {
3052            None => mapped_val.clone(),
3053            Some(map) => {
3054                let joint = match (site.also_target, site.also_enum_map) {
3055                    (Some(also), Some(also_map)) => {
3056                        Self::read_plain_string(entity, also).and_then(|also_v| {
3057                            map.iter()
3058                                .find(|(code, bo4e_v)| {
3059                                    *bo4e_v == &mapped_val && also_map.get(*code) == Some(&also_v)
3060                                })
3061                                .map(|(code, _)| code.clone())
3062                        })
3063                    }
3064                    _ => None,
3065                };
3066                joint
3067                    .or_else(|| {
3068                        map.iter()
3069                            .find(|(_, bo4e_v)| *bo4e_v == &mapped_val)
3070                            .map(|(code, _)| code.clone())
3071                    })
3072                    .unwrap_or_else(|| mapped_val.clone())
3073            }
3074        };
3075
3076        let Some(codes) = code_lookup.enrichment_codes(
3077            site.source_path,
3078            &site.seg_tag,
3079            site.path_qualifier.as_deref(),
3080            site.disc_qualifier.as_deref(),
3081            site.element_idx,
3082            site.component_idx,
3083        ) else {
3084            return;
3085        };
3086
3087        // Class C: PID self-reference stays a plain string.
3088        if let Some(ref pid) = self.current_pid {
3089            if codes.len() == 1 && codes.contains_key(pid.as_str()) {
3090                return;
3091            }
3092        }
3093
3094        let enrichment = codes.get(&raw);
3095        let meaning = enrichment
3096            .map(|e| serde_json::Value::String(e.meaning.clone()))
3097            .unwrap_or(serde_json::Value::Null);
3098
3099        let mut obj = serde_json::Map::new();
3100        obj.insert("code".into(), serde_json::json!(mapped_val));
3101        obj.insert("meaning".into(), meaning);
3102        if let Some(enum_key) = enrichment.and_then(|e| e.enum_key.as_ref()) {
3103            obj.insert("enum".into(), serde_json::json!(enum_key));
3104        }
3105
3106        if let serde_json::Value::Object(map) = entity {
3107            set_nested_value_json(map, site.target, serde_json::Value::Object(obj));
3108        }
3109    }
3110
3111    /// The string at a dotted target path, or `None` when it is absent or has
3112    /// already been replaced by an enrichment object.
3113    fn read_plain_string(entity: &serde_json::Value, target: &str) -> Option<String> {
3114        let mut current = entity;
3115        for part in target.split('.') {
3116            current = current.get(part)?;
3117        }
3118        current.as_str().map(str::to_string)
3119    }
3120
3121    /// Map an assembled tree into message-level and transaction-level results.
3122    ///
3123    /// - `msg_engine`: MappingEngine loaded with message-level definitions (SG2, SG3, root segments)
3124    /// - `tx_engine`: MappingEngine loaded with transaction-level definitions (relative to SG4)
3125    /// - `tree`: The assembled tree for one message
3126    /// - `transaction_group`: The group ID that represents transactions (e.g., "SG4")
3127    ///
3128    /// Returns a `MappedMessage` with message stammdaten and per-transaction results.
3129    pub fn map_interchange(
3130        msg_engine: &MappingEngine,
3131        tx_engine: &MappingEngine,
3132        tree: &AssembledTree,
3133        transaction_group: &str,
3134        enrich_codes: bool,
3135    ) -> crate::model::MappedMessage {
3136        let mut mapped =
3137            Self::translate_edifact_to_bo4e(msg_engine, tx_engine, tree, transaction_group);
3138        if enrich_codes {
3139            Self::enrich_bo4e_types(msg_engine, tx_engine, &mut mapped);
3140        }
3141        mapped
3142    }
3143
3144    /// The translation itself, with enrichment still inlined in the extraction.
3145    ///
3146    /// Retained so the split can be proven equivalent: `map_interchange_inner`
3147    /// with `enrich_codes = true` must produce exactly what
3148    /// `translate_edifact_to_bo4e` followed by `enrich_bo4e_types` produces.
3149    /// See `enrich_split_parity_test`.
3150    /// Test-only door onto the pre-split path, so the parity gate can compare
3151    /// the two. Not part of the public pipeline.
3152    #[doc(hidden)]
3153    pub fn map_interchange_inner_for_test(
3154        msg_engine: &MappingEngine,
3155        tx_engine: &MappingEngine,
3156        tree: &AssembledTree,
3157        transaction_group: &str,
3158        enrich_codes: bool,
3159    ) -> crate::model::MappedMessage {
3160        Self::map_interchange_inner(msg_engine, tx_engine, tree, transaction_group, enrich_codes)
3161    }
3162
3163    pub(crate) fn map_interchange_inner(
3164        msg_engine: &MappingEngine,
3165        tx_engine: &MappingEngine,
3166        tree: &AssembledTree,
3167        transaction_group: &str,
3168        enrich_codes: bool,
3169    ) -> crate::model::MappedMessage {
3170        // Map message-level entities (also captures nesting info)
3171        let (stammdaten, nesting_info) = msg_engine.map_all_forward_inner(tree, enrich_codes);
3172
3173        // Find the transaction group and map each repetition
3174        let transaktionen = tree
3175            .groups
3176            .iter()
3177            .find(|g| g.group_id == transaction_group)
3178            .map(|sg| {
3179                sg.repetitions
3180                    .iter()
3181                    .map(|instance| {
3182                        // Wrap the instance in its group so that definitions with
3183                        // source_group paths like "SG4.SG5" can resolve correctly.
3184                        let wrapped_tree = AssembledTree {
3185                            segments: vec![],
3186                            groups: vec![AssembledGroup {
3187                                group_id: transaction_group.to_string(),
3188                                repetitions: vec![instance.clone()],
3189                            }],
3190                            post_group_start: 0,
3191                            inter_group_segments: std::collections::BTreeMap::new(),
3192                        };
3193
3194                        // Pass the transaction_group into the tx_engine so its direct
3195                        // children (Marktlokation etc.) stay top-level peers of
3196                        // Prozessdaten rather than nested under it.
3197                        let (tx_result, tx_nesting) = tx_engine.map_all_forward_inner_with_tx(
3198                            &wrapped_tree,
3199                            enrich_codes,
3200                            Some(transaction_group),
3201                        );
3202
3203                        // Split the transaction's own metadata out of its
3204                        // business objects. The engine maps `Prozessdaten` like
3205                        // any other entity; it just does not belong among the
3206                        // BOs once mapped.
3207                        let mut tx_result = tx_result;
3208                        let transaktionsdaten = crate::model::take_entity(
3209                            &mut tx_result,
3210                            crate::model::TX_METADATA_ENTITY,
3211                        );
3212
3213                        crate::model::MappedTransaktion {
3214                            stammdaten: tx_result,
3215                            transaktionsdaten,
3216                            nesting_info: tx_nesting,
3217                        }
3218                    })
3219                    .collect()
3220            })
3221            .unwrap_or_default();
3222
3223        // Same split one level up: `Nachricht` is metadata about the message.
3224        let mut stammdaten = stammdaten;
3225        let nachricht_meta =
3226            crate::model::take_entity(&mut stammdaten, crate::model::MSG_METADATA_ENTITY);
3227
3228        crate::model::MappedMessage {
3229            stammdaten,
3230            nachricht_meta,
3231            transaktionen,
3232            nesting_info,
3233            inter_group_segments: tree.inter_group_segments.clone(),
3234        }
3235    }
3236
3237    /// Reverse-map a `MappedMessage` back to an `AssembledTree`.
3238    ///
3239    /// Two-engine approach mirroring `map_interchange()`:
3240    /// - `msg_engine` handles message-level stammdaten → SG2/SG3 groups
3241    /// - `tx_engine` handles per-transaction stammdaten → SG4 instances
3242    ///
3243    /// All entities (including prozessdaten/nachricht) are in `tx.stammdaten`.
3244    /// Results are merged into one `AssembledGroupInstance` per transaction,
3245    /// collected into an SG4 `AssembledGroup`, then combined with message-level groups.
3246    pub fn map_interchange_reverse(
3247        msg_engine: &MappingEngine,
3248        tx_engine: &MappingEngine,
3249        mapped: &crate::model::MappedMessage,
3250        transaction_group: &str,
3251        filtered_mig: Option<&MigSchema>,
3252    ) -> AssembledTree {
3253        // Step 1: Reverse message-level stammdaten.
3254        //
3255        // The message's metadata entity goes back in here first: the forward
3256        // pass split `Nachricht` out into its own slot, but the definitions
3257        // resolve against one flat entity map, so without this the BGM/DTM
3258        // segments it feeds cannot be rebuilt. Clone only when there is
3259        // metadata to restore — keeps the common path zero-copy.
3260        let _owned_msg: Option<serde_json::Value>;
3261        let msg_stammdaten = if !mapped.nachricht_meta.is_null() {
3262            let mut merged = mapped.stammdaten.clone();
3263            crate::model::restore_entity(
3264                &mut merged,
3265                crate::model::MSG_METADATA_ENTITY,
3266                &mapped.nachricht_meta,
3267            );
3268            _owned_msg = Some(merged);
3269            _owned_msg.as_ref().unwrap()
3270        } else {
3271            _owned_msg = None;
3272            &mapped.stammdaten
3273        };
3274
3275        let msg_tree = msg_engine.map_all_reverse_with_mig(
3276            msg_stammdaten,
3277            if mapped.nesting_info.is_empty() {
3278                None
3279            } else {
3280                Some(&mapped.nesting_info)
3281            },
3282            filtered_mig,
3283        );
3284
3285        // Step 2: Build transaction instances from each Transaktion
3286        let mut sg4_reps: Vec<AssembledGroupInstance> = Vec::new();
3287
3288        // Collect all definitions with their relative paths and sort by depth.
3289        // Shallower paths (SG8) must be processed before deeper ones (SG8:0.SG10)
3290        // so that parent group repetitions exist before children are added.
3291        struct DefWithMeta<'a> {
3292            def: &'a MappingDefinition,
3293            relative: String,
3294            depth: usize,
3295        }
3296
3297        let mut sorted_defs: Vec<DefWithMeta> = tx_engine
3298            .definitions
3299            .iter()
3300            // `parent_field` and bound children are reversed with their parent
3301            // object (see `reverse_nested_children`).
3302            .filter(|def| {
3303                def.meta.parent_field.is_none() && !is_bound_child(&tx_engine.definitions, def)
3304            })
3305            .map(|def| {
3306                let relative = strip_tx_group_prefix(&def.meta.source_group, transaction_group);
3307                let depth = if relative.is_empty() {
3308                    0
3309                } else {
3310                    relative.chars().filter(|c| *c == '.').count() + 1
3311                };
3312                DefWithMeta {
3313                    def,
3314                    relative,
3315                    depth,
3316                }
3317            })
3318            .collect();
3319
3320        // Build parent source_path → rep_index map from deeper definitions.
3321        // SG10 defs like "SG4.SG8:0.SG10" with source_path "sg4.sg8_z79.sg10"
3322        // tell us that the SG8 def with source_path "sg4.sg8_z79" should be rep 0.
3323        let mut parent_rep_map: std::collections::HashMap<String, usize> =
3324            std::collections::HashMap::new();
3325        for dm in &sorted_defs {
3326            if dm.depth >= 2 {
3327                let parts: Vec<&str> = dm.relative.split('.').collect();
3328                let (_, parent_rep) = parse_group_spec(parts[0]);
3329                if let Some(rep_idx) = parent_rep {
3330                    if let Some(sp) = &dm.def.meta.source_path {
3331                        if let Some((parent_path, _)) = sp.rsplit_once('.') {
3332                            parent_rep_map
3333                                .entry(parent_path.to_string())
3334                                .or_insert(rep_idx);
3335                        }
3336                    }
3337                }
3338            }
3339        }
3340
3341        // Augment shallow definitions with explicit rep indices from the map,
3342        // but only for single-rep cases (no multi-rep — those use dynamic tracking).
3343        for dm in &mut sorted_defs {
3344            if dm.depth == 1 && !dm.relative.contains(':') {
3345                if let Some(sp) = &dm.def.meta.source_path {
3346                    if let Some(rep_idx) = parent_rep_map.get(sp.as_str()) {
3347                        dm.relative = format!("{}:{}", dm.relative, rep_idx);
3348                    }
3349                }
3350            }
3351        }
3352
3353        // Sort: shallower depth first, so SG8 defs create reps before SG8:N.SG10 defs.
3354        // Within same depth, sort by MIG group position (if available) for correct emission order,
3355        // falling back to alphabetical relative path for deterministic ordering.
3356        //
3357        // For variant groups (SG8 with Z01/Z03/Z07 etc.), use per-variant MIG positions
3358        // extracted from each definition's source_path qualifier suffix (e.g., "sg4.sg8_z01" → "Z01").
3359        if let Some(mig) = filtered_mig {
3360            let mig_order = build_reverse_mig_group_order(mig, transaction_group);
3361            sorted_defs.sort_by(|a, b| {
3362                a.depth.cmp(&b.depth).then_with(|| {
3363                    let a_id = a.relative.split(':').next().unwrap_or(&a.relative);
3364                    let b_id = b.relative.split(':').next().unwrap_or(&b.relative);
3365                    // Try per-variant lookup from source_path (e.g., "sg4.sg8_z01" → "SG8_Z01")
3366                    let a_pos = variant_mig_position(a.def, a_id, &mig_order);
3367                    let b_pos = variant_mig_position(b.def, b_id, &mig_order);
3368                    a_pos.cmp(&b_pos).then(a.relative.cmp(&b.relative))
3369                })
3370            });
3371        } else {
3372            sorted_defs.sort_by(|a, b| a.depth.cmp(&b.depth).then(a.relative.cmp(&b.relative)));
3373        }
3374
3375        for tx in &mapped.transaktionen {
3376            let mut root_segs: Vec<AssembledSegment> = Vec::new();
3377            let mut child_groups: Vec<AssembledGroup> = Vec::new();
3378
3379            // `transaktionsdaten` is merged back for the same reason as the
3380            // message's metadata above — the definitions expect one flat map.
3381            let _owned_tx: Option<serde_json::Value>;
3382            let tx_stammdaten: &serde_json::Value = if !tx.transaktionsdaten.is_null() {
3383                let mut merged = tx.stammdaten.clone();
3384                crate::model::restore_entity(
3385                    &mut merged,
3386                    crate::model::TX_METADATA_ENTITY,
3387                    &tx.transaktionsdaten,
3388                );
3389                _owned_tx = Some(merged);
3390                _owned_tx.as_ref().unwrap()
3391            } else {
3392                _owned_tx = None;
3393                &tx.stammdaten
3394            };
3395
3396            // Track source_path → repetition indices for parent groups (top-down).
3397            // Built during depth-1 processing, used by depth-2+ defs without
3398            // explicit rep indices to find their correct parent via source_path.
3399            // Vec<usize> supports multi-rep parents (e.g., two SG8+ZF3 reps).
3400            let mut source_path_to_rep: std::collections::HashMap<String, Vec<usize>> =
3401                std::collections::HashMap::new();
3402
3403            for dm in &sorted_defs {
3404                // Determine the BO4E value to reverse-map from.
3405                // Check top level first, then nested under parent entity.
3406                let entity_key = to_camel_case(&dm.def.meta.entity);
3407                let _tx_extracted: Option<serde_json::Value>;
3408                let bo4e_value = if let Some(v) = tx_stammdaten.get(&entity_key) {
3409                    _tx_extracted = None;
3410                    v
3411                } else if dm.def.meta.source_group.contains('.') {
3412                    match extract_child_from_parent(tx_stammdaten, &tx_engine.definitions, dm.def) {
3413                        Some(v) => {
3414                            _tx_extracted = Some(v);
3415                            _tx_extracted.as_ref().unwrap()
3416                        }
3417                        None => continue,
3418                    }
3419                } else {
3420                    continue;
3421                };
3422
3423                // Support map-keyed entities from typed PID format (same logic as map_all_reverse).
3424                let unwrapped_value: Option<serde_json::Value>;
3425                let bo4e_value = if bo4e_value.is_object() && !bo4e_value.is_array() {
3426                    if let Some(disc_value) = dm
3427                        .def
3428                        .meta
3429                        .discriminator
3430                        .as_deref()
3431                        .and_then(|d| d.split_once('='))
3432                        .map(|(_, v)| v)
3433                    {
3434                        if let Some(inner) = bo4e_value.get(disc_value) {
3435                            let mut injected = inner.clone();
3436                            if let Some(qualifier_field) = find_qualifier_companion_field(
3437                                &tx_engine.definitions,
3438                                &dm.def.meta.entity,
3439                            ) {
3440                                if let Some(obj) = injected.as_object_mut() {
3441                                    obj.entry(qualifier_field).or_insert_with(|| {
3442                                        serde_json::Value::String(disc_value.to_string())
3443                                    });
3444                                }
3445                            }
3446                            unwrapped_value = Some(injected);
3447                            unwrapped_value.as_ref().unwrap()
3448                        } else {
3449                            bo4e_value
3450                        }
3451                    } else if is_map_keyed_object(bo4e_value) {
3452                        let map = bo4e_value.as_object().unwrap();
3453                        let arr: Vec<serde_json::Value> = map
3454                            .iter()
3455                            .map(|(key, val)| {
3456                                let mut item = val.clone();
3457                                if let Some(obj) = item.as_object_mut() {
3458                                    if let Some(qualifier_field) = find_qualifier_companion_field(
3459                                        &tx_engine.definitions,
3460                                        &dm.def.meta.entity,
3461                                    ) {
3462                                        let entry = obj
3463                                            .entry(qualifier_field)
3464                                            .or_insert(serde_json::Value::Null);
3465                                        if entry.is_null() {
3466                                            *entry = serde_json::Value::String(key.clone());
3467                                        }
3468                                    }
3469                                }
3470                                item
3471                            })
3472                            .collect();
3473                        unwrapped_value = Some(serde_json::Value::Array(arr));
3474                        unwrapped_value.as_ref().unwrap()
3475                    } else {
3476                        bo4e_value
3477                    }
3478                } else {
3479                    bo4e_value
3480                };
3481
3482                // Handle array entities: each element becomes a separate group rep.
3483                // This supports both the NAD/SG12 pattern (multiple qualifiers) and
3484                // the multi-rep pattern (e.g., two LOC+Z17 Messlokationen).
3485                let items: Vec<&serde_json::Value> = if bo4e_value.is_array() {
3486                    bo4e_value.as_array().unwrap().iter().collect()
3487                } else {
3488                    vec![bo4e_value]
3489                };
3490
3491                for (item_idx, item) in items.iter().enumerate() {
3492                    let instance = tx_engine.map_reverse(item, dm.def);
3493
3494                    // Skip empty instances (definition had no real BO4E data)
3495                    if instance.segments.is_empty() && instance.child_groups.is_empty() {
3496                        continue;
3497                    }
3498
3499                    if dm.relative.is_empty() {
3500                        // The definition maps the transaction group itself
3501                        // (CONTRL's SG1, UTILMD's SG4): its segments are the
3502                        // instance's own root segments. Children it nested with
3503                        // `parent_field` (CONTRL SG1.SG2, the UCS/UCD errors of
3504                        // this checked message) are already built as child
3505                        // groups of that instance and must travel with it.
3506                        root_segs.extend(instance.segments);
3507                        for child in instance.child_groups {
3508                            match child_groups
3509                                .iter_mut()
3510                                .find(|g| g.group_id == child.group_id)
3511                            {
3512                                Some(existing) => existing.repetitions.extend(child.repetitions),
3513                                None => child_groups.push(child),
3514                            }
3515                        }
3516                    } else {
3517                        // For depth-2+ defs without explicit rep index, resolve
3518                        // parent rep from source_path matching (qualifier-based).
3519                        // item_idx selects the correct parent rep for multi-rep entities.
3520                        let effective_relative = if dm.depth >= 2 {
3521                            // Multi-rep: strip hardcoded parent :N indices so
3522                            // resolve_child_relative uses source_path lookup instead.
3523                            let rel = if items.len() > 1 {
3524                                strip_all_rep_indices(&dm.relative)
3525                            } else {
3526                                dm.relative.clone()
3527                            };
3528                            // Use tx nesting info for multi-rep arrays, BUT skip it
3529                            // when source_path is present and resolves to a single
3530                            // parent rep. In that case, nesting_info indices (from the
3531                            // original tree) may not match the reverse tree's rep layout.
3532                            // resolve_child_relative uses reverse-tree source_path_to_rep
3533                            // which is always correct.
3534                            let skip_nesting = dm
3535                                .def
3536                                .meta
3537                                .source_path
3538                                .as_ref()
3539                                .and_then(|sp| sp.rsplit_once('.'))
3540                                .and_then(|(parent_path, _)| source_path_to_rep.get(parent_path))
3541                                .is_some_and(|reps| reps.len() == 1);
3542                            let nesting_idx = if items.len() > 1 && !skip_nesting {
3543                                dm.def
3544                                    .meta
3545                                    .source_path
3546                                    .as_ref()
3547                                    .and_then(|sp| tx.nesting_info.get(sp))
3548                                    .and_then(|dist| dist.get(item_idx))
3549                                    .copied()
3550                            } else {
3551                                None
3552                            };
3553                            if let Some(parent_rep) = nesting_idx {
3554                                // Direct placement using known nesting distribution
3555                                let parts: Vec<&str> = rel.split('.').collect();
3556                                let parent_id = parts[0].split(':').next().unwrap_or(parts[0]);
3557                                let rest = parts[1..].join(".");
3558                                format!("{}:{}.{}", parent_id, parent_rep, rest)
3559                            } else {
3560                                resolve_child_relative(
3561                                    &rel,
3562                                    dm.def.meta.source_path.as_deref(),
3563                                    &source_path_to_rep,
3564                                    item_idx,
3565                                )
3566                            }
3567                        } else if dm.depth == 1 {
3568                            // Depth-1: use nesting_info child indices for correct
3569                            // rep placement (preserves original interleaving order).
3570                            let child_key = dm
3571                                .def
3572                                .meta
3573                                .source_path
3574                                .as_ref()
3575                                .map(|sp| format!("{sp}#child"));
3576                            if let Some(child_indices) =
3577                                child_key.as_ref().and_then(|ck| tx.nesting_info.get(ck))
3578                            {
3579                                if let Some(&target) = child_indices.get(item_idx) {
3580                                    if target != usize::MAX {
3581                                        let base =
3582                                            dm.relative.split(':').next().unwrap_or(&dm.relative);
3583                                        format!("{}:{}", base, target)
3584                                    } else {
3585                                        dm.relative.clone()
3586                                    }
3587                                } else if items.len() > 1 && item_idx > 0 {
3588                                    strip_rep_index(&dm.relative)
3589                                } else {
3590                                    dm.relative.clone()
3591                                }
3592                            } else if items.len() > 1 && item_idx > 0 {
3593                                strip_rep_index(&dm.relative)
3594                            } else {
3595                                dm.relative.clone()
3596                            }
3597                        } else if items.len() > 1 && item_idx > 0 {
3598                            // Multi-rep entity with hardcoded :N index: first item uses
3599                            // the original index, subsequent items append (strip :N).
3600                            strip_rep_index(&dm.relative)
3601                        } else {
3602                            dm.relative.clone()
3603                        };
3604
3605                        let rep_used =
3606                            place_in_groups(&mut child_groups, &effective_relative, instance);
3607
3608                        // Track source_path → rep_index for depth-1 (parent) defs
3609                        if dm.depth == 1 {
3610                            if let Some(sp) = &dm.def.meta.source_path {
3611                                source_path_to_rep
3612                                    .entry(sp.clone())
3613                                    .or_default()
3614                                    .push(rep_used);
3615                            }
3616                        }
3617                    }
3618                }
3619            }
3620
3621            sg4_reps.push(AssembledGroupInstance {
3622                segments: root_segs,
3623                child_groups,
3624                entry_mig_number: None,
3625                variant_mig_numbers: vec![],
3626                skipped_segments: Vec::new(),
3627                skipped_positions: Vec::new(),
3628            });
3629        }
3630
3631        // Step 3: Combine message tree with transaction group.
3632        // Move UNS section separator from root segments to inter_group_segments.
3633        // UNS+D (detail) goes BEFORE the tx group (MSCONS: header/detail boundary).
3634        // UNS+S (summary) goes AFTER the tx group (ORDERS: detail/summary boundary).
3635        // Any segments that follow UNS in the sequence (e.g., summary MOA in REMADV)
3636        // are also placed in inter_group_segments alongside UNS.
3637        let mut root_segments = Vec::new();
3638        let mut uns_segments = Vec::new();
3639        let mut uns_is_summary = false;
3640        let mut found_uns = false;
3641        for seg in msg_tree.segments {
3642            if seg.tag == "UNS" {
3643                // Check if this is UNS+S (summary separator) vs UNS+D (detail separator)
3644                uns_is_summary = seg
3645                    .elements
3646                    .first()
3647                    .and_then(|el| el.first())
3648                    .map(|v| v == "S")
3649                    .unwrap_or(false);
3650                uns_segments.push(seg);
3651                found_uns = true;
3652            } else if found_uns {
3653                // Segments after UNS belong in the same inter_group position
3654                uns_segments.push(seg);
3655            } else {
3656                root_segments.push(seg);
3657            }
3658        }
3659
3660        let pre_group_count = root_segments.len();
3661        let mut all_groups = msg_tree.groups;
3662        let mut inter_group = msg_tree.inter_group_segments;
3663
3664        // Helper: parse SG number from group_id (e.g., "SG26" → 26).
3665        let sg_num = |id: &str| -> usize {
3666            id.strip_prefix("SG")
3667                .and_then(|n| n.parse::<usize>().ok())
3668                .unwrap_or(0)
3669        };
3670
3671        if !sg4_reps.is_empty() {
3672            if uns_is_summary {
3673                // UNS+S: place AFTER the transaction group (detail/summary boundary)
3674                all_groups.push(AssembledGroup {
3675                    group_id: transaction_group.to_string(),
3676                    repetitions: sg4_reps,
3677                });
3678                if !uns_segments.is_empty() {
3679                    // Sort groups by SG number so the disassembler emits them
3680                    // in MIG order.  Insert UNS right after the tx_group —
3681                    // any groups with higher SG numbers (e.g., SG50/SG52 in
3682                    // INVOIC) are post-UNS summary groups.
3683                    all_groups.sort_by_key(|g| sg_num(&g.group_id));
3684                    let tx_num = sg_num(transaction_group);
3685                    let uns_pos = all_groups
3686                        .iter()
3687                        .rposition(|g| sg_num(&g.group_id) <= tx_num)
3688                        .map(|i| i + 1)
3689                        .unwrap_or(all_groups.len());
3690                    inter_group.insert(uns_pos, uns_segments);
3691                }
3692            } else {
3693                // UNS+D: place BEFORE the transaction group (header/detail boundary)
3694                if !uns_segments.is_empty() {
3695                    inter_group.insert(all_groups.len(), uns_segments);
3696                }
3697                all_groups.push(AssembledGroup {
3698                    group_id: transaction_group.to_string(),
3699                    repetitions: sg4_reps,
3700                });
3701            }
3702        } else if !uns_segments.is_empty() {
3703            if transaction_group.is_empty() {
3704                // Truly message-only (tx_group=""): UNS is a section separator.
3705                // UNS+S (summary) goes AFTER all groups — e.g., ORDCHG UNS+S
3706                // follows SG1 (NAD+CTA+COM) groups.
3707                // UNS+D (detail) goes BEFORE groups.
3708                all_groups.sort_by_key(|g| sg_num(&g.group_id));
3709                if uns_is_summary {
3710                    inter_group.insert(all_groups.len(), uns_segments);
3711                } else {
3712                    inter_group.insert(0, uns_segments);
3713                }
3714            } else {
3715                // Has a tx_group but no tx reps (e.g., INVOIC PID 31004
3716                // Storno — no SG26 data).  Sort groups and insert UNS after
3717                // the last group with SG number ≤ tx_group number.
3718                all_groups.sort_by_key(|g| sg_num(&g.group_id));
3719                let tx_num = sg_num(transaction_group);
3720                let uns_pos = all_groups
3721                    .iter()
3722                    .rposition(|g| sg_num(&g.group_id) <= tx_num)
3723                    .map(|i| i + 1)
3724                    .unwrap_or(all_groups.len());
3725                inter_group.insert(uns_pos, uns_segments);
3726            }
3727        }
3728
3729        // Restore inter_group_segments captured during forward mapping
3730        // (e.g. PID-foreign top-level segments preserved by the assembler's
3731        // skip-unknown mode — see `Assembler::assemble_generic`). Without
3732        // this, BO4E forward + reverse drops anything not represented in a
3733        // TOML mapping definition. We append rather than overwrite so the
3734        // UNS placement computed above survives — same-key collisions are
3735        // rare in practice (UNS goes at well-known positions).
3736        for (k, segs) in &mapped.inter_group_segments {
3737            if segs.is_empty() {
3738                continue;
3739            }
3740            let existing_tags: std::collections::HashSet<String> = inter_group
3741                .get(k)
3742                .map(|v| v.iter().map(|s| s.tag.clone()).collect())
3743                .unwrap_or_default();
3744            for seg in segs {
3745                if existing_tags.contains(&seg.tag) {
3746                    continue;
3747                }
3748                inter_group.entry(*k).or_default().push(seg.clone());
3749            }
3750        }
3751
3752        let mut tree = AssembledTree {
3753            segments: root_segments,
3754            groups: all_groups,
3755            post_group_start: pre_group_count,
3756            inter_group_segments: inter_group,
3757        };
3758
3759        // Order repetitions of same-ID group variants (SG2 NAD+MS / NAD+MR,
3760        // SG12 NAD+Z07 / NAD+Z08, SG10 CCI variants, …) by MIG variant order.
3761        // The reps above were appended in definition order and, within one
3762        // definition, in the order of the BO4E JSON array — which carries no
3763        // ordering information. The transaction group itself keeps its order:
3764        // the order of transactions is data.
3765        if let Some(mig) = filtered_mig {
3766            mig_assembly::repetition_order::sort_repetitions_by_mig_variant(
3767                &mut tree,
3768                mig,
3769                (!transaction_group.is_empty()).then_some(transaction_group),
3770            );
3771        }
3772        tree
3773    }
3774
3775    /// Build an assembled group from BO4E values and a definition.
3776    pub fn build_group_from_bo4e(
3777        &self,
3778        bo4e_value: &serde_json::Value,
3779        def: &MappingDefinition,
3780    ) -> AssembledGroup {
3781        let instance = self.map_reverse(bo4e_value, def);
3782        let leaf_group = def
3783            .meta
3784            .source_group
3785            .rsplit('.')
3786            .next()
3787            .unwrap_or(&def.meta.source_group);
3788
3789        AssembledGroup {
3790            group_id: leaf_group.to_string(),
3791            repetitions: vec![instance],
3792        }
3793    }
3794
3795    /// Forward-map an assembled tree to a typed interchange.
3796    ///
3797    /// Runs the dynamic mapping pipeline, wraps the result with metadata,
3798    /// then converts via JSON serialization into the caller's typed structs.
3799    ///
3800    /// - `M`: message-level stammdaten type (e.g., `Pid55001MsgStammdaten`)
3801    /// - `T`: transaction-level stammdaten type (e.g., `Pid55001TxStammdaten`)
3802    pub fn map_interchange_typed<M, T>(
3803        msg_engine: &MappingEngine,
3804        tx_engine: &MappingEngine,
3805        tree: &AssembledTree,
3806        tx_group: &str,
3807        enrich_codes: bool,
3808        nachrichtendaten: crate::model::Nachrichtendaten,
3809        interchangedaten: crate::model::Interchangedaten,
3810    ) -> Result<crate::model::Interchange<M, T>, serde_json::Error>
3811    where
3812        M: serde::de::DeserializeOwned,
3813        T: serde::de::DeserializeOwned,
3814    {
3815        let mapped = Self::map_interchange(msg_engine, tx_engine, tree, tx_group, enrich_codes);
3816        let nachricht = mapped.into_dynamic_nachricht(nachrichtendaten);
3817        let dynamic = crate::model::DynamicInterchange {
3818            interchangedaten,
3819            nachrichten: vec![nachricht],
3820        };
3821        let value = serde_json::to_value(&dynamic)?;
3822        serde_json::from_value(value)
3823    }
3824
3825    /// Reverse-map a typed interchange nachricht back to an assembled tree.
3826    ///
3827    /// Serializes the typed struct to JSON, then runs the dynamic reverse pipeline.
3828    ///
3829    /// - `M`: message-level stammdaten type
3830    /// - `T`: transaction-level stammdaten type
3831    pub fn map_interchange_reverse_typed<M, T>(
3832        msg_engine: &MappingEngine,
3833        tx_engine: &MappingEngine,
3834        nachricht: &crate::model::Nachricht<M, T>,
3835        tx_group: &str,
3836    ) -> Result<AssembledTree, serde_json::Error>
3837    where
3838        M: serde::Serialize,
3839        T: serde::Serialize,
3840    {
3841        // The reverse resolves definitions against one flat entity map, so both
3842        // metadata slots go back where the mappings expect to find them.
3843        let mut stammdaten = serde_json::to_value(&nachricht.stammdaten)?;
3844        crate::model::restore_message_metadata(&mut stammdaten, &nachricht.nachrichtendaten);
3845        let transaktionen: Vec<crate::model::MappedTransaktion> = nachricht
3846            .transaktionen
3847            .iter()
3848            .map(|t| {
3849                Ok(crate::model::MappedTransaktion {
3850                    stammdaten: serde_json::to_value(t)?,
3851                    transaktionsdaten: serde_json::Value::Null,
3852                    nesting_info: Default::default(),
3853                })
3854            })
3855            .collect::<Result<Vec<_>, serde_json::Error>>()?;
3856        let mapped = crate::model::MappedMessage {
3857            stammdaten,
3858            nachricht_meta: serde_json::Value::Null,
3859            transaktionen,
3860            nesting_info: Default::default(),
3861            inter_group_segments: Default::default(),
3862        };
3863        Ok(Self::map_interchange_reverse(
3864            msg_engine, tx_engine, &mapped, tx_group, None,
3865        ))
3866    }
3867}
3868
3869/// Parse a group path part with optional repetition: "SG8:1" → ("SG8", Some(1)).
3870/// Parse a source_path part into (group_id, optional_qualifier).
3871///
3872/// `"sg8_z98"` → `("sg8", Some("z98"))`
3873/// `"sg4"` → `("sg4", None)`
3874/// `"sg10"` → `("sg10", None)`
3875fn parse_source_path_part(part: &str) -> (&str, Option<&str>) {
3876    // Find the first underscore that separates group from qualifier.
3877    // Source path parts look like "sg8_z98", "sg4", "sg10", "sg12_z04".
3878    // The group ID is always "sgN", so the underscore after the digits is the separator.
3879    if let Some(pos) = part.find('_') {
3880        let group = &part[..pos];
3881        let qualifier = &part[pos + 1..];
3882        if !qualifier.is_empty() {
3883            return (group, Some(qualifier));
3884        }
3885    }
3886    (part, None)
3887}
3888
3889/// Build a map from group ID (e.g., "SG5", "SG8") to its position index
3890/// within the transaction group's nested_groups Vec.
3891/// Used by `map_interchange_reverse` to sort definitions in MIG order.
3892///
3893/// For variant groups (same ID with variant_code set, e.g., SG8 with Z01, Z03, Z07),
3894/// stores per-variant positions (e.g., "SG8_Z01" → 0, "SG8_Z03" → 1) so that
3895/// definitions are sorted in MIG XML order rather than alphabetical qualifier order.
3896fn build_reverse_mig_group_order(mig: &MigSchema, tx_group_id: &str) -> HashMap<String, usize> {
3897    let mut order = HashMap::new();
3898    if let Some(tg) = mig.segment_groups.iter().find(|g| g.id == tx_group_id) {
3899        for (i, nested) in tg.nested_groups.iter().enumerate() {
3900            // For variant groups, store per-variant key (e.g., "SG8_Z01" → i)
3901            if let Some(ref vc) = nested.variant_code {
3902                let variant_key = format!("{}_{}", nested.id, vc.to_uppercase());
3903                order.insert(variant_key, i);
3904            }
3905            // Always store base group ID for fallback
3906            order.entry(nested.id.clone()).or_insert(i);
3907        }
3908    }
3909    order
3910}
3911
3912/// Extract the MIG position for a definition, using per-variant lookup when possible.
3913///
3914/// For a definition with source_path "sg4.sg8_z01", extracts the variant qualifier "Z01"
3915/// and looks up "SG8_Z01" in the MIG order map. Falls back to the base group ID (e.g., "SG8")
3916/// if no variant qualifier is found or if the per-variant key isn't in the map.
3917fn variant_mig_position(
3918    def: &MappingDefinition,
3919    base_group_id: &str,
3920    mig_order: &HashMap<String, usize>,
3921) -> usize {
3922    // Try to extract variant qualifier from source_path.
3923    // source_path like "sg4.sg8_z01" or "sg4.sg8_z01.sg10" — we want the part matching base_group_id.
3924    if let Some(ref sp) = def.meta.source_path {
3925        // Find the path segment matching the base group (e.g., "sg8_z01" for base "SG8")
3926        let base_lower = base_group_id.to_lowercase();
3927        for part in sp.split('.') {
3928            if part.starts_with(&base_lower)
3929                || part.starts_with(base_group_id.to_lowercase().as_str())
3930            {
3931                // Extract qualifier suffix: "sg8_z01" → "z01"
3932                if let Some(underscore_pos) = part.find('_') {
3933                    let qualifier = &part[underscore_pos + 1..];
3934                    let variant_key = format!("{}_{}", base_group_id, qualifier.to_uppercase());
3935                    if let Some(&pos) = mig_order.get(&variant_key) {
3936                        return pos;
3937                    }
3938                }
3939            }
3940        }
3941    }
3942    // Fallback to base group position
3943    mig_order.get(base_group_id).copied().unwrap_or(usize::MAX)
3944}
3945
3946/// Find a group repetition whose entry segment has a matching qualifier.
3947///
3948/// The entry segment is the first segment in the instance (e.g., SEQ for SG8).
3949/// The qualifier is matched against `elements[0][0]` (case-insensitive).
3950fn find_rep_by_entry_qualifier<'a>(
3951    reps: &'a [AssembledGroupInstance],
3952    qualifier: &str,
3953) -> Option<&'a AssembledGroupInstance> {
3954    // Support compound qualifiers like "za1_za2" — match any part.
3955    let parts: Vec<&str> = qualifier.split('_').collect();
3956    reps.iter().find(|inst| {
3957        inst.segments.first().is_some_and(|seg| {
3958            seg.elements
3959                .first()
3960                .and_then(|e| e.first())
3961                .is_some_and(|v| parts.iter().any(|part| v.eq_ignore_ascii_case(part)))
3962        })
3963    })
3964}
3965
3966/// Find ALL repetitions whose entry segment qualifier matches (case-insensitive).
3967fn find_all_reps_by_entry_qualifier<'a>(
3968    reps: &'a [AssembledGroupInstance],
3969    qualifier: &str,
3970) -> Vec<&'a AssembledGroupInstance> {
3971    // Support compound qualifiers like "za1_za2" — match any part.
3972    let parts: Vec<&str> = qualifier.split('_').collect();
3973    reps.iter()
3974        .filter(|inst| {
3975            inst.segments.first().is_some_and(|seg| {
3976                seg.elements
3977                    .first()
3978                    .and_then(|e| e.first())
3979                    .is_some_and(|v| parts.iter().any(|part| v.eq_ignore_ascii_case(part)))
3980            })
3981        })
3982        .collect()
3983}
3984
3985/// Check if a source_path contains qualifier suffixes (e.g., "sg8_z98").
3986fn has_source_path_qualifiers(source_path: &str) -> bool {
3987    source_path.split('.').any(|part| {
3988        if let Some(pos) = part.find('_') {
3989            pos < part.len() - 1
3990        } else {
3991            false
3992        }
3993    })
3994}
3995
3996fn parse_group_spec(part: &str) -> (&str, Option<usize>) {
3997    if let Some(colon_pos) = part.find(':') {
3998        let id = &part[..colon_pos];
3999        let rep = part[colon_pos + 1..].parse::<usize>().ok();
4000        (id, rep)
4001    } else {
4002        (part, None)
4003    }
4004}
4005
4006/// Strip the transaction group prefix from a source_group path.
4007///
4008/// Given `source_group = "SG4.SG8:0.SG10"` and `tx_group = "SG4"`,
4009/// returns `"SG8:0.SG10"`.
4010/// Given `source_group = "SG4"` and `tx_group = "SG4"`, returns `""`.
4011fn strip_tx_group_prefix(source_group: &str, tx_group: &str) -> String {
4012    if source_group == tx_group || source_group.is_empty() {
4013        String::new()
4014    } else if let Some(rest) = source_group.strip_prefix(tx_group) {
4015        rest.strip_prefix('.').unwrap_or(rest).to_string()
4016    } else {
4017        source_group.to_string()
4018    }
4019}
4020
4021/// Place a reverse-mapped group instance into the correct nesting position.
4022///
4023/// `relative_path` is the group path relative to the transaction group:
4024/// - `"SG5"` → top-level child group
4025/// - `"SG8:0.SG10"` → SG10 inside SG8 repetition 0
4026///
4027/// Returns the repetition index used at the first nesting level.
4028fn place_in_groups(
4029    groups: &mut Vec<AssembledGroup>,
4030    relative_path: &str,
4031    instance: AssembledGroupInstance,
4032) -> usize {
4033    let parts: Vec<&str> = relative_path.split('.').collect();
4034
4035    if parts.len() == 1 {
4036        // Leaf group: "SG5", "SG8", "SG12", or with explicit index "SG8:0"
4037        let (id, rep) = parse_group_spec(parts[0]);
4038
4039        // Find or create the group
4040        let group = if let Some(g) = groups.iter_mut().find(|g| g.group_id == id) {
4041            g
4042        } else {
4043            groups.push(AssembledGroup {
4044                group_id: id.to_string(),
4045                repetitions: vec![],
4046            });
4047            groups.last_mut().unwrap()
4048        };
4049
4050        if let Some(rep_idx) = rep {
4051            // Explicit index: place at specific position, merging into existing
4052            while group.repetitions.len() <= rep_idx {
4053                group.repetitions.push(AssembledGroupInstance {
4054                    segments: vec![],
4055                    child_groups: vec![],
4056                    entry_mig_number: None,
4057                    variant_mig_numbers: vec![],
4058                    skipped_segments: Vec::new(),
4059                    skipped_positions: Vec::new(),
4060                });
4061            }
4062            group.repetitions[rep_idx]
4063                .segments
4064                .extend(instance.segments);
4065            group.repetitions[rep_idx]
4066                .child_groups
4067                .extend(instance.child_groups);
4068            rep_idx
4069        } else {
4070            // No index: append new repetition
4071            let pos = group.repetitions.len();
4072            group.repetitions.push(instance);
4073            pos
4074        }
4075    } else {
4076        // Nested path: e.g., "SG8:0.SG10" → place SG10 inside SG8 rep 0
4077        let (parent_id, parent_rep) = parse_group_spec(parts[0]);
4078        let rep_idx = parent_rep.unwrap_or(0);
4079
4080        // Find or create the parent group
4081        let parent_group = if let Some(g) = groups.iter_mut().find(|g| g.group_id == parent_id) {
4082            g
4083        } else {
4084            groups.push(AssembledGroup {
4085                group_id: parent_id.to_string(),
4086                repetitions: vec![],
4087            });
4088            groups.last_mut().unwrap()
4089        };
4090
4091        // Ensure the target repetition exists (extend with empty instances if needed)
4092        while parent_group.repetitions.len() <= rep_idx {
4093            parent_group.repetitions.push(AssembledGroupInstance {
4094                segments: vec![],
4095                child_groups: vec![],
4096                entry_mig_number: None,
4097                variant_mig_numbers: vec![],
4098                skipped_segments: Vec::new(),
4099                skipped_positions: Vec::new(),
4100            });
4101        }
4102
4103        let remaining = parts[1..].join(".");
4104        place_in_groups(
4105            &mut parent_group.repetitions[rep_idx].child_groups,
4106            &remaining,
4107            instance,
4108        );
4109        rep_idx
4110    }
4111}
4112
4113/// Resolve the effective relative path for a child definition (depth >= 2).
4114///
4115/// If the child's relative already has an explicit parent rep index (e.g., "SG8:5.SG10"),
4116/// use it as-is. Otherwise, use the `source_path` to look up the parent's actual
4117/// repetition index from `source_path_to_rep`.
4118///
4119/// `item_idx` selects which parent rep to use when the parent created multiple reps
4120/// (e.g., two SG8 reps with ZF3 → item_idx 0 picks the first, 1 picks the second).
4121///
4122/// Example: relative = "SG8.SG10", source_path = "sg4.sg8_zf3.sg10"
4123/// → looks up "sg4.sg8_zf3" in map → finds reps [3, 4] → item_idx=1 → returns "SG8:4.SG10"
4124fn resolve_child_relative(
4125    relative: &str,
4126    source_path: Option<&str>,
4127    source_path_to_rep: &std::collections::HashMap<String, Vec<usize>>,
4128    item_idx: usize,
4129) -> String {
4130    let parts: Vec<&str> = relative.split('.').collect();
4131    if parts.is_empty() {
4132        return relative.to_string();
4133    }
4134
4135    // If first part already has explicit index, keep as-is
4136    let (parent_id, parent_rep) = parse_group_spec(parts[0]);
4137    if parent_rep.is_some() {
4138        return relative.to_string();
4139    }
4140
4141    // Try to resolve from source_path: extract parent path and look up its rep
4142    if let Some(sp) = source_path {
4143        if let Some((parent_path, _child)) = sp.rsplit_once('.') {
4144            // Exact match first.
4145            if let Some(rep_indices) = source_path_to_rep.get(parent_path) {
4146                let rep_idx = rep_indices
4147                    .get(item_idx)
4148                    .or_else(|| rep_indices.last())
4149                    .copied()
4150                    .unwrap_or(0);
4151                let rest = parts[1..].join(".");
4152                return format!("{}:{}.{}", parent_id, rep_idx, rest);
4153            }
4154            // Fallback: variant wildcard. When TOMLs use a flat parent path
4155            // like "sg4" but the schema splits it into variants (e.g. sg4_su,
4156            // sg4_z10..z21), union the reps from every matching variant so a
4157            // per-item iteration can place each child under its own parent.
4158            // `PidSchemaIndex::has_group` already accepts this style for
4159            // forward mapping — reverse mapping needs the same or children
4160            // from all-but-one variant get dropped (PARTIN 12 SG4 reps).
4161            let prefix = format!("{}_", parent_path);
4162            let mut unioned: Vec<usize> = source_path_to_rep
4163                .iter()
4164                .filter(|(k, _)| k.starts_with(&prefix))
4165                .flat_map(|(_, v)| v.iter().copied())
4166                .collect();
4167            if !unioned.is_empty() {
4168                unioned.sort_unstable();
4169                unioned.dedup();
4170                let rep_idx = unioned
4171                    .get(item_idx)
4172                    .or_else(|| unioned.last())
4173                    .copied()
4174                    .unwrap_or(0);
4175                let rest = parts[1..].join(".");
4176                return format!("{}:{}.{}", parent_id, rep_idx, rest);
4177            }
4178        }
4179    }
4180
4181    // No resolution possible, keep original
4182    relative.to_string()
4183}
4184
4185/// Parsed discriminator for filtering assembled group instances.
4186///
4187/// Discriminator format: "TAG.element_idx.component_idx=VALUE" or
4188/// "TAG.element_idx.component_idx=VAL1|VAL2" (pipe-separated multi-value).
4189/// E.g., "LOC.0.0=Z17" → match LOC segments where elements[0][0] == "Z17"
4190/// E.g., "RFF.0.0=Z49|Z53" → match RFF where elements[0][0] is Z49 OR Z53
4191struct DiscriminatorMatcher<'a> {
4192    tag: &'a str,
4193    element_idx: usize,
4194    component_idx: usize,
4195    expected_values: Vec<&'a str>,
4196    /// Optional occurrence index: `#N` selects the Nth match among instances.
4197    occurrence: Option<usize>,
4198}
4199
4200impl<'a> DiscriminatorMatcher<'a> {
4201    fn parse(disc: &'a str) -> Option<Self> {
4202        let (spec, expected) = disc.split_once('=')?;
4203        let parts: Vec<&str> = spec.split('.').collect();
4204        if parts.len() != 3 {
4205            return None;
4206        }
4207        let (expected_raw, occurrence) = parse_discriminator_occurrence(expected);
4208        Some(Self {
4209            tag: parts[0],
4210            element_idx: parts[1].parse().ok()?,
4211            component_idx: parts[2].parse().ok()?,
4212            expected_values: expected_raw.split('|').collect(),
4213            occurrence,
4214        })
4215    }
4216
4217    fn matches(&self, instance: &AssembledGroupInstance) -> bool {
4218        instance.segments.iter().any(|s| {
4219            s.tag.eq_ignore_ascii_case(self.tag)
4220                && s.elements
4221                    .get(self.element_idx)
4222                    .and_then(|e| e.get(self.component_idx))
4223                    .map(|v| self.expected_values.iter().any(|ev| v == ev))
4224                    .unwrap_or(false)
4225        })
4226    }
4227
4228    /// Filter instances, respecting the occurrence index if present.
4229    fn filter_instances<'b>(
4230        &self,
4231        instances: Vec<&'b AssembledGroupInstance>,
4232    ) -> Vec<&'b AssembledGroupInstance> {
4233        let matching: Vec<_> = instances
4234            .into_iter()
4235            .filter(|inst| self.matches(inst))
4236            .collect();
4237        if let Some(occ) = self.occurrence {
4238            matching.into_iter().nth(occ).into_iter().collect()
4239        } else {
4240            matching
4241        }
4242    }
4243}
4244
4245/// Parse an optional occurrence index from a discriminator expected value.
4246///
4247/// `"TN#1"` → `("TN", Some(1))` — select the 2nd matching rep
4248/// `"TN"`   → `("TN", None)` — select all matching reps
4249/// `"Z13|Z14#0"` → `("Z13|Z14", Some(0))` — first match among Z13 or Z14
4250fn parse_discriminator_occurrence(expected: &str) -> (&str, Option<usize>) {
4251    if let Some(hash_pos) = expected.rfind('#') {
4252        if let Ok(occ) = expected[hash_pos + 1..].parse::<usize>() {
4253            return (&expected[..hash_pos], Some(occ));
4254        }
4255    }
4256    (expected, None)
4257}
4258
4259/// Strip explicit rep index from a relative path: "SG5:4" → "SG5", "SG8:3" → "SG8".
4260/// Used for multi-rep entities where subsequent items should append rather than
4261/// merge into the same rep position.
4262fn strip_rep_index(relative: &str) -> String {
4263    let (id, _) = parse_group_spec(relative);
4264    id.to_string()
4265}
4266
4267/// Strip all explicit rep indices from a multi-part relative path:
4268/// "SG8:3.SG10" → "SG8.SG10", "SG8:3.SG10:0" → "SG8.SG10".
4269/// Used for multi-rep depth-2+ entities so resolve_child_relative uses
4270/// source_path lookup instead of hardcoded indices.
4271pub(crate) fn strip_all_rep_indices(relative: &str) -> String {
4272    relative
4273        .split('.')
4274        .map(|part| {
4275            let (id, _) = parse_group_spec(part);
4276            id
4277        })
4278        .collect::<Vec<_>>()
4279        .join(".")
4280}
4281
4282// ── Nested child groups (`[meta] parent_field`) ──
4283
4284/// Whether `child` is a `parent_field` definition nested directly below `parent`
4285/// (which may itself be a `parent_field` definition — nesting can span several
4286/// group levels, one `parent_field` per level):
4287/// same entity, `source_group` exactly one level deeper, and (when both carry a
4288/// `source_path`) a structurally compatible parent path. Qualifiers on the parent
4289/// part are compared only when both sides specify one; the instance-level check
4290/// is [`nested_parent_qualifier`] + [`entry_qualifier_matches`].
4291pub fn is_nested_child_of(child: &MappingDefinition, parent: &MappingDefinition) -> bool {
4292    if child.meta.parent_field.is_none() || child.meta.entity != parent.meta.entity {
4293        return false;
4294    }
4295    let child_sg = strip_all_rep_indices(&child.meta.source_group);
4296    let parent_sg = strip_all_rep_indices(&parent.meta.source_group);
4297    match child_sg.rsplit_once('.') {
4298        Some((head, _)) if head.eq_ignore_ascii_case(&parent_sg) => {}
4299        _ => return false,
4300    }
4301    let (Some(child_sp), Some(parent_sp)) = (
4302        child.meta.source_path.as_deref(),
4303        parent.meta.source_path.as_deref(),
4304    ) else {
4305        return true;
4306    };
4307    let Some((child_parent_sp, _)) = child_sp.rsplit_once('.') else {
4308        return false;
4309    };
4310    let child_parts: Vec<&str> = child_parent_sp.split('.').collect();
4311    let parent_parts: Vec<&str> = parent_sp.split('.').collect();
4312    child_parts.len() == parent_parts.len()
4313        && child_parts.iter().zip(&parent_parts).all(|(c, p)| {
4314            let (c_id, c_q) = parse_source_path_part(c);
4315            let (p_id, p_q) = parse_source_path_part(p);
4316            c_id.eq_ignore_ascii_case(p_id)
4317                && match (c_q, p_q) {
4318                    (Some(cq), Some(pq)) => cq.eq_ignore_ascii_case(pq),
4319                    _ => true,
4320                }
4321        })
4322}
4323
4324/// Whether `child` is bound to the repetitions of `parent`: a definition without
4325/// `parent_field` whose `source_path` lies exactly one group below `parent`'s,
4326/// both writing the same entity (e.g. a CCI rule on `sg4.sg8_z01.sg10` writing
4327/// `regelzone` into the `MarktlokationDaten` of `sg4.sg8_z01`).
4328///
4329/// Its fields land in the object mapped from the parent repetition that
4330/// contains the child group, and are rendered under that same repetition. Both
4331/// were paired by array position before: with several SG8 repetitions and
4332/// SG10s under only some of them, a child's fields landed in the wrong object
4333/// and were rendered under the wrong SEQ. BO4E carries no positions; the
4334/// object a field sits in is the only link there is.
4335///
4336/// Only parents at least two groups deep bind (`sg4.sg8_z01`, not `sg4`): a
4337/// transaction-root or message-level group is one object anyway.
4338pub fn is_bound_child_of(child: &MappingDefinition, parent: &MappingDefinition) -> bool {
4339    if std::ptr::eq(child, parent)
4340        || child.meta.parent_field.is_some()
4341        || parent.meta.parent_field.is_some()
4342        || child.meta.target_list.is_some()
4343        || parent.meta.target_list.is_some()
4344        || child.meta.entity != parent.meta.entity
4345    {
4346        return false;
4347    }
4348    let (Some(child_sp), Some(parent_sp)) = (
4349        child.meta.source_path.as_deref(),
4350        parent.meta.source_path.as_deref(),
4351    ) else {
4352        return false;
4353    };
4354    parent_sp.contains('.')
4355        && child_sp
4356            .rsplit_once('.')
4357            .is_some_and(|(head, _)| head.eq_ignore_ascii_case(parent_sp))
4358}
4359
4360/// Whether `def` is bound to a parent definition among `definitions` (see
4361/// [`is_bound_child_of`]) and so mapped inside its parent, never on its own.
4362pub fn is_bound_child(definitions: &[MappingDefinition], def: &MappingDefinition) -> bool {
4363    definitions.iter().any(|p| is_bound_child_of(def, p))
4364}
4365
4366/// Entry qualifier the parent group instance must carry for a nested child
4367/// definition to apply (e.g. `"z08"` for `source_path = "sg4.sg12_z08.sg13"`).
4368fn nested_parent_qualifier(child: &MappingDefinition) -> Option<&str> {
4369    let (parent_path, _) = child.meta.source_path.as_deref()?.rsplit_once('.')?;
4370    let last = parent_path.rsplit('.').next()?;
4371    parse_source_path_part(last).1
4372}
4373
4374/// Leaf group id and optional entry qualifier of a nested child definition
4375/// (e.g. `("SG13", None)` for `source_group = "SG4.SG12.SG13"`).
4376fn nested_child_leaf(child: &MappingDefinition) -> (String, Option<&str>) {
4377    let leaf_group = strip_all_rep_indices(
4378        child
4379            .meta
4380            .source_group
4381            .rsplit('.')
4382            .next()
4383            .unwrap_or(&child.meta.source_group),
4384    );
4385    let leaf_qualifier = child
4386        .meta
4387        .source_path
4388        .as_deref()
4389        .and_then(|sp| sp.rsplit('.').next())
4390        .and_then(|part| parse_source_path_part(part).1);
4391    (leaf_group, leaf_qualifier)
4392}
4393
4394/// The repetitions of `instance`'s child group that the bound `child` maps:
4395/// the group named by its `source_path` leaf, narrowed by the leaf's qualifier
4396/// and by the definition's discriminator.
4397fn bound_child_reps<'i>(
4398    instance: &'i AssembledGroupInstance,
4399    child: &MappingDefinition,
4400) -> Vec<&'i AssembledGroupInstance> {
4401    let (leaf_id, leaf_qualifier) = nested_child_leaf(child);
4402    let Some(group) = instance
4403        .child_groups
4404        .iter()
4405        .find(|g| g.group_id.eq_ignore_ascii_case(&leaf_id))
4406    else {
4407        return Vec::new();
4408    };
4409    let reps: Vec<&AssembledGroupInstance> = match leaf_qualifier {
4410        Some(q) => find_all_reps_by_entry_qualifier(&group.repetitions, q),
4411        None => group.repetitions.iter().collect(),
4412    };
4413    match child
4414        .meta
4415        .discriminator
4416        .as_deref()
4417        .and_then(DiscriminatorMatcher::parse)
4418    {
4419        Some(matcher) => matcher.filter_instances(reps),
4420        None => reps,
4421    }
4422}
4423
4424/// Append `reps` to `instance`'s child group `leaf_id`, creating it if absent.
4425fn push_child_reps(
4426    instance: &mut AssembledGroupInstance,
4427    leaf_id: String,
4428    reps: Vec<AssembledGroupInstance>,
4429) {
4430    match instance
4431        .child_groups
4432        .iter_mut()
4433        .find(|g| g.group_id.eq_ignore_ascii_case(&leaf_id))
4434    {
4435        Some(group) => group.repetitions.extend(reps),
4436        None => instance.child_groups.push(AssembledGroup {
4437            group_id: leaf_id,
4438            repetitions: reps,
4439        }),
4440    }
4441}
4442
4443/// Whether the instance's entry segment (its first segment) carries `qualifier`
4444/// at `elements[0][0]`. Compound qualifiers (`"z53_z54"`) match any part.
4445fn entry_qualifier_matches(instance: &AssembledGroupInstance, qualifier: &str) -> bool {
4446    segment_qualifier_matches(instance.segments.first(), qualifier)
4447}
4448
4449/// [`entry_qualifier_matches`] for a group repetition rebuilt by the reverse
4450/// mapping from `def`. Its segments follow the order of `def`'s fields, so the
4451/// entry segment need not come first (e.g. `PIA` listed before `SEQ`). When
4452/// `def` has a discriminator, its segment tag names the entry segment.
4453fn rebuilt_entry_qualifier_matches(
4454    instance: &AssembledGroupInstance,
4455    def: &MappingDefinition,
4456    qualifier: &str,
4457) -> bool {
4458    let entry_tag = def
4459        .meta
4460        .discriminator
4461        .as_deref()
4462        .and_then(|d| d.split('.').next())
4463        .filter(|tag| !tag.is_empty());
4464    let entry = match entry_tag {
4465        Some(tag) => instance
4466            .segments
4467            .iter()
4468            .find(|s| s.tag.eq_ignore_ascii_case(tag)),
4469        None => instance.segments.first(),
4470    };
4471    segment_qualifier_matches(entry, qualifier)
4472}
4473
4474fn segment_qualifier_matches(segment: Option<&AssembledSegment>, qualifier: &str) -> bool {
4475    segment
4476        .and_then(|seg| seg.elements.first())
4477        .and_then(|e| e.first())
4478        .is_some_and(|v| qualifier.split('_').any(|q| v.eq_ignore_ascii_case(q)))
4479}
4480
4481/// Whether a `when_filled` guard's field carries data: a string (or an enriched
4482/// `{code, …}` object), or a non-empty array or object. A group whose content
4483/// sits in nested children (`parent_field`, e.g. `zuordnungen` from SG10) has
4484/// nothing else to name — its entry segment must still be written when they
4485/// are there, or the group cannot be rendered from data the AHB allows.
4486fn field_is_filled(bo4e_value: &serde_json::Value, field: &str) -> bool {
4487    let mut current = bo4e_value;
4488    for part in field.split('.') {
4489        match current.get(part) {
4490            Some(v) => current = v,
4491            None => return false,
4492        }
4493    }
4494    match current {
4495        serde_json::Value::String(s) => !s.is_empty(),
4496        serde_json::Value::Array(a) => !a.is_empty(),
4497        serde_json::Value::Object(o) => !o.is_empty(),
4498        serde_json::Value::Number(_) | serde_json::Value::Bool(_) => true,
4499        serde_json::Value::Null => false,
4500    }
4501}
4502
4503/// A list target `name[].sub` → `("name", "sub")`: the field writes `sub` of
4504/// one element of the array `name` per matching segment.
4505pub(crate) fn list_target(target: &str) -> Option<(&str, &str)> {
4506    let (list, sub) = target.split_once("[].")?;
4507    (!list.is_empty() && !sub.is_empty()).then_some((list, sub))
4508}
4509
4510/// Parse a segment tag with optional qualifier and occurrence index.
4511///
4512/// - `"dtm[92]"`    → `("DTM", Some("92"), 0)` — first (default) occurrence
4513/// - `"rff[Z34,1]"` → `("RFF", Some("Z34"), 1)` — second occurrence (0-indexed)
4514/// - `"rff[Z34,*]"` → `("RFF", Some("Z34"), 0)` — wildcard occurrence
4515/// - `"rff"`         → `("RFF", None, 0)`
4516pub(crate) fn parse_tag_qualifier(tag_part: &str) -> (String, Option<&str>, usize) {
4517    if let Some(bracket_start) = tag_part.find('[') {
4518        let tag = tag_part[..bracket_start].to_uppercase();
4519        let inner = tag_part[bracket_start + 1..].trim_end_matches(']');
4520        if let Some(comma_pos) = inner.find(',') {
4521            let qualifier = &inner[..comma_pos];
4522            let index = inner[comma_pos + 1..].parse::<usize>().unwrap_or(0);
4523            // "*" wildcard means no qualifier filter — positional access only
4524            if qualifier == "*" {
4525                (tag, None, index)
4526            } else {
4527                (tag, Some(qualifier), index)
4528            }
4529        } else {
4530            (tag, Some(inner), 0)
4531        }
4532    } else {
4533        (tag_part.to_uppercase(), None, 0)
4534    }
4535}
4536
4537/// Deep-merge a BO4E value into the result map.
4538///
4539/// If the entity already exists as an object, new fields are merged in
4540/// (existing fields are NOT overwritten). This allows multiple TOML
4541/// definitions with the same `entity` name to contribute fields to one object.
4542pub fn deep_merge_insert(
4543    result: &mut serde_json::Map<String, serde_json::Value>,
4544    entity: &str,
4545    bo4e: serde_json::Value,
4546) {
4547    merge_entity(result, entity, bo4e, false);
4548}
4549
4550/// [`deep_merge_insert`], choosing what happens when the two values do not
4551/// line up (an array meets an object, or arrays of different lengths):
4552/// `keep_both` appends them as separate repetitions, otherwise the new value
4553/// replaces the old.
4554///
4555/// Keeping both is right for *sibling* groups sharing an entity — two LOC+Z16
4556/// (an array) and one LOC+Z22 (an object) are three `Marktlokation`
4557/// repetitions, and replacing dropped both MaLos without an error. It is wrong
4558/// for a group and its own flat child rule (an SG8 and its SG10 on one entity
4559/// without `parent_field`): their values are one repetition's fields, and
4560/// appending the child rows would turn each into an SG8 repetition of its own.
4561fn merge_entity(
4562    result: &mut serde_json::Map<String, serde_json::Value>,
4563    entity: &str,
4564    bo4e: serde_json::Value,
4565    keep_both: bool,
4566) {
4567    if let Some(existing) = result.get_mut(entity) {
4568        // Array + Array: element-wise merge (same entity from multiple TOML defs,
4569        // each producing an array for multi-rep groups like two LOC+Z17).
4570        if let (Some(existing_arr), Some(new_arr)) =
4571            (existing.as_array().map(|a| a.len()), bo4e.as_array())
4572        {
4573            if existing_arr == new_arr.len() {
4574                let existing_arr = existing.as_array_mut().unwrap();
4575                for (existing_elem, new_elem) in existing_arr.iter_mut().zip(new_arr) {
4576                    if let (Some(existing_map), Some(new_map)) =
4577                        (existing_elem.as_object_mut(), new_elem.as_object())
4578                    {
4579                        for (k, v) in new_map {
4580                            if let Some(existing_v) = existing_map.get_mut(k) {
4581                                if let (Some(existing_inner), Some(new_inner)) =
4582                                    (existing_v.as_object_mut(), v.as_object())
4583                                {
4584                                    for (ik, iv) in new_inner {
4585                                        existing_inner
4586                                            .entry(ik.clone())
4587                                            .or_insert_with(|| iv.clone());
4588                                    }
4589                                }
4590                            } else {
4591                                existing_map.insert(k.clone(), v.clone());
4592                            }
4593                        }
4594                    }
4595                }
4596                return;
4597            }
4598        }
4599        // Object + Object: field-level merge
4600        if let (Some(existing_map), serde_json::Value::Object(new_map)) =
4601            (existing.as_object_mut(), &bo4e)
4602        {
4603            for (k, v) in new_map {
4604                if let Some(existing_v) = existing_map.get_mut(k) {
4605                    // Recursively merge nested objects (e.g., companion types)
4606                    if let (Some(existing_inner), Some(new_inner)) =
4607                        (existing_v.as_object_mut(), v.as_object())
4608                    {
4609                        for (ik, iv) in new_inner {
4610                            existing_inner
4611                                .entry(ik.clone())
4612                                .or_insert_with(|| iv.clone());
4613                        }
4614                    }
4615                    // Don't overwrite existing scalar/array values
4616                } else {
4617                    existing_map.insert(k.clone(), v.clone());
4618                }
4619            }
4620            return;
4621        }
4622        if !keep_both {
4623            result.insert(entity.to_string(), bo4e);
4624            return;
4625        }
4626        // Shapes that do not line up are different repetitions: keep them all.
4627        let existing_items = match std::mem::take(existing) {
4628            serde_json::Value::Array(items) => items,
4629            other => vec![other],
4630        };
4631        let new_items = match bo4e {
4632            serde_json::Value::Array(items) => items,
4633            other => vec![other],
4634        };
4635        *existing = serde_json::Value::Array(existing_items.into_iter().chain(new_items).collect());
4636        return;
4637    }
4638    result.insert(entity.to_string(), bo4e);
4639}
4640
4641/// Append a definition's per-repetition output to a **list-valued field** on an
4642/// entity — the write half of `MappingMeta::target_list`.
4643///
4644/// This cannot go through `deep_merge_insert`, which documents that it does
4645/// "not overwrite existing scalar/array values". That rule is right for ordinary
4646/// fields and wrong here: a list field is the one place where several
4647/// definitions are *expected* to contribute to the same key (four separate
4648/// `Obis*` definitions all feed `zaehlwerke`), and under `deep_merge_insert`
4649/// every contribution after the first would be dropped without a trace.
4650///
4651/// Empty elements are skipped so an absent optional group does not leave a
4652/// `[{}]` behind, which would reverse into a phantom segment.
4653fn append_to_list_field(
4654    result: &mut serde_json::Map<String, serde_json::Value>,
4655    entity: &str,
4656    list_field: &str,
4657    bo4e: serde_json::Value,
4658) {
4659    let mut items = match bo4e {
4660        serde_json::Value::Array(a) => a,
4661        other => vec![other],
4662    };
4663    items.retain(|v| !v.as_object().is_some_and(|o| o.is_empty()));
4664    if items.is_empty() {
4665        return;
4666    }
4667    let entry = result
4668        .entry(entity.to_string())
4669        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
4670    // An entity carrying a list field is a single object. If it is already an
4671    // array, some other definition made it multi-rep and the two shapes are
4672    // incompatible — leave it alone rather than corrupt it silently.
4673    let Some(obj) = entry.as_object_mut() else {
4674        return;
4675    };
4676    match obj.get_mut(list_field).and_then(|v| v.as_array_mut()) {
4677        Some(existing) => existing.extend(items),
4678        None => {
4679            obj.insert(list_field.to_string(), serde_json::Value::Array(items));
4680        }
4681    }
4682}
4683
4684/// Convert a PascalCase name to camelCase by lowering the first character.
4685///
4686/// E.g., `"Ansprechpartner"` → `"ansprechpartner"`,
4687/// `"AnsprechpartnerEdifact"` → `"ansprechpartnerEdifact"`,
4688/// `"ProduktpaketPriorisierung"` → `"produktpaketPriorisierung"`.
4689/// Detect whether a JSON object looks like a map-keyed entity (typed PID format).
4690///
4691/// Map-keyed objects have short uppercase/alphanumeric keys that look like qualifier
4692/// codes (e.g., `{"Z04": {...}, "Z09": {...}}` or `{"MS": {...}, "MR": {...}}`),
4693/// as opposed to normal field-name objects (e.g., `{"name1": "...", "adresse": {...}}`).
4694fn is_map_keyed_object(value: &serde_json::Value) -> bool {
4695    let Some(obj) = value.as_object() else {
4696        return false;
4697    };
4698    if obj.is_empty() {
4699        return false;
4700    }
4701    // All keys must be short (≤5 chars), uppercase/digit only, and all values must be objects
4702    obj.iter().all(|(k, v)| {
4703        k.len() <= 5
4704            && k.chars()
4705                .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
4706            && v.is_object()
4707    })
4708}
4709
4710/// Find the BO4E companion field name used for the qualifier/discriminator
4711/// across definitions that share the same entity name.
4712///
4713/// For example, if `Geschaeftspartner` has a definition with discriminator
4714/// `NAD.0.0=Z04` and companion field `nad.0.0 → nadQualifier`, this returns
4715/// `Some("nadQualifier")`.
4716///
4717/// Used to inject map keys into inner objects when converting map-keyed entities.
4718fn find_qualifier_companion_field(
4719    definitions: &[crate::definition::MappingDefinition],
4720    entity: &str,
4721) -> Option<String> {
4722    for def in definitions {
4723        if def.meta.entity != *entity || def.meta.parent_field.is_some() {
4724            continue;
4725        }
4726        let disc = def.meta.discriminator.as_deref()?;
4727        let (disc_path, _) = disc.split_once('=')?;
4728        let disc_path_lower = disc_path.to_lowercase();
4729
4730        // Search [fields] for the qualifier field (e.g., Marktteilnehmer has
4731        // "marktrolle" in [fields]).
4732        for (path, mapping) in &def.fields {
4733            let cf_path = path.to_lowercase();
4734            let matches = cf_path == disc_path_lower || format!("{}.0", cf_path) == disc_path_lower;
4735            if matches {
4736                let target = match mapping {
4737                    FieldMapping::Simple(t) => t.as_str(),
4738                    FieldMapping::Structured(s) => s.target.as_str(),
4739                    FieldMapping::Nested(_) => continue,
4740                };
4741                if !target.is_empty() {
4742                    return Some(target.to_string());
4743                }
4744            }
4745        }
4746    }
4747    None
4748}
4749
4750/// Extract a child entity from its parent entity in the reverse mapping input.
4751///
4752/// When a child entity (e.g., Kontakt with source_group="SG2.SG3") isn't found
4753/// at the top level, look inside the parent entity (e.g., Marktteilnehmer with
4754/// source_group="SG2") for a nested field matching the child's camelCase name.
4755///
4756/// For map-keyed parents ({"MS": {...}, "MR": {...}}), collects child values
4757/// from all inner objects that have the field, returning them as an array.
4758fn extract_child_from_parent(
4759    entities: &serde_json::Value,
4760    definitions: &[MappingDefinition],
4761    child_def: &MappingDefinition,
4762) -> Option<serde_json::Value> {
4763    extract_child_from_parent_with_indices(entities, definitions, child_def).map(|(v, _)| v)
4764}
4765
4766/// Like `extract_child_from_parent`, but also returns the parent rep indices
4767/// from which each child was extracted.  This allows the nesting distribution
4768/// to place child groups under the correct parent rep even when `nesting_info`
4769/// is unavailable (e.g., typed struct / manual JSON construction).
4770fn extract_child_from_parent_with_indices(
4771    entities: &serde_json::Value,
4772    definitions: &[MappingDefinition],
4773    child_def: &MappingDefinition,
4774) -> Option<(serde_json::Value, Vec<usize>)> {
4775    let parts: Vec<&str> = child_def.meta.source_group.split('.').collect();
4776    if parts.len() < 2 {
4777        return None;
4778    }
4779    let parent_group = parts[0];
4780    let parent_def = definitions
4781        .iter()
4782        .find(|d| d.meta.source_group == parent_group && d.meta.entity != child_def.meta.entity)?;
4783    let parent_key = to_camel_case(&parent_def.meta.entity);
4784    let child_key = to_camel_case(&child_def.meta.entity);
4785    let parent_value = entities.get(&parent_key)?;
4786
4787    // Map-keyed parent: collect child from each inner object
4788    if let Some(parent_map) = parent_value.as_object() {
4789        if is_map_keyed_value(parent_map) {
4790            let mut children: Vec<serde_json::Value> = Vec::new();
4791            let mut indices: Vec<usize> = Vec::new();
4792            for (i, (_key, inner)) in parent_map.iter().enumerate() {
4793                if let Some(child) = inner.get(&child_key) {
4794                    if !child.is_null() {
4795                        children.push(child.clone());
4796                        indices.push(i);
4797                    }
4798                }
4799            }
4800            return match children.len() {
4801                0 => None,
4802                1 => Some((children.into_iter().next().unwrap(), indices)),
4803                _ => Some((serde_json::Value::Array(children), indices)),
4804            };
4805        }
4806    }
4807
4808    // Array parent: collect child from each element
4809    if let Some(parent_arr) = parent_value.as_array() {
4810        let mut children: Vec<serde_json::Value> = Vec::new();
4811        let mut indices: Vec<usize> = Vec::new();
4812        for (i, item) in parent_arr.iter().enumerate() {
4813            if let Some(child) = item.get(&child_key) {
4814                if !child.is_null() {
4815                    children.push(child.clone());
4816                    indices.push(i);
4817                }
4818            }
4819        }
4820        return match children.len() {
4821            0 => None,
4822            1 => Some((children.into_iter().next().unwrap(), indices)),
4823            _ => Some((serde_json::Value::Array(children), indices)),
4824        };
4825    }
4826
4827    // Single parent object — always index 0
4828    let child = parent_value.get(&child_key)?;
4829    if child.is_null() {
4830        return None;
4831    }
4832    Some((child.clone(), vec![0]))
4833}
4834
4835/// Move child entities under their parent entities in the forward-mapped result.
4836///
4837/// For each definition with a dotted `source_group` (e.g., "SG2.SG3"), finds the
4838/// parent definition (e.g., "SG2") and moves the child entity from the top-level
4839/// result into the parent entity as a nested field.
4840fn nest_child_entities_in_result(
4841    result: &mut serde_json::Map<String, serde_json::Value>,
4842    definitions: &[MappingDefinition],
4843    nesting_info: &std::collections::HashMap<String, Vec<usize>>,
4844    transaction_group: Option<&str>,
4845) {
4846    let nesting_pairs = child_entity_nesting_pairs(definitions, transaction_group);
4847
4848    for (_parent_group, parent_entity, child_entity, child_source_path) in nesting_pairs {
4849        let parent_key = to_camel_case(&parent_entity);
4850        let child_key = to_camel_case(&child_entity);
4851
4852        // Remove child from top level (if present)
4853        let child_value = match result.remove(&child_key) {
4854            Some(v) => v,
4855            None => continue,
4856        };
4857
4858        // Get parent value.
4859        // If the parent is a plain array (not map-keyed), nesting would silently
4860        // place the child into arbitrary array elements. Skip and leave the child
4861        // at the top level where the reverse mapper can find it.
4862        let Some(parent_value) = result.get_mut(&parent_key) else {
4863            // Parent doesn't exist — put child back
4864            result.insert(child_key, child_value);
4865            continue;
4866        };
4867        if parent_value.is_array() {
4868            result.insert(child_key, child_value);
4869            continue;
4870        }
4871
4872        // Get the nesting distribution (which parent rep each child rep belongs to)
4873        let distribution = child_source_path
4874            .as_deref()
4875            .and_then(|sp| nesting_info.get(sp));
4876
4877        // Normalize child to a list of (index, value) pairs
4878        let child_items: Vec<(usize, &serde_json::Value)> = match &child_value {
4879            serde_json::Value::Array(arr) => arr.iter().enumerate().collect(),
4880            other => vec![(0, other)],
4881        };
4882
4883        // Helper: insert or append child value into a parent object field.
4884        // First call inserts the value; subsequent calls convert to array and append.
4885        let insert_or_append = |obj: &mut serde_json::Map<String, serde_json::Value>,
4886                                key: &str,
4887                                val: &serde_json::Value| {
4888            match obj.get_mut(key) {
4889                Some(existing) => {
4890                    // Convert single value to array, then push
4891                    if !existing.is_array() {
4892                        let prev = existing.take();
4893                        *existing = serde_json::Value::Array(vec![prev]);
4894                    }
4895                    if let Some(arr) = existing.as_array_mut() {
4896                        arr.push(val.clone());
4897                    }
4898                }
4899                None => {
4900                    obj.insert(key.to_string(), val.clone());
4901                }
4902            }
4903        };
4904
4905        // Handle parent as map-keyed object: {"MS": {...}, "MR": {...}}
4906        if let Some(parent_map) = parent_value.as_object_mut() {
4907            if is_map_keyed_value(parent_map) {
4908                // Map keys in insertion order correspond to rep indices
4909                let keys: Vec<String> = parent_map.keys().cloned().collect();
4910                for (i, child_item) in &child_items {
4911                    let target_idx = distribution
4912                        .and_then(|dist| dist.get(*i))
4913                        .copied()
4914                        .unwrap_or(0);
4915                    if let Some(key) = keys.get(target_idx) {
4916                        if let Some(inner) = parent_map.get_mut(key).and_then(|v| v.as_object_mut())
4917                        {
4918                            insert_or_append(inner, &child_key, child_item);
4919                        }
4920                    }
4921                }
4922                continue;
4923            }
4924        }
4925
4926        // Handle parent as array
4927        if let Some(parent_arr) = parent_value.as_array_mut() {
4928            for (i, child_item) in &child_items {
4929                let target_idx = distribution
4930                    .and_then(|dist| dist.get(*i))
4931                    .copied()
4932                    .unwrap_or(0);
4933                if let Some(parent_obj) = parent_arr
4934                    .get_mut(target_idx)
4935                    .and_then(|v| v.as_object_mut())
4936                {
4937                    insert_or_append(parent_obj, &child_key, child_item);
4938                }
4939            }
4940            continue;
4941        }
4942
4943        // Handle parent as single object
4944        if let Some(parent_obj) = parent_value.as_object_mut() {
4945            for (_i, child_item) in &child_items {
4946                insert_or_append(parent_obj, &child_key, child_item);
4947            }
4948            continue;
4949        }
4950
4951        // Fallback: put child back at top level
4952        result.insert(child_key, child_value);
4953    }
4954}
4955
4956/// Parent/child entity pairs the forward mapping nests (see
4957/// [`nest_child_entities_in_result`]): `(parent_group, parent_entity,
4958/// child_entity, child_source_path)`.
4959///
4960/// A child entity (dotted `source_group`, e.g. `SG2.SG3` Kontakt) is moved into
4961/// the object of the entity mapped from its parent group (e.g. `SG2`
4962/// Marktteilnehmer) — unless the parent group is the transaction root, the
4963/// child also has a definition at the parent level (same-entity enrichment), or
4964/// the parent maps a dotted field of the child's name.
4965pub(crate) fn child_entity_nesting_pairs(
4966    definitions: &[MappingDefinition],
4967    transaction_group: Option<&str>,
4968) -> Vec<(String, String, String, Option<String>)> {
4969    // Collect parent→child relationships from definitions.
4970    // parent_group → (parent_entity, child_entity, child_source_path)
4971    let mut nesting_pairs: Vec<(String, String, String, Option<String>)> = Vec::new();
4972    for def in definitions {
4973        let parts: Vec<&str> = def.meta.source_group.split('.').collect();
4974        if parts.len() < 2 || def.meta.parent_field.is_some() {
4975            continue;
4976        }
4977        let parent_group = parts[0];
4978        // Skip nesting when the parent group is the transaction root. SG4 in UTILMD
4979        // IS the transaction — its direct children (Marktlokation, Geschaeftspartner,
4980        // ProduktpaketDaten, …) are peers of the transaction metadata (Prozessdaten),
4981        // not sub-objects of it. Nesting still applies to other parents (e.g. SG2.SG3
4982        // Kontakt stays nested under SG2 Marktteilnehmer).
4983        if transaction_group.is_some_and(|tx| tx == parent_group) {
4984            continue;
4985        }
4986        let child_entity = def.meta.entity.clone();
4987        // Skip if the child entity also has a definition at the parent group level.
4988        // E.g., Prozessdaten at SG4.SG6 enriches Prozessdaten at SG4 via deep_merge —
4989        // this is same-entity enrichment, not a parent-child nesting relationship.
4990        let child_has_parent_level_def = definitions
4991            .iter()
4992            .any(|d| d.meta.source_group == parent_group && d.meta.entity == child_entity);
4993        if child_has_parent_level_def {
4994            continue;
4995        }
4996        // Find the parent definition (a different entity at the parent group level)
4997        let parent_entity = definitions
4998            .iter()
4999            .find(|d| d.meta.source_group == parent_group && d.meta.entity != child_entity)
5000            .map(|d| d.meta.entity.clone());
5001        if let Some(ref parent_entity) = parent_entity {
5002            // Skip nesting if the parent definition has a dotted field target
5003            // that creates a sub-object with the same name as the child entity.
5004            // E.g., Prozessdaten has "zeitscheibe.referenz" which creates
5005            // prozessdaten.zeitscheibe — collides with nesting Zeitscheibe entity.
5006            let child_key_lc = to_camel_case(&child_entity);
5007            let parent_defs: Vec<_> = definitions
5008                .iter()
5009                .filter(|d| d.meta.entity == *parent_entity)
5010                .collect();
5011            let has_conflicting_field = parent_defs.iter().any(|pd| {
5012                pd.fields.values().any(|fm| {
5013                    let target = match fm {
5014                        crate::definition::FieldMapping::Simple(t) => t.as_str(),
5015                        crate::definition::FieldMapping::Structured(s) => s.target.as_str(),
5016                        crate::definition::FieldMapping::Nested(_) => "",
5017                    };
5018                    target.starts_with(&child_key_lc)
5019                        && target.get(child_key_lc.len()..child_key_lc.len() + 1) == Some(".")
5020                })
5021            });
5022            if has_conflicting_field {
5023                continue;
5024            }
5025            // Avoid duplicates
5026            if nesting_pairs
5027                .iter()
5028                .any(|(_, pe, ce, _)| *pe == *parent_entity && *ce == child_entity)
5029            {
5030                continue;
5031            }
5032            nesting_pairs.push((
5033                parent_group.to_string(),
5034                parent_entity.clone(),
5035                child_entity,
5036                def.meta.source_path.clone(),
5037            ));
5038        }
5039    }
5040
5041    nesting_pairs
5042}
5043
5044/// Check if a JSON map looks like a map-keyed entity (short uppercase/code keys → objects).
5045fn is_map_keyed_value(map: &serde_json::Map<String, serde_json::Value>) -> bool {
5046    if map.is_empty() {
5047        return false;
5048    }
5049    map.values().all(|v| v.is_object())
5050        && map.keys().all(|k| {
5051            k.len() <= 5
5052                || k.chars()
5053                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
5054        })
5055}
5056
5057/// One code-field position recovered from a mapping definition: where the value
5058/// came from in EDIFACT, and where it landed in BO4E.
5059#[derive(Clone)]
5060struct CodeSite<'a> {
5061    target: &'a str,
5062    /// `[meta] parent_field`: the site is a key of an element of that array on
5063    /// the entity, not a key of the entity. Without this the split enrichment
5064    /// looks for the target directly on the carrier and finds nothing, while
5065    /// the pre-split path enriched it at write time — the two would disagree on
5066    /// every nested rule.
5067    parent_field: Option<&'a str>,
5068    source_path: &'a str,
5069    seg_tag: String,
5070    /// The qualifier on the field key itself (`cav[Z30]...`).
5071    path_qualifier: Option<String>,
5072    /// The qualifier the definition's discriminator pins for this tag.
5073    disc_qualifier: Option<String>,
5074    element_idx: usize,
5075    component_idx: usize,
5076    enum_map: Option<&'a std::collections::BTreeMap<String, String>>,
5077    also_target: Option<&'a str>,
5078    also_enum_map: Option<&'a std::collections::BTreeMap<String, String>>,
5079}
5080
5081pub(crate) fn to_camel_case(name: &str) -> String {
5082    let mut chars = name.chars();
5083    match chars.next() {
5084        Some(c) => c.to_lowercase().to_string() + chars.as_str(),
5085        None => String::new(),
5086    }
5087}
5088
5089/// Set a value in a nested JSON map using a dotted path.
5090/// E.g., "address.city" sets `{"address": {"city": "value"}}`.
5091fn set_nested_value(map: &mut serde_json::Map<String, serde_json::Value>, path: &str, val: String) {
5092    set_nested_value_json(map, path, serde_json::Value::String(val));
5093}
5094
5095/// Like `set_nested_value` but accepts a `serde_json::Value` instead of a `String`.
5096fn set_nested_value_json(
5097    map: &mut serde_json::Map<String, serde_json::Value>,
5098    path: &str,
5099    val: serde_json::Value,
5100) {
5101    if let Some((prefix, leaf)) = path.rsplit_once('.') {
5102        let mut current = map;
5103        for part in prefix.split('.') {
5104            let entry = current
5105                .entry(part.to_string())
5106                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
5107            current = entry.as_object_mut().expect("expected object in path");
5108        }
5109        current.insert(leaf.to_string(), val);
5110    } else {
5111        map.insert(path.to_string(), val);
5112    }
5113}
5114
5115/// Precompiled cache for a single format-version/variant (e.g., FV2504/UTILMD_Strom).
5116///
5117/// Contains all engines with paths pre-resolved, ready for immediate use.
5118/// Loading one `VariantCache` file replaces thousands of individual `.bin` reads.
5119#[derive(serde::Serialize, serde::Deserialize)]
5120pub struct VariantCache {
5121    /// Message-level definitions (shared across PIDs).
5122    pub message_defs: Vec<MappingDefinition>,
5123    /// Per-PID transaction definitions (key: "pid_55001").
5124    pub transaction_defs: BTreeMap<String, Vec<MappingDefinition>>,
5125    /// Per-PID combined definitions (key: "pid_55001").
5126    pub combined_defs: BTreeMap<String, Vec<MappingDefinition>>,
5127    /// Per-PID code lookups (key: "pid_55001"). Cached to avoid reading schema JSONs at load time.
5128    #[serde(default)]
5129    pub code_lookups: BTreeMap<String, crate::code_lookup::CodeLookup>,
5130    /// Parsed MIG schema — cached to avoid re-parsing MIG XML at startup.
5131    #[serde(default)]
5132    pub mig_schema: Option<mig_types::schema::mig::MigSchema>,
5133    /// Segment element counts derived from MIG — cached for reverse mapping padding.
5134    #[serde(default)]
5135    pub segment_structure: Option<crate::segment_structure::SegmentStructure>,
5136    /// The shared code-list tables the definitions' `code_list` names resolve
5137    /// against. Not part of the cache file: the tables live once beside it, so
5138    /// `load` finds them and every engine this cache builds inherits them.
5139    /// Without that a translated code reaches the output raw.
5140    #[serde(skip)]
5141    pub code_lists: std::sync::Arc<crate::code_lists::CodeLists>,
5142    /// Per-PID AHB segment numbers (key: "pid_55001"). Used for MIG filtering at runtime.
5143    /// Eliminates the need to parse AHB XML files at startup.
5144    #[serde(default)]
5145    pub pid_segment_numbers: BTreeMap<String, Vec<String>>,
5146    /// Per-PID field requirements (key: "pid_55001"). Built from PID schema + TOML definitions.
5147    /// Used by `validate_pid()` to check field completeness.
5148    #[serde(default)]
5149    pub pid_requirements: BTreeMap<String, crate::pid_requirements::PidRequirements>,
5150    /// Per-PID pre-built AHB workflow (key: "pid_55001"). The EDIFACT-side rulebook
5151    /// (segment-path keyed), twin of `pid_requirements` (BO4E-entity keyed). Built at
5152    /// compile-mappings from the PID schema JSON so downstream consumers can run full
5153    /// raw-EDIFACT validation (`Mapper::validate_edifact`) without the schema files.
5154    #[serde(default)]
5155    pub pid_ahb_workflows: BTreeMap<String, ahb_types::AhbWorkflow>,
5156    /// Per-PID transaction group ID (key: "pid_55001", value: "SG4").
5157    /// Derived from the common `source_group` prefix of transaction definitions.
5158    /// Empty string for message-only variants (e.g., ORDCHG).
5159    #[serde(default)]
5160    pub tx_groups: BTreeMap<String, String>,
5161}
5162
5163impl VariantCache {
5164    /// Save this variant cache to a single JSON file.
5165    pub fn save(&self, path: &Path) -> Result<(), MappingError> {
5166        let encoded = serde_json::to_vec(self).map_err(|e| MappingError::CacheWrite {
5167            path: path.display().to_string(),
5168            message: e.to_string(),
5169        })?;
5170        if let Some(parent) = path.parent() {
5171            std::fs::create_dir_all(parent)?;
5172        }
5173        std::fs::write(path, encoded)?;
5174        Ok(())
5175    }
5176
5177    /// Load a variant cache from a single JSON file.
5178    pub fn load(path: &Path) -> Result<Self, MappingError> {
5179        let bytes = std::fs::read(path)?;
5180        let mut cache: Self =
5181            serde_json::from_slice(&bytes).map_err(|e| MappingError::CacheRead {
5182                path: path.display().to_string(),
5183                message: e.to_string(),
5184            })?;
5185        cache.code_lists = crate::code_lists::CodeLists::discover(path);
5186        Ok(cache)
5187    }
5188
5189    /// Get the transaction group for a PID (e.g., "SG4" for UTILMD PIDs).
5190    /// Returns `None` if the PID is not in this variant.
5191    /// Returns `Some("")` for message-only variants (no transaction group).
5192    pub fn tx_group(&self, pid: &str) -> Option<&str> {
5193        self.tx_groups
5194            .get(&format!("pid_{pid}"))
5195            .map(|s| s.as_str())
5196    }
5197
5198    /// Build a `MappingEngine` from the message-level definitions, attaching
5199    /// the per-PID code lookup so forward mapping enriches code fields with
5200    /// `{ code, meaning, enum }` objects.
5201    pub fn msg_engine(&self, pid: &str) -> MappingEngine {
5202        let mut eng = MappingEngine::from_definitions_with_code_lists(
5203            std::sync::Arc::clone(&self.code_lists),
5204            self.message_defs.clone(),
5205        )
5206        .with_pid(pid);
5207        if let Some(cl) = self.code_lookups.get(&format!("pid_{pid}")) {
5208            eng = eng.with_code_lookup(cl.clone());
5209        }
5210        eng
5211    }
5212
5213    /// Build a `MappingEngine` from the transaction-level definitions for a PID,
5214    /// attaching the per-PID code lookup. Returns `None` if the PID is not in
5215    /// this variant.
5216    pub fn tx_engine(&self, pid: &str) -> Option<MappingEngine> {
5217        self.transaction_defs
5218            .get(&format!("pid_{pid}"))
5219            .map(|defs| {
5220                let mut eng = MappingEngine::from_definitions_with_code_lists(
5221                    std::sync::Arc::clone(&self.code_lists),
5222                    defs.clone(),
5223                )
5224                .with_pid(pid);
5225                if let Some(cl) = self.code_lookups.get(&format!("pid_{pid}")) {
5226                    eng = eng.with_code_lookup(cl.clone());
5227                }
5228                eng
5229            })
5230    }
5231
5232    /// Get a PID-filtered MIG schema.
5233    /// Returns `None` if no MIG schema or no segment numbers for this PID.
5234    ///
5235    /// Falls back to the empty-PID workflow's segment numbers when the AHB
5236    /// has no Pruefidentifikator attribute (e.g., APERAK — one workflow for
5237    /// all BGM doc codes). This lets `from_edifact` work for variants whose
5238    /// AHB doesn't enumerate per-PID segment numbers.
5239    pub fn filtered_mig(&self, pid: &str) -> Option<mig_types::schema::mig::MigSchema> {
5240        let mig = self.mig_schema.as_ref()?;
5241        let numbers = self
5242            .pid_segment_numbers
5243            .get(&format!("pid_{pid}"))
5244            .or_else(|| self.pid_segment_numbers.get("pid_"))?;
5245        let number_set: std::collections::HashSet<String> = numbers.iter().cloned().collect();
5246        Some(mig_assembly::pid_filter::filter_mig_for_pid(
5247            mig,
5248            &number_set,
5249        ))
5250    }
5251}
5252
5253/// Bundled data for a single format version (e.g., FV2504).
5254///
5255/// Contains all VariantCaches for every message type in that FV,
5256/// serialized as one bincode file for distribution via GitHub releases.
5257#[derive(serde::Serialize, serde::Deserialize)]
5258pub struct DataBundle {
5259    pub format_version: String,
5260    pub bundle_version: u32,
5261    pub variants: BTreeMap<String, VariantCache>,
5262    /// PID-agnostic BO4E type catalog (parsed from `bo4e-german` source).
5263    ///
5264    /// Populated by the bundle generator at compile-mappings time. Older bundles
5265    /// without this field deserialize to an empty catalog.
5266    #[serde(default)]
5267    pub bo4e_catalog: crate::bo4e_catalog::Bo4eCatalog,
5268
5269    /// The crate version that produced this bundle.
5270    ///
5271    /// Distinct from [`bundle_version`](Self::bundle_version), which guards the
5272    /// serialisation *format* and has been unchanged for many releases — a
5273    /// bundle can satisfy it while its mappings, schemas and code lists come
5274    /// from another era. That is not a hypothetical: a bundle five months old
5275    /// passed the format check, loaded cleanly, and rendered 12% of a message
5276    /// with no error (issue #158).
5277    ///
5278    /// `None` for bundles produced before this field existed, which is itself
5279    /// evidence of age.
5280    #[serde(default, skip_serializing_if = "Option::is_none")]
5281    pub built_by: Option<String>,
5282    /// The shared code-list tables the definitions' `code_list` names resolve
5283    /// against.
5284    ///
5285    /// Carried IN the bundle, unlike `VariantCache`, which is written beside a
5286    /// copy of `code_lists.toml` and repairs itself from it on load. A bundle
5287    /// is a bare `.bin` fetched into `~/.edifact/data` with nothing beside it,
5288    /// so a bundle that does not carry its tables cannot resolve a single
5289    /// name: forward, the EDIFACT code reaches the output untranslated;
5290    /// reverse, the BO4E name is written into the EDIFACT slot verbatim. The
5291    /// deduplication that made naming worth doing does not argue against this
5292    /// -- there is one bundle per format version, so the tables appear once.
5293    #[serde(default)]
5294    pub code_lists: crate::code_lists::CodeLists,
5295}
5296
5297impl DataBundle {
5298    pub const CURRENT_VERSION: u32 = 2;
5299
5300    /// The release a bundle built now belongs to, and the one a bundle must
5301    /// have been built by to be read.
5302    ///
5303    /// Taken from `mig-bo4e` rather than from whichever crate produces or
5304    /// consumes a bundle: `mig-bo4e` carries the workspace version, which is
5305    /// what the release process stamps, while `automapper-generator` versions
5306    /// itself separately. Reading it from the producer gave `0.1.0` against a
5307    /// consumer expecting `0.1.1` — a mismatch that is an artefact of where the
5308    /// constant was read, not of the data.
5309    pub const PRODUCING_VERSION: &'static str = env!("CARGO_PKG_VERSION");
5310
5311    pub fn variant(&self, name: &str) -> Option<&VariantCache> {
5312        self.variants.get(name)
5313    }
5314
5315    pub fn write_to<W: std::io::Write>(&self, writer: &mut W) -> Result<(), MappingError> {
5316        let encoded = serde_json::to_vec(self).map_err(|e| MappingError::CacheWrite {
5317            path: "<stream>".to_string(),
5318            message: e.to_string(),
5319        })?;
5320        writer.write_all(&encoded).map_err(MappingError::Io)
5321    }
5322
5323    pub fn read_from<R: std::io::Read>(reader: &mut R) -> Result<Self, MappingError> {
5324        let mut bytes = Vec::new();
5325        reader.read_to_end(&mut bytes).map_err(MappingError::Io)?;
5326        serde_json::from_slice(&bytes).map_err(|e| MappingError::CacheRead {
5327            path: "<stream>".to_string(),
5328            message: e.to_string(),
5329        })
5330    }
5331
5332    pub fn read_from_checked<R: std::io::Read>(reader: &mut R) -> Result<Self, MappingError> {
5333        let mut bundle = Self::read_from(reader)?;
5334        // Every engine this bundle builds resolves names through its variant's
5335        // `Arc`, which `#[serde(skip)]` left empty on the way in.
5336        let shared = std::sync::Arc::new(std::mem::take(&mut bundle.code_lists));
5337        for variant in bundle.variants.values_mut() {
5338            variant.code_lists = std::sync::Arc::clone(&shared);
5339        }
5340        bundle.code_lists = (*shared).clone();
5341        if bundle.bundle_version != Self::CURRENT_VERSION {
5342            return Err(MappingError::CacheRead {
5343                path: "<stream>".to_string(),
5344                message: format!(
5345                    "Incompatible bundle version {}, expected version {}. \
5346                     Run `edifact-data update` to fetch compatible bundles.",
5347                    bundle.bundle_version,
5348                    Self::CURRENT_VERSION
5349                ),
5350            });
5351        }
5352        Ok(bundle)
5353    }
5354
5355    pub fn save(&self, path: &Path) -> Result<(), MappingError> {
5356        if let Some(parent) = path.parent() {
5357            std::fs::create_dir_all(parent)?;
5358        }
5359        let mut file = std::fs::File::create(path).map_err(MappingError::Io)?;
5360        self.write_to(&mut file)
5361    }
5362
5363    pub fn load(path: &Path) -> Result<Self, MappingError> {
5364        let mut file = std::fs::File::open(path).map_err(MappingError::Io)?;
5365        Self::read_from_checked(&mut file)
5366    }
5367}
5368
5369#[cfg(test)]
5370mod variant_cache_helper_tests {
5371    use super::*;
5372
5373    fn make_test_cache() -> VariantCache {
5374        let mut tx_groups = BTreeMap::new();
5375        tx_groups.insert("pid_55001".to_string(), "SG4".to_string());
5376        tx_groups.insert("pid_21007".to_string(), "SG14".to_string());
5377
5378        let mut transaction_defs = BTreeMap::new();
5379        transaction_defs.insert("pid_55001".to_string(), vec![]);
5380        transaction_defs.insert("pid_21007".to_string(), vec![]);
5381
5382        VariantCache {
5383            code_lists: Default::default(),
5384            message_defs: vec![],
5385            transaction_defs,
5386            combined_defs: BTreeMap::new(),
5387            code_lookups: BTreeMap::new(),
5388            mig_schema: None,
5389            segment_structure: None,
5390            pid_segment_numbers: BTreeMap::new(),
5391            pid_requirements: BTreeMap::new(),
5392            pid_ahb_workflows: BTreeMap::new(),
5393            tx_groups,
5394        }
5395    }
5396
5397    #[test]
5398    fn test_tx_group_returns_correct_group() {
5399        let vc = make_test_cache();
5400        assert_eq!(vc.tx_group("55001").unwrap(), "SG4");
5401        assert_eq!(vc.tx_group("21007").unwrap(), "SG14");
5402    }
5403
5404    #[test]
5405    fn test_tx_group_unknown_pid_returns_none() {
5406        let vc = make_test_cache();
5407        assert!(vc.tx_group("99999").is_none());
5408    }
5409
5410    #[test]
5411    fn test_msg_engine_returns_engine() {
5412        let vc = make_test_cache();
5413        let engine = vc.msg_engine("55001");
5414        assert_eq!(engine.definitions().len(), 0);
5415    }
5416
5417    #[test]
5418    fn test_tx_engine_returns_engine_for_known_pid() {
5419        let vc = make_test_cache();
5420        assert!(vc.tx_engine("55001").is_some());
5421    }
5422
5423    #[test]
5424    fn test_tx_engine_returns_none_for_unknown_pid() {
5425        let vc = make_test_cache();
5426        assert!(vc.tx_engine("99999").is_none());
5427    }
5428
5429    /// Build a cache whose every map holds many keys. Each call creates fresh
5430    /// `HashMap`s (fresh random hash seeds), so an order-dependent serializer
5431    /// produces different bytes on different calls.
5432    fn make_populated_cache() -> VariantCache {
5433        let pids: Vec<String> = (0..40).map(|i| format!("pid_{}", 55000 + i * 7)).collect();
5434        let schema: serde_json::Value = serde_json::from_str(include_str!(
5435            "../../mig-types/src/generated/fv2504/utilmd/pids/pid_55001_schema.json"
5436        ))
5437        .unwrap();
5438        let code_lookup = crate::code_lookup::CodeLookup::from_schema_value(&schema);
5439        let element_counts: serde_json::Map<String, serde_json::Value> = (0..40)
5440            .map(|i| (format!("T{i:02}"), serde_json::json!(i)))
5441            .collect();
5442        let segment_structure: SegmentStructure =
5443            serde_json::from_value(serde_json::json!({ "element_counts": element_counts }))
5444                .unwrap();
5445        let ubs: serde_json::Map<String, serde_json::Value> = (0..40)
5446            .map(|i| (format!("UB{i}"), serde_json::json!({ "Ref": i })))
5447            .collect();
5448        let workflow: ahb_types::AhbWorkflow = serde_json::from_value(serde_json::json!({
5449            "pruefidentifikator": "55001",
5450            "description": "",
5451            "communication_direction": null,
5452            "fields": [],
5453            "ub_definitions": ubs,
5454        }))
5455        .unwrap();
5456
5457        let mut vc = make_test_cache();
5458        vc.segment_structure = Some(segment_structure);
5459        for pid in &pids {
5460            vc.transaction_defs.insert(pid.clone(), vec![]);
5461            vc.combined_defs.insert(pid.clone(), vec![]);
5462            vc.code_lookups.insert(pid.clone(), code_lookup.clone());
5463            vc.pid_segment_numbers
5464                .insert(pid.clone(), vec!["00001".to_string()]);
5465            vc.pid_ahb_workflows.insert(pid.clone(), workflow.clone());
5466            vc.tx_groups.insert(pid.clone(), "SG4".to_string());
5467        }
5468        vc
5469    }
5470
5471    /// Enrichment of qualified field paths uses the codes of the segment variant
5472    /// the field reads, never those of a sibling variant of the same tag.
5473    #[test]
5474    fn test_enrichment_uses_codes_of_the_path_qualifier_variant() {
5475        let comp = |sub: u64, id: &str, codes: Option<serde_json::Value>| match codes {
5476            Some(c) => serde_json::json!({"sub_index": sub, "id": id, "type": "code", "codes": c}),
5477            None => serde_json::json!({"sub_index": sub, "id": id, "type": "data"}),
5478        };
5479        let code = |v: &str, n: &str| serde_json::json!([{"value": v, "name": n}]);
5480        let seg = |tag: &str, composite: &str, comps: Vec<serde_json::Value>| serde_json::json!({"id": tag, "elements": [{"index": 0, "composite": composite, "components": comps}]});
5481        let schema = serde_json::json!({"fields": {"sg15": {"segments": [
5482            seg("RFF", "C506", vec![comp(0, "1153", Some(code("Z13", "PID"))), comp(1, "1154", Some(code("21037", "RD / NB-Bewertung")))]),
5483            seg("RFF", "C506", vec![comp(0, "1153", Some(code("ACW", "Referenz"))), comp(1, "1154", None)]),
5484            seg("CAV", "C889", vec![comp(0, "7111", Some(code("Z91", "Z91"))), comp(1, "7110", Some(code("A", "Alpha")))]),
5485            seg("CAV", "C889", vec![comp(0, "7111", Some(code("ZF0", "ZF0"))), comp(1, "7110", Some(code("C", "Gamma")))]),
5486        ]}}});
5487        let engine = MappingEngine::new_empty()
5488            .with_code_lookup(crate::code_lookup::CodeLookup::from_schema_value(&schema));
5489        let def = MappingDefinition::from_toml_str(
5490            r#"
5491[meta]
5492entity = "Status"
5493bo4e_type = "Status"
5494source_group = "SG15"
5495source_path = "sg15"
5496discriminator = "RFF.0.0=Z13"
5497
5498[fields]
5499"rff.0.1" = "pruefidentifikator"
5500"rff[ACW].0.1" = "referenz"
5501"cav[Z91].0.1" = "z91Wert"
5502"cav[ZF0].0.1" = "zf0Wert"
5503"#,
5504        )
5505        .unwrap();
5506        let segment = |tag: &str, elements: &[&[&str]]| OwnedSegment {
5507            id: tag.to_string(),
5508            elements: elements
5509                .iter()
5510                .map(|e| e.iter().map(|c| c.to_string()).collect())
5511                .collect(),
5512            segment_number: 1,
5513        };
5514        let json = engine.map_forward_from_segments(
5515            &[
5516                segment("RFF", &[&["Z13", "21037"]]),
5517                segment("RFF", &[&["ACW", "REF-1"]]),
5518                segment("CAV", &[&["Z91", "C"]]),
5519                segment("CAV", &[&["ZF0", "C"]]),
5520            ],
5521            &def,
5522        );
5523        assert_eq!(
5524            json["referenz"],
5525            serde_json::json!("REF-1"),
5526            "RFF+ACW d1154 is data; RFF+Z13's codes must not apply: {json}"
5527        );
5528        assert_eq!(json["pruefidentifikator"]["meaning"], "RD / NB-Bewertung");
5529        assert_eq!(
5530            json["z91Wert"]["meaning"],
5531            serde_json::Value::Null,
5532            "'C' is a CAV+ZF0 code, unknown to CAV+Z91: {json}"
5533        );
5534        assert_eq!(json["zf0Wert"]["meaning"], "Gamma");
5535    }
5536
5537    /// A list target keeps every CAV with its own code, in wire order, and
5538    /// writes them back the same way — an absent first CAV no longer shifts
5539    /// the others, and a third CAV has somewhere to go.
5540    #[test]
5541    fn list_target_reads_and_writes_every_repetition_in_order() {
5542        let engine = MappingEngine::new_empty();
5543        let def = MappingDefinition::from_toml_str(
5544            r#"
5545[meta]
5546entity = "Zuordnung"
5547bo4e_type = "Zuordnung"
5548source_group = "SG10"
5549source_path = "sg10"
5550
5551[fields]
5552"cci.2.0" = "merkmal.code"
5553"cav[*,*].0.0" = "werte[].code"
5554"cav[*,*].0.3" = "werte[].text"
5555"cav[Z30,*].0.3" = "geraetenummern[].nummer"
5556"#,
5557        )
5558        .unwrap();
5559        let segment = |tag: &str, elements: &[&[&str]]| OwnedSegment {
5560            id: tag.to_string(),
5561            elements: elements
5562                .iter()
5563                .map(|e| e.iter().map(|c| c.to_string()).collect())
5564                .collect(),
5565            segment_number: 1,
5566        };
5567        let json = engine.map_forward_from_segments(
5568            &[
5569                segment("CCI", &[&[""], &[""], &["ZB3"]]),
5570                segment("CAV", &[&["Z90", "", "", "UENB"]]),
5571                segment("CAV", &[&["Z91", "", "", "MSB"]]),
5572                segment("CAV", &[&["Z30", "", "", "W1"]]),
5573                segment("CAV", &[&["Z30", "", "", "W2"]]),
5574            ],
5575            &def,
5576        );
5577        assert_eq!(
5578            json["werte"],
5579            serde_json::json!([
5580                {"code": "Z90", "text": "UENB"},
5581                {"code": "Z91", "text": "MSB"},
5582                {"code": "Z30", "text": "W1"},
5583                {"code": "Z30", "text": "W2"},
5584            ]),
5585            "{json}"
5586        );
5587        assert_eq!(
5588            json["geraetenummern"],
5589            serde_json::json!([{"nummer": "W1"}, {"nummer": "W2"}])
5590        );
5591
5592        // Back: one CAV per element, in the list's order.
5593        let only_werte = serde_json::json!({
5594            "merkmal": {"code": "ZB3"},
5595            "werte": [{"text": "UENB", "code": "Z90"}, {"code": "Z91", "text": "MSB"}],
5596        });
5597        let instance = engine.map_reverse(&only_werte, &def);
5598        let cavs: Vec<Vec<String>> = instance
5599            .segments
5600            .iter()
5601            .filter(|s| s.tag == "CAV")
5602            .map(|s| s.elements[0].clone())
5603            .collect();
5604        assert_eq!(
5605            cavs,
5606            vec![
5607                vec![
5608                    "Z90".to_string(),
5609                    String::new(),
5610                    String::new(),
5611                    "UENB".to_string()
5612                ],
5613                vec![
5614                    "Z91".to_string(),
5615                    String::new(),
5616                    String::new(),
5617                    "MSB".to_string()
5618                ],
5619            ]
5620        );
5621    }
5622
5623    #[test]
5624    fn test_variant_cache_serialization_is_deterministic() {
5625        let reference = serde_json::to_vec(&make_populated_cache()).unwrap();
5626        for _ in 0..5 {
5627            let again = serde_json::to_vec(&make_populated_cache()).unwrap();
5628            assert!(
5629                reference == again,
5630                "VariantCache serialization must not depend on HashMap iteration order"
5631            );
5632        }
5633    }
5634
5635    #[test]
5636    fn test_variant_cache_serializes_map_keys_sorted() {
5637        use indexmap::IndexMap;
5638        use serde::de::IgnoredAny;
5639
5640        #[derive(serde::Deserialize)]
5641        struct ProbeWorkflow {
5642            ub_definitions: IndexMap<String, IgnoredAny>,
5643        }
5644        #[derive(serde::Deserialize)]
5645        struct ProbeStructure {
5646            element_counts: IndexMap<String, usize>,
5647        }
5648        #[derive(serde::Deserialize)]
5649        struct Probe {
5650            transaction_defs: IndexMap<String, IgnoredAny>,
5651            combined_defs: IndexMap<String, IgnoredAny>,
5652            code_lookups: IndexMap<String, IndexMap<String, IgnoredAny>>,
5653            segment_structure: ProbeStructure,
5654            pid_segment_numbers: IndexMap<String, IgnoredAny>,
5655            pid_requirements: IndexMap<String, IgnoredAny>,
5656            pid_ahb_workflows: IndexMap<String, ProbeWorkflow>,
5657            tx_groups: IndexMap<String, String>,
5658        }
5659        fn assert_sorted<'a>(what: &str, keys: impl Iterator<Item = &'a String>) {
5660            let keys: Vec<&String> = keys.collect();
5661            let mut sorted = keys.clone();
5662            sorted.sort();
5663            assert_eq!(keys, sorted, "{what} keys must serialize in sorted order");
5664        }
5665
5666        let json = serde_json::to_string(&make_populated_cache()).unwrap();
5667        let probe: Probe = serde_json::from_str(&json).unwrap();
5668        assert_sorted("transaction_defs", probe.transaction_defs.keys());
5669        assert_sorted("combined_defs", probe.combined_defs.keys());
5670        assert_sorted("code_lookups", probe.code_lookups.keys());
5671        let lookup = probe.code_lookups.values().next().unwrap();
5672        assert!(lookup.len() > 10, "fixture lookup should have many entries");
5673        assert_sorted("code_lookup entries", lookup.keys());
5674        assert_sorted(
5675            "segment_structure",
5676            probe.segment_structure.element_counts.keys(),
5677        );
5678        assert_sorted("pid_segment_numbers", probe.pid_segment_numbers.keys());
5679        assert_sorted("pid_requirements", probe.pid_requirements.keys());
5680        assert_sorted("pid_ahb_workflows", probe.pid_ahb_workflows.keys());
5681        let wf = probe.pid_ahb_workflows.values().next().unwrap();
5682        assert_sorted("ub_definitions", wf.ub_definitions.keys());
5683        assert_sorted("tx_groups", probe.tx_groups.keys());
5684    }
5685
5686    #[test]
5687    fn test_data_bundle_serializes_variants_sorted() {
5688        use indexmap::IndexMap;
5689        use serde::de::IgnoredAny;
5690
5691        #[derive(serde::Deserialize)]
5692        struct Probe {
5693            variants: IndexMap<String, IgnoredAny>,
5694        }
5695        let variants: BTreeMap<String, VariantCache> = (0..20)
5696            .map(|i| (format!("VARIANT_{i:02}"), make_test_cache()))
5697            .collect();
5698        let bundle = DataBundle {
5699            format_version: "FV2504".to_string(),
5700            bundle_version: DataBundle::CURRENT_VERSION,
5701            built_by: Some(DataBundle::PRODUCING_VERSION.to_string()),
5702            variants,
5703            bo4e_catalog: Default::default(),
5704            code_lists: Default::default(),
5705        };
5706        let mut bytes = Vec::new();
5707        bundle.write_to(&mut bytes).unwrap();
5708        let probe: Probe = serde_json::from_slice(&bytes).unwrap();
5709        let keys: Vec<&String> = probe.variants.keys().collect();
5710        let mut sorted = keys.clone();
5711        sorted.sort();
5712        assert_eq!(keys, sorted);
5713    }
5714}
5715
5716#[cfg(test)]
5717mod tests {
5718    use super::*;
5719    use crate::definition::{MappingDefinition, MappingMeta, StructuredFieldMapping};
5720    use indexmap::IndexMap;
5721
5722    fn make_def(fields: IndexMap<String, FieldMapping>) -> MappingDefinition {
5723        MappingDefinition {
5724            meta: MappingMeta {
5725                entity: "Test".to_string(),
5726                bo4e_type: "Test".to_string(),
5727                source_group: "SG4".to_string(),
5728                source_path: None,
5729                discriminator: None,
5730                repeat_on_tag: None,
5731                parent_field: None,
5732                target_list: None,
5733                order: None,
5734            },
5735            fields,
5736            complex_handlers: None,
5737        }
5738    }
5739
5740    #[test]
5741    fn test_map_interchange_single_transaction_backward_compat() {
5742        use mig_assembly::assembler::*;
5743
5744        // Single SG4 with SG5 — the common case for current PID 55001 fixtures
5745        let tree = AssembledTree {
5746            segments: vec![
5747                AssembledSegment {
5748                    tag: "UNH".to_string(),
5749                    elements: vec![vec!["001".to_string()]],
5750                    mig_number: None,
5751                    segment_number: None,
5752                },
5753                AssembledSegment {
5754                    tag: "BGM".to_string(),
5755                    elements: vec![vec!["E01".to_string()], vec!["DOC001".to_string()]],
5756                    mig_number: None,
5757                    segment_number: None,
5758                },
5759            ],
5760            groups: vec![
5761                AssembledGroup {
5762                    group_id: "SG2".to_string(),
5763                    repetitions: vec![AssembledGroupInstance {
5764                        segments: vec![AssembledSegment {
5765                            tag: "NAD".to_string(),
5766                            elements: vec![vec!["MS".to_string()], vec!["9900123".to_string()]],
5767                            mig_number: None,
5768                            segment_number: None,
5769                        }],
5770                        child_groups: vec![],
5771                        entry_mig_number: None,
5772                        variant_mig_numbers: vec![],
5773                        skipped_segments: vec![],
5774                        skipped_positions: Vec::new(),
5775                    }],
5776                },
5777                AssembledGroup {
5778                    group_id: "SG4".to_string(),
5779                    repetitions: vec![AssembledGroupInstance {
5780                        segments: vec![AssembledSegment {
5781                            tag: "IDE".to_string(),
5782                            elements: vec![vec!["24".to_string()], vec!["TX001".to_string()]],
5783                            mig_number: None,
5784                            segment_number: None,
5785                        }],
5786                        child_groups: vec![AssembledGroup {
5787                            group_id: "SG5".to_string(),
5788                            repetitions: vec![AssembledGroupInstance {
5789                                segments: vec![AssembledSegment {
5790                                    tag: "LOC".to_string(),
5791                                    elements: vec![
5792                                        vec!["Z16".to_string()],
5793                                        vec!["DE000111222333".to_string()],
5794                                    ],
5795                                    mig_number: None,
5796                                    segment_number: None,
5797                                }],
5798                                child_groups: vec![],
5799                                entry_mig_number: None,
5800                                variant_mig_numbers: vec![],
5801                                skipped_segments: vec![],
5802                                skipped_positions: Vec::new(),
5803                            }],
5804                        }],
5805                        entry_mig_number: None,
5806                        variant_mig_numbers: vec![],
5807                        skipped_segments: vec![],
5808                        skipped_positions: Vec::new(),
5809                    }],
5810                },
5811            ],
5812            post_group_start: 2,
5813            inter_group_segments: std::collections::BTreeMap::new(),
5814        };
5815
5816        // Empty message engine (no message-level defs for this test)
5817        let msg_engine = MappingEngine::from_definitions(vec![]);
5818
5819        // Transaction defs
5820        let mut tx_fields: IndexMap<String, FieldMapping> = IndexMap::new();
5821        tx_fields.insert(
5822            "ide.1".to_string(),
5823            FieldMapping::Simple("vorgangId".to_string()),
5824        );
5825        let mut malo_fields: IndexMap<String, FieldMapping> = IndexMap::new();
5826        malo_fields.insert(
5827            "loc.1".to_string(),
5828            FieldMapping::Simple("marktlokationsId".to_string()),
5829        );
5830
5831        let tx_engine = MappingEngine::from_definitions(vec![
5832            MappingDefinition {
5833                meta: MappingMeta {
5834                    entity: "Prozessdaten".to_string(),
5835                    bo4e_type: "Prozessdaten".to_string(),
5836                    source_group: "SG4".to_string(),
5837                    source_path: None,
5838                    discriminator: None,
5839                    repeat_on_tag: None,
5840                    parent_field: None,
5841                    target_list: None,
5842                    order: None,
5843                },
5844                fields: tx_fields,
5845                complex_handlers: None,
5846            },
5847            MappingDefinition {
5848                meta: MappingMeta {
5849                    entity: "Marktlokation".to_string(),
5850                    bo4e_type: "Marktlokation".to_string(),
5851                    source_group: "SG4.SG5".to_string(),
5852                    source_path: None,
5853                    discriminator: None,
5854                    repeat_on_tag: None,
5855                    parent_field: None,
5856                    target_list: None,
5857                    order: None,
5858                },
5859                fields: malo_fields,
5860                complex_handlers: None,
5861            },
5862        ]);
5863
5864        let result = MappingEngine::map_interchange(&msg_engine, &tx_engine, &tree, "SG4", true);
5865
5866        assert_eq!(result.transaktionen.len(), 1);
5867        assert_eq!(
5868            result.transaktionen[0].transaktionsdaten["vorgangId"]
5869                .as_str()
5870                .unwrap(),
5871            "TX001"
5872        );
5873        // Marktlokation (SG4.SG5) stays top-level — SG4 IS the transaction root,
5874        // so Marktlokation is a peer of Prozessdaten, not a child of it.
5875        assert_eq!(
5876            result.transaktionen[0].stammdaten["marktlokation"]["marktlokationsId"]
5877                .as_str()
5878                .unwrap(),
5879            "DE000111222333"
5880        );
5881    }
5882
5883    #[test]
5884    fn test_map_reverse_pads_intermediate_empty_elements() {
5885        // NAD+Z09+++Muster:Max — positions 0 and 3 populated, 1 and 2 should become [""]
5886        let mut fields = IndexMap::new();
5887        fields.insert(
5888            "nad.0".to_string(),
5889            FieldMapping::Structured(StructuredFieldMapping {
5890                target: String::new(),
5891                transform: None,
5892                when: None,
5893                default: Some("Z09".to_string()),
5894                enum_map: None,
5895                code_list: None,
5896                also_code_list: None,
5897                when_filled: None,
5898                also_target: None,
5899                also_enum_map: None,
5900            }),
5901        );
5902        fields.insert(
5903            "nad.3.0".to_string(),
5904            FieldMapping::Simple("name".to_string()),
5905        );
5906        fields.insert(
5907            "nad.3.1".to_string(),
5908            FieldMapping::Simple("vorname".to_string()),
5909        );
5910
5911        let def = make_def(fields);
5912        let engine = MappingEngine::from_definitions(vec![]);
5913
5914        let bo4e = serde_json::json!({
5915            "name": "Muster",
5916            "vorname": "Max"
5917        });
5918
5919        let instance = engine.map_reverse(&bo4e, &def);
5920        assert_eq!(instance.segments.len(), 1);
5921
5922        let nad = &instance.segments[0];
5923        assert_eq!(nad.tag, "NAD");
5924        assert_eq!(nad.elements.len(), 4);
5925        assert_eq!(nad.elements[0], vec!["Z09"]);
5926        // Intermediate positions 1 and 2 should be padded to [""]
5927        assert_eq!(nad.elements[1], vec![""]);
5928        assert_eq!(nad.elements[2], vec![""]);
5929        assert_eq!(nad.elements[3][0], "Muster");
5930        assert_eq!(nad.elements[3][1], "Max");
5931    }
5932
5933    #[test]
5934    fn test_map_reverse_no_padding_when_contiguous() {
5935        // DTM+92:20250531:303 — all three components in element 0, no gaps
5936        let mut fields = IndexMap::new();
5937        fields.insert(
5938            "dtm.0.0".to_string(),
5939            FieldMapping::Structured(StructuredFieldMapping {
5940                target: String::new(),
5941                transform: None,
5942                when: None,
5943                default: Some("92".to_string()),
5944                enum_map: None,
5945                code_list: None,
5946                also_code_list: None,
5947                when_filled: None,
5948                also_target: None,
5949                also_enum_map: None,
5950            }),
5951        );
5952        fields.insert(
5953            "dtm.0.1".to_string(),
5954            FieldMapping::Simple("value".to_string()),
5955        );
5956        fields.insert(
5957            "dtm.0.2".to_string(),
5958            FieldMapping::Structured(StructuredFieldMapping {
5959                target: String::new(),
5960                transform: None,
5961                when: None,
5962                default: Some("303".to_string()),
5963                enum_map: None,
5964                code_list: None,
5965                also_code_list: None,
5966                when_filled: None,
5967                also_target: None,
5968                also_enum_map: None,
5969            }),
5970        );
5971
5972        let def = make_def(fields);
5973        let engine = MappingEngine::from_definitions(vec![]);
5974
5975        let bo4e = serde_json::json!({ "value": "20250531" });
5976
5977        let instance = engine.map_reverse(&bo4e, &def);
5978        let dtm = &instance.segments[0];
5979        // Single element with 3 components — no intermediate padding needed
5980        assert_eq!(dtm.elements.len(), 1);
5981        assert_eq!(dtm.elements[0], vec!["92", "20250531", "303"]);
5982    }
5983
5984    #[test]
5985    fn test_map_message_level_extracts_sg2_only() {
5986        use mig_assembly::assembler::*;
5987
5988        // Build a tree with SG2 (message-level) and SG4 (transaction-level)
5989        let tree = AssembledTree {
5990            segments: vec![
5991                AssembledSegment {
5992                    tag: "UNH".to_string(),
5993                    elements: vec![vec!["001".to_string()]],
5994                    mig_number: None,
5995                    segment_number: None,
5996                },
5997                AssembledSegment {
5998                    tag: "BGM".to_string(),
5999                    elements: vec![vec!["E01".to_string()]],
6000                    mig_number: None,
6001                    segment_number: None,
6002                },
6003            ],
6004            groups: vec![
6005                AssembledGroup {
6006                    group_id: "SG2".to_string(),
6007                    repetitions: vec![AssembledGroupInstance {
6008                        segments: vec![AssembledSegment {
6009                            tag: "NAD".to_string(),
6010                            elements: vec![vec!["MS".to_string()], vec!["9900123".to_string()]],
6011                            mig_number: None,
6012                            segment_number: None,
6013                        }],
6014                        child_groups: vec![],
6015                        entry_mig_number: None,
6016                        variant_mig_numbers: vec![],
6017                        skipped_segments: vec![],
6018                        skipped_positions: Vec::new(),
6019                    }],
6020                },
6021                AssembledGroup {
6022                    group_id: "SG4".to_string(),
6023                    repetitions: vec![AssembledGroupInstance {
6024                        segments: vec![AssembledSegment {
6025                            tag: "IDE".to_string(),
6026                            elements: vec![vec!["24".to_string()], vec!["TX001".to_string()]],
6027                            mig_number: None,
6028                            segment_number: None,
6029                        }],
6030                        child_groups: vec![],
6031                        entry_mig_number: None,
6032                        variant_mig_numbers: vec![],
6033                        skipped_segments: vec![],
6034                        skipped_positions: Vec::new(),
6035                    }],
6036                },
6037            ],
6038            post_group_start: 2,
6039            inter_group_segments: std::collections::BTreeMap::new(),
6040        };
6041
6042        // Message-level definition maps SG2
6043        let mut msg_fields: IndexMap<String, FieldMapping> = IndexMap::new();
6044        msg_fields.insert(
6045            "nad.0".to_string(),
6046            FieldMapping::Simple("marktrolle".to_string()),
6047        );
6048        msg_fields.insert(
6049            "nad.1".to_string(),
6050            FieldMapping::Simple("rollencodenummer".to_string()),
6051        );
6052        let msg_def = MappingDefinition {
6053            meta: MappingMeta {
6054                entity: "Marktteilnehmer".to_string(),
6055                bo4e_type: "Marktteilnehmer".to_string(),
6056                source_group: "SG2".to_string(),
6057                source_path: None,
6058                discriminator: None,
6059                repeat_on_tag: None,
6060                parent_field: None,
6061                target_list: None,
6062                order: None,
6063            },
6064            fields: msg_fields,
6065            complex_handlers: None,
6066        };
6067
6068        let engine = MappingEngine::from_definitions(vec![msg_def.clone()]);
6069        let result = engine.map_all_forward(&tree);
6070
6071        // Should contain Marktteilnehmer from SG2
6072        assert!(result.get("marktteilnehmer").is_some());
6073        let mt = &result["marktteilnehmer"];
6074        assert_eq!(mt["marktrolle"].as_str().unwrap(), "MS");
6075        assert_eq!(mt["rollencodenummer"].as_str().unwrap(), "9900123");
6076    }
6077
6078    #[test]
6079    fn test_map_transaction_scoped_to_sg4_instance() {
6080        use mig_assembly::assembler::*;
6081
6082        // Build a tree with SG4 containing SG5 (LOC+Z16)
6083        let tree = AssembledTree {
6084            segments: vec![
6085                AssembledSegment {
6086                    tag: "UNH".to_string(),
6087                    elements: vec![vec!["001".to_string()]],
6088                    mig_number: None,
6089                    segment_number: None,
6090                },
6091                AssembledSegment {
6092                    tag: "BGM".to_string(),
6093                    elements: vec![vec!["E01".to_string()]],
6094                    mig_number: None,
6095                    segment_number: None,
6096                },
6097            ],
6098            groups: vec![AssembledGroup {
6099                group_id: "SG4".to_string(),
6100                repetitions: vec![AssembledGroupInstance {
6101                    segments: vec![AssembledSegment {
6102                        tag: "IDE".to_string(),
6103                        elements: vec![vec!["24".to_string()], vec!["TX001".to_string()]],
6104                        mig_number: None,
6105                        segment_number: None,
6106                    }],
6107                    child_groups: vec![AssembledGroup {
6108                        group_id: "SG5".to_string(),
6109                        repetitions: vec![AssembledGroupInstance {
6110                            segments: vec![AssembledSegment {
6111                                tag: "LOC".to_string(),
6112                                elements: vec![
6113                                    vec!["Z16".to_string()],
6114                                    vec!["DE000111222333".to_string()],
6115                                ],
6116                                mig_number: None,
6117                                segment_number: None,
6118                            }],
6119                            child_groups: vec![],
6120                            entry_mig_number: None,
6121                            variant_mig_numbers: vec![],
6122                            skipped_segments: vec![],
6123                            skipped_positions: Vec::new(),
6124                        }],
6125                    }],
6126                    entry_mig_number: None,
6127                    variant_mig_numbers: vec![],
6128                    skipped_segments: vec![],
6129                    skipped_positions: Vec::new(),
6130                }],
6131            }],
6132            post_group_start: 2,
6133            inter_group_segments: std::collections::BTreeMap::new(),
6134        };
6135
6136        // Transaction-level definitions: prozessdaten (root of SG4) + marktlokation (SG5)
6137        let mut proz_fields: IndexMap<String, FieldMapping> = IndexMap::new();
6138        proz_fields.insert(
6139            "ide.1".to_string(),
6140            FieldMapping::Simple("vorgangId".to_string()),
6141        );
6142        let proz_def = MappingDefinition {
6143            meta: MappingMeta {
6144                entity: "Prozessdaten".to_string(),
6145                bo4e_type: "Prozessdaten".to_string(),
6146                source_group: "".to_string(), // Root-level within transaction sub-tree
6147                source_path: None,
6148                discriminator: None,
6149                repeat_on_tag: None,
6150                parent_field: None,
6151                target_list: None,
6152                order: None,
6153            },
6154            fields: proz_fields,
6155            complex_handlers: None,
6156        };
6157
6158        let mut malo_fields: IndexMap<String, FieldMapping> = IndexMap::new();
6159        malo_fields.insert(
6160            "loc.1".to_string(),
6161            FieldMapping::Simple("marktlokationsId".to_string()),
6162        );
6163        let malo_def = MappingDefinition {
6164            meta: MappingMeta {
6165                entity: "Marktlokation".to_string(),
6166                bo4e_type: "Marktlokation".to_string(),
6167                source_group: "SG5".to_string(), // Relative to SG4, not "SG4.SG5"
6168                source_path: None,
6169                discriminator: None,
6170                repeat_on_tag: None,
6171                parent_field: None,
6172                target_list: None,
6173                order: None,
6174            },
6175            fields: malo_fields,
6176            complex_handlers: None,
6177        };
6178
6179        let tx_engine = MappingEngine::from_definitions(vec![proz_def, malo_def]);
6180
6181        // Scope to the SG4 instance and map
6182        let sg4 = &tree.groups[0]; // SG4 group
6183        let sg4_instance = &sg4.repetitions[0];
6184        let sub_tree = sg4_instance.as_assembled_tree();
6185
6186        let result = tx_engine.map_all_forward(&sub_tree);
6187
6188        // Should contain Prozessdaten from SG4 root segments
6189        assert_eq!(
6190            result["prozessdaten"]["vorgangId"].as_str().unwrap(),
6191            "TX001"
6192        );
6193
6194        // Should contain Marktlokation from SG5 within SG4
6195        assert_eq!(
6196            result["marktlokation"]["marktlokationsId"]
6197                .as_str()
6198                .unwrap(),
6199            "DE000111222333"
6200        );
6201    }
6202
6203    #[test]
6204    fn test_map_interchange_produces_full_hierarchy() {
6205        use mig_assembly::assembler::*;
6206
6207        // Build a tree with SG2 (message-level) and SG4 with two repetitions (two transactions)
6208        let tree = AssembledTree {
6209            segments: vec![
6210                AssembledSegment {
6211                    tag: "UNH".to_string(),
6212                    elements: vec![vec!["001".to_string()]],
6213                    mig_number: None,
6214                    segment_number: None,
6215                },
6216                AssembledSegment {
6217                    tag: "BGM".to_string(),
6218                    elements: vec![vec!["E01".to_string()]],
6219                    mig_number: None,
6220                    segment_number: None,
6221                },
6222            ],
6223            groups: vec![
6224                AssembledGroup {
6225                    group_id: "SG2".to_string(),
6226                    repetitions: vec![AssembledGroupInstance {
6227                        segments: vec![AssembledSegment {
6228                            tag: "NAD".to_string(),
6229                            elements: vec![vec!["MS".to_string()], vec!["9900123".to_string()]],
6230                            mig_number: None,
6231                            segment_number: None,
6232                        }],
6233                        child_groups: vec![],
6234                        entry_mig_number: None,
6235                        variant_mig_numbers: vec![],
6236                        skipped_segments: vec![],
6237                        skipped_positions: Vec::new(),
6238                    }],
6239                },
6240                AssembledGroup {
6241                    group_id: "SG4".to_string(),
6242                    repetitions: vec![
6243                        AssembledGroupInstance {
6244                            segments: vec![AssembledSegment {
6245                                tag: "IDE".to_string(),
6246                                elements: vec![vec!["24".to_string()], vec!["TX001".to_string()]],
6247                                mig_number: None,
6248                                segment_number: None,
6249                            }],
6250                            child_groups: vec![],
6251                            entry_mig_number: None,
6252                            variant_mig_numbers: vec![],
6253                            skipped_segments: vec![],
6254                            skipped_positions: Vec::new(),
6255                        },
6256                        AssembledGroupInstance {
6257                            segments: vec![AssembledSegment {
6258                                tag: "IDE".to_string(),
6259                                elements: vec![vec!["24".to_string()], vec!["TX002".to_string()]],
6260                                mig_number: None,
6261                                segment_number: None,
6262                            }],
6263                            child_groups: vec![],
6264                            entry_mig_number: None,
6265                            variant_mig_numbers: vec![],
6266                            skipped_segments: vec![],
6267                            skipped_positions: Vec::new(),
6268                        },
6269                    ],
6270                },
6271            ],
6272            post_group_start: 2,
6273            inter_group_segments: std::collections::BTreeMap::new(),
6274        };
6275
6276        // Message-level definitions
6277        let mut msg_fields: IndexMap<String, FieldMapping> = IndexMap::new();
6278        msg_fields.insert(
6279            "nad.0".to_string(),
6280            FieldMapping::Simple("marktrolle".to_string()),
6281        );
6282        let msg_defs = vec![MappingDefinition {
6283            meta: MappingMeta {
6284                entity: "Marktteilnehmer".to_string(),
6285                bo4e_type: "Marktteilnehmer".to_string(),
6286                source_group: "SG2".to_string(),
6287                source_path: None,
6288                discriminator: None,
6289                repeat_on_tag: None,
6290                parent_field: None,
6291                target_list: None,
6292                order: None,
6293            },
6294            fields: msg_fields,
6295            complex_handlers: None,
6296        }];
6297
6298        // Transaction-level definitions (source_group includes SG4 prefix)
6299        let mut tx_fields: IndexMap<String, FieldMapping> = IndexMap::new();
6300        tx_fields.insert(
6301            "ide.1".to_string(),
6302            FieldMapping::Simple("vorgangId".to_string()),
6303        );
6304        let tx_defs = vec![MappingDefinition {
6305            meta: MappingMeta {
6306                entity: "Prozessdaten".to_string(),
6307                bo4e_type: "Prozessdaten".to_string(),
6308                source_group: "SG4".to_string(),
6309                source_path: None,
6310                discriminator: None,
6311                repeat_on_tag: None,
6312                parent_field: None,
6313                target_list: None,
6314                order: None,
6315            },
6316            fields: tx_fields,
6317            complex_handlers: None,
6318        }];
6319
6320        let msg_engine = MappingEngine::from_definitions(msg_defs);
6321        let tx_engine = MappingEngine::from_definitions(tx_defs);
6322
6323        let result = MappingEngine::map_interchange(&msg_engine, &tx_engine, &tree, "SG4", true);
6324
6325        // Message-level stammdaten
6326        assert!(result.stammdaten["marktteilnehmer"].is_object());
6327        assert_eq!(
6328            result.stammdaten["marktteilnehmer"]["marktrolle"]
6329                .as_str()
6330                .unwrap(),
6331            "MS"
6332        );
6333
6334        // Two transactions
6335        assert_eq!(result.transaktionen.len(), 2);
6336        assert_eq!(
6337            result.transaktionen[0].transaktionsdaten["vorgangId"]
6338                .as_str()
6339                .unwrap(),
6340            "TX001"
6341        );
6342        assert_eq!(
6343            result.transaktionen[1].transaktionsdaten["vorgangId"]
6344                .as_str()
6345                .unwrap(),
6346            "TX002"
6347        );
6348    }
6349
6350    #[test]
6351    fn test_map_reverse_with_segment_structure_pads_trailing() {
6352        // STS+7++E01 — position 0 and 2 populated, MIG says 5 elements
6353        let mut fields = IndexMap::new();
6354        fields.insert(
6355            "sts.0".to_string(),
6356            FieldMapping::Structured(StructuredFieldMapping {
6357                target: String::new(),
6358                transform: None,
6359                when: None,
6360                default: Some("7".to_string()),
6361                enum_map: None,
6362                code_list: None,
6363                also_code_list: None,
6364                when_filled: None,
6365                also_target: None,
6366                also_enum_map: None,
6367            }),
6368        );
6369        fields.insert(
6370            "sts.2".to_string(),
6371            FieldMapping::Simple("grund".to_string()),
6372        );
6373
6374        let def = make_def(fields);
6375
6376        // Build a SegmentStructure manually via BTreeMap
6377        let mut counts = std::collections::BTreeMap::new();
6378        counts.insert("STS".to_string(), 5usize);
6379        let ss = SegmentStructure {
6380            element_counts: counts,
6381        };
6382
6383        let engine = MappingEngine::from_definitions(vec![]).with_segment_structure(ss);
6384
6385        let bo4e = serde_json::json!({ "grund": "E01" });
6386
6387        let instance = engine.map_reverse(&bo4e, &def);
6388        let sts = &instance.segments[0];
6389        // Should have 5 elements: pos 0 = ["7"], pos 1 = [""] (intermediate pad),
6390        // pos 2 = ["E01"], pos 3 = [""] (trailing pad), pos 4 = [""] (trailing pad)
6391        assert_eq!(sts.elements.len(), 5);
6392        assert_eq!(sts.elements[0], vec!["7"]);
6393        assert_eq!(sts.elements[1], vec![""]);
6394        assert_eq!(sts.elements[2], vec!["E01"]);
6395        assert_eq!(sts.elements[3], vec![""]);
6396        assert_eq!(sts.elements[4], vec![""]);
6397    }
6398
6399    #[test]
6400    fn test_resolve_child_relative_with_source_path() {
6401        let mut map: std::collections::HashMap<String, Vec<usize>> =
6402            std::collections::HashMap::new();
6403        map.insert("sg4.sg8_ze1".to_string(), vec![6]);
6404        map.insert("sg4.sg8_z98".to_string(), vec![0]);
6405
6406        // Child without explicit index → resolved from source_path
6407        assert_eq!(
6408            resolve_child_relative("SG8.SG10", Some("sg4.sg8_ze1.sg10"), &map, 0),
6409            "SG8:6.SG10"
6410        );
6411
6412        // Child with explicit index → kept as-is
6413        assert_eq!(
6414            resolve_child_relative("SG8:3.SG10", Some("sg4.sg8_ze1.sg10"), &map, 0),
6415            "SG8:3.SG10"
6416        );
6417
6418        // Source path not in map → kept as-is
6419        assert_eq!(
6420            resolve_child_relative("SG8.SG10", Some("sg4.sg8_unknown.sg10"), &map, 0),
6421            "SG8.SG10"
6422        );
6423
6424        // No source_path → kept as-is
6425        assert_eq!(
6426            resolve_child_relative("SG8.SG10", None, &map, 0),
6427            "SG8.SG10"
6428        );
6429
6430        // SG9 also works
6431        assert_eq!(
6432            resolve_child_relative("SG8.SG9", Some("sg4.sg8_z98.sg9"), &map, 0),
6433            "SG8:0.SG9"
6434        );
6435
6436        // Multi-rep parent: item_idx selects the correct parent rep
6437        map.insert("sg4.sg8_zf3".to_string(), vec![3, 4]);
6438        assert_eq!(
6439            resolve_child_relative("SG8.SG10", Some("sg4.sg8_zf3.sg10"), &map, 0),
6440            "SG8:3.SG10"
6441        );
6442        assert_eq!(
6443            resolve_child_relative("SG8.SG10", Some("sg4.sg8_zf3.sg10"), &map, 1),
6444            "SG8:4.SG10"
6445        );
6446    }
6447
6448    #[test]
6449    fn test_place_in_groups_returns_rep_index() {
6450        let mut groups: Vec<AssembledGroup> = Vec::new();
6451
6452        // Append (no index) → returns position 0
6453        let instance = AssembledGroupInstance {
6454            segments: vec![],
6455            child_groups: vec![],
6456            entry_mig_number: None,
6457            variant_mig_numbers: vec![],
6458            skipped_segments: vec![],
6459            skipped_positions: Vec::new(),
6460        };
6461        assert_eq!(place_in_groups(&mut groups, "SG8", instance), 0);
6462
6463        // Append again → returns position 1
6464        let instance = AssembledGroupInstance {
6465            segments: vec![],
6466            child_groups: vec![],
6467            entry_mig_number: None,
6468            variant_mig_numbers: vec![],
6469            skipped_segments: vec![],
6470            skipped_positions: Vec::new(),
6471        };
6472        assert_eq!(place_in_groups(&mut groups, "SG8", instance), 1);
6473
6474        // Explicit index → returns that index
6475        let instance = AssembledGroupInstance {
6476            segments: vec![],
6477            child_groups: vec![],
6478            entry_mig_number: None,
6479            variant_mig_numbers: vec![],
6480            skipped_segments: vec![],
6481            skipped_positions: Vec::new(),
6482        };
6483        assert_eq!(place_in_groups(&mut groups, "SG8:5", instance), 5);
6484    }
6485
6486    #[test]
6487    fn test_resolve_by_source_path() {
6488        use mig_assembly::assembler::*;
6489
6490        // Build a tree: SG4[0] → SG8 with two reps (Z98 and ZD7) → each has SG10
6491        let tree = AssembledTree {
6492            segments: vec![],
6493            groups: vec![AssembledGroup {
6494                group_id: "SG4".to_string(),
6495                repetitions: vec![AssembledGroupInstance {
6496                    segments: vec![],
6497                    child_groups: vec![AssembledGroup {
6498                        group_id: "SG8".to_string(),
6499                        repetitions: vec![
6500                            AssembledGroupInstance {
6501                                segments: vec![AssembledSegment {
6502                                    tag: "SEQ".to_string(),
6503                                    elements: vec![vec!["Z98".to_string()]],
6504                                    mig_number: None,
6505                                    segment_number: None,
6506                                }],
6507                                child_groups: vec![AssembledGroup {
6508                                    group_id: "SG10".to_string(),
6509                                    repetitions: vec![AssembledGroupInstance {
6510                                        segments: vec![AssembledSegment {
6511                                            tag: "CCI".to_string(),
6512                                            elements: vec![vec![], vec![], vec!["ZB3".to_string()]],
6513                                            mig_number: None,
6514                                            segment_number: None,
6515                                        }],
6516                                        child_groups: vec![],
6517                                        entry_mig_number: None,
6518                                        variant_mig_numbers: vec![],
6519                                        skipped_segments: vec![],
6520                                        skipped_positions: Vec::new(),
6521                                    }],
6522                                }],
6523                                entry_mig_number: None,
6524                                variant_mig_numbers: vec![],
6525                                skipped_segments: vec![],
6526                                skipped_positions: Vec::new(),
6527                            },
6528                            AssembledGroupInstance {
6529                                segments: vec![AssembledSegment {
6530                                    tag: "SEQ".to_string(),
6531                                    elements: vec![vec!["ZD7".to_string()]],
6532                                    mig_number: None,
6533                                    segment_number: None,
6534                                }],
6535                                child_groups: vec![AssembledGroup {
6536                                    group_id: "SG10".to_string(),
6537                                    repetitions: vec![AssembledGroupInstance {
6538                                        segments: vec![AssembledSegment {
6539                                            tag: "CCI".to_string(),
6540                                            elements: vec![vec![], vec![], vec!["ZE6".to_string()]],
6541                                            mig_number: None,
6542                                            segment_number: None,
6543                                        }],
6544                                        child_groups: vec![],
6545                                        entry_mig_number: None,
6546                                        variant_mig_numbers: vec![],
6547                                        skipped_segments: vec![],
6548                                        skipped_positions: Vec::new(),
6549                                    }],
6550                                }],
6551                                entry_mig_number: None,
6552                                variant_mig_numbers: vec![],
6553                                skipped_segments: vec![],
6554                                skipped_positions: Vec::new(),
6555                            },
6556                        ],
6557                    }],
6558                    entry_mig_number: None,
6559                    variant_mig_numbers: vec![],
6560                    skipped_segments: vec![],
6561                    skipped_positions: Vec::new(),
6562                }],
6563            }],
6564            post_group_start: 0,
6565            inter_group_segments: std::collections::BTreeMap::new(),
6566        };
6567
6568        // Resolve SG10 under Z98
6569        let inst = MappingEngine::resolve_by_source_path(&tree, "sg4.sg8_z98.sg10");
6570        assert!(inst.is_some());
6571        assert_eq!(inst.unwrap().segments[0].elements[2][0], "ZB3");
6572
6573        // Resolve SG10 under ZD7
6574        let inst = MappingEngine::resolve_by_source_path(&tree, "sg4.sg8_zd7.sg10");
6575        assert!(inst.is_some());
6576        assert_eq!(inst.unwrap().segments[0].elements[2][0], "ZE6");
6577
6578        // Unknown qualifier → None
6579        let inst = MappingEngine::resolve_by_source_path(&tree, "sg4.sg8_zzz.sg10");
6580        assert!(inst.is_none());
6581
6582        // Without qualifier → first rep (Z98)
6583        let inst = MappingEngine::resolve_by_source_path(&tree, "sg4.sg8.sg10");
6584        assert!(inst.is_some());
6585        assert_eq!(inst.unwrap().segments[0].elements[2][0], "ZB3");
6586    }
6587
6588    #[test]
6589    fn test_parse_source_path_part() {
6590        assert_eq!(parse_source_path_part("sg4"), ("sg4", None));
6591        assert_eq!(parse_source_path_part("sg8_z98"), ("sg8", Some("z98")));
6592        assert_eq!(parse_source_path_part("sg10"), ("sg10", None));
6593        assert_eq!(parse_source_path_part("sg12_z04"), ("sg12", Some("z04")));
6594    }
6595
6596    #[test]
6597    fn test_has_source_path_qualifiers() {
6598        assert!(has_source_path_qualifiers("sg4.sg8_z98.sg10"));
6599        assert!(has_source_path_qualifiers("sg4.sg8_ze1.sg9"));
6600        assert!(!has_source_path_qualifiers("sg4.sg6"));
6601        assert!(!has_source_path_qualifiers("sg4.sg8.sg10"));
6602    }
6603
6604    #[test]
6605    fn test_extract_all_from_instance_collects_all_qualifier_matches() {
6606        use mig_assembly::assembler::*;
6607
6608        // Instance with 3 RFF+Z34 segments
6609        let instance = AssembledGroupInstance {
6610            segments: vec![
6611                AssembledSegment {
6612                    tag: "SEQ".to_string(),
6613                    elements: vec![vec!["ZD6".to_string()]],
6614                    mig_number: None,
6615                    segment_number: None,
6616                },
6617                AssembledSegment {
6618                    tag: "RFF".to_string(),
6619                    elements: vec![vec!["Z34".to_string(), "REF_A".to_string()]],
6620                    mig_number: None,
6621                    segment_number: None,
6622                },
6623                AssembledSegment {
6624                    tag: "RFF".to_string(),
6625                    elements: vec![vec!["Z34".to_string(), "REF_B".to_string()]],
6626                    mig_number: None,
6627                    segment_number: None,
6628                },
6629                AssembledSegment {
6630                    tag: "RFF".to_string(),
6631                    elements: vec![vec!["Z34".to_string(), "REF_C".to_string()]],
6632                    mig_number: None,
6633                    segment_number: None,
6634                },
6635                AssembledSegment {
6636                    tag: "RFF".to_string(),
6637                    elements: vec![vec!["Z35".to_string(), "OTHER".to_string()]],
6638                    mig_number: None,
6639                    segment_number: None,
6640                },
6641            ],
6642            child_groups: vec![],
6643            entry_mig_number: None,
6644            variant_mig_numbers: vec![],
6645            skipped_segments: vec![],
6646            skipped_positions: Vec::new(),
6647        };
6648
6649        // Wildcard collect: rff[Z34,*] should collect all 3 RFF+Z34 values
6650        let all = MappingEngine::extract_all_from_instance(&instance, "rff[Z34,*].0.1");
6651        assert_eq!(all, vec!["REF_A", "REF_B", "REF_C"]);
6652
6653        // Non-wildcard still returns single value via extract_from_instance
6654        let single = MappingEngine::extract_from_instance(&instance, "rff[Z34].0.1");
6655        assert_eq!(single, Some("REF_A".to_string()));
6656
6657        let second = MappingEngine::extract_from_instance(&instance, "rff[Z34,1].0.1");
6658        assert_eq!(second, Some("REF_B".to_string()));
6659    }
6660}