Skip to main content

edifact_mapper/
mapper.rs

1//! High-level [`Mapper`] API for EDIFACT-to-BO4E conversion.
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5
6use mig_assembly::ConversionService;
7use mig_bo4e::engine::DataBundle;
8use mig_bo4e::MappingEngine;
9
10use crate::data_dir::DataDir;
11use crate::error::MapperError;
12
13/// Result of a BO4E mapping operation.
14pub struct Bo4eResult {
15    /// The PID (Pruefidentifikator) that was detected or specified.
16    pub pid: String,
17    /// The EDIFACT message type (e.g., "UTILMD", "MSCONS").
18    pub message_type: String,
19    /// The message variant (e.g., "UTILMD_Strom", "MSCONS").
20    pub variant: String,
21    /// The mapped BO4E JSON output.
22    pub bo4e: serde_json::Value,
23}
24
25/// High-level facade for bidirectional EDIFACT ↔ BO4E conversion.
26///
27/// Wraps [`DataBundle`] loading with lazy/eager initialization, and provides
28/// convenient accessors for [`ConversionService`] and [`MappingEngine`] instances.
29///
30/// # Inbound (EDIFACT → BO4E)
31///
32/// ```ignore
33/// use edifact_mapper::{DataDir, Mapper};
34///
35/// let mapper = Mapper::from_data_dir(DataDir::auto())?;
36///
37/// // Detect PID from raw EDIFACT (no upfront knowledge needed)
38/// let pid = mapper.detect_pid(edifact_str)?;
39///
40/// // Convert to typed BO4E interchange
41/// let interchange: DynamicInterchange =
42///     mapper.from_edifact(edifact_str, "FV2504", "UTILMD_Strom", &pid)?;
43/// ```
44///
45/// # Outbound (BO4E → EDIFACT)
46///
47/// ```ignore
48/// let edifact = mapper.to_edifact(
49///     &msg_stammdaten, &tx_stammdaten,
50///     "FV2504", "UTILMD_Strom", "55001",
51/// )?;
52/// ```
53///
54/// # Mid-level Access
55///
56/// ```ignore
57/// let cs = mapper.conversion_service("FV2504", "UTILMD_Strom")?;
58/// let engine = mapper.engine("FV2504", "UTILMD_Strom", "55001")?;
59/// ```
60/// A single entry returned by [`Mapper::list_pids`].
61#[derive(Debug, Clone)]
62pub struct PidListEntry {
63    pub fv: String,
64    pub variant: String,
65    pub pid: String,
66    pub beschreibung: String,
67}
68
69/// How [`Mapper::from_edifact_with`] writes code fields.
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
71pub enum CodeForm {
72    /// Through the rule's table: `NAD+Z65` → `"kundeDesLf"`. The canonical form,
73    /// and what [`Mapper::from_edifact`] writes. Names belong to the release
74    /// that wrote them.
75    #[default]
76    Names,
77    /// As on the wire: `NAD+Z65` → `"Z65"`, stable across releases. Each
78    /// element is written once — no `also_target` field is derived from it.
79    /// [`Mapper::to_edifact`] accepts it and renders the same message.
80    Raw,
81}
82
83/// Options for [`Mapper::from_edifact_with`].
84#[derive(Debug, Clone, Default)]
85pub struct FromEdifactOptions {
86    /// How code fields are written.
87    pub codes: CodeForm,
88}
89
90pub struct Mapper {
91    data_dir: DataDir,
92    bundles: Mutex<HashMap<String, DataBundle>>,
93}
94
95/// Read one caller-supplied transaction into a [`mig_bo4e::model::MappedTransaktion`].
96///
97/// Accepts both shapes. A `{transaktionsdaten, stammdaten}` object is taken
98/// apart into the two halves; anything else is a bare entity map, which is what
99/// callers passed before the metadata slot existed — including one that already
100/// contains `prozessdaten` among its entities, where the engine's own reverse
101/// merge handles it.
102///
103/// Either key identifies the wrapper — see
104/// [`is_wrapped_transaktion`](mig_bo4e::model::is_wrapped_transaktion). A half
105/// that is absent stands in as empty, so a transaction of metadata alone keeps
106/// its metadata instead of being read as an entity map (issue #153).
107fn split_transaktion(tx: &serde_json::Value) -> mig_bo4e::model::MappedTransaktion {
108    let (transaktionsdaten, stammdaten) = if mig_bo4e::model::is_wrapped_transaktion(tx) {
109        (
110            tx.get("transaktionsdaten")
111                .cloned()
112                .unwrap_or(serde_json::Value::Null),
113            tx.get("stammdaten")
114                .cloned()
115                .unwrap_or_else(|| serde_json::Value::Object(Default::default())),
116        )
117    } else {
118        (serde_json::Value::Null, tx.clone())
119    };
120    mig_bo4e::model::MappedTransaktion {
121        transaktionsdaten,
122        stammdaten,
123        nesting_info: Default::default(),
124    }
125}
126
127impl Mapper {
128    /// Create a new `Mapper` from a [`DataDir`] configuration.
129    ///
130    /// Any format versions marked as [`eager`](DataDir::eager) are loaded immediately.
131    /// All others are loaded lazily on first access.
132    pub fn from_data_dir(data_dir: DataDir) -> Result<Self, MapperError> {
133        let mapper = Self {
134            data_dir,
135            bundles: Mutex::new(HashMap::new()),
136        };
137        let eager_fvs: Vec<String> = mapper.data_dir.eager_fvs().to_vec();
138        for fv in &eager_fvs {
139            mapper.ensure_bundle_loaded(fv)?;
140        }
141        Ok(mapper)
142    }
143
144    /// Ensure that the bundle for `fv` is loaded into memory.
145    fn ensure_bundle_loaded(&self, fv: &str) -> Result<(), MapperError> {
146        let mut bundles = self.bundles.lock().unwrap();
147        if bundles.contains_key(fv) {
148            return Ok(());
149        }
150        let path = self.data_dir.bundle_path(fv);
151        if !path.exists() {
152            return Err(MapperError::BundleNotFound { fv: fv.to_string() });
153        }
154        let bundle = DataBundle::load(&path)?;
155        // `DataBundle::load` has already checked the serialisation format.
156        // That says the file parses, not that its mappings belong with this
157        // crate — the check that would have caught #158.
158        let expected = DataBundle::PRODUCING_VERSION;
159        if !self.data_dir.allows_bundle_from_other_release()
160            && bundle.built_by.as_deref() != Some(expected)
161        {
162            return Err(MapperError::BundleFromOtherRelease {
163                fv: fv.to_string(),
164                built_by: bundle.built_by.clone(),
165                expected: expected.to_string(),
166                path: path.display().to_string(),
167            });
168        }
169        bundles.insert(fv.to_string(), bundle);
170        Ok(())
171    }
172
173    /// Get a [`ConversionService`] for the given format version and variant.
174    ///
175    /// The service can tokenize EDIFACT input and assemble it into a MIG tree.
176    pub fn conversion_service(
177        &self,
178        fv: &str,
179        variant: &str,
180    ) -> Result<ConversionService, MapperError> {
181        self.ensure_bundle_loaded(fv)?;
182        let bundles = self.bundles.lock().unwrap();
183        let bundle = bundles.get(fv).unwrap();
184        let vc = bundle
185            .variant(variant)
186            .ok_or_else(|| MapperError::VariantNotFound {
187                fv: fv.to_string(),
188                variant: variant.to_string(),
189            })?;
190        let mig = vc
191            .mig_schema
192            .as_ref()
193            .ok_or_else(|| MapperError::VariantNotFound {
194                fv: fv.to_string(),
195                variant: format!("{variant} (no MIG schema in bundle)"),
196            })?;
197        Ok(ConversionService::from_mig(mig.clone()))
198    }
199
200    /// Get a [`MappingEngine`] for a specific PID within a format version and variant.
201    ///
202    /// The engine can convert between assembled MIG trees and BO4E JSON.
203    pub fn engine(&self, fv: &str, variant: &str, pid: &str) -> Result<MappingEngine, MapperError> {
204        self.ensure_bundle_loaded(fv)?;
205        let bundles = self.bundles.lock().unwrap();
206        let bundle = bundles.get(fv).unwrap();
207        let vc = bundle
208            .variant(variant)
209            .ok_or_else(|| MapperError::VariantNotFound {
210                fv: fv.to_string(),
211                variant: variant.to_string(),
212            })?;
213        let pid_key = format!("pid_{pid}");
214        let defs = vc
215            .combined_defs
216            .get(&pid_key)
217            .ok_or_else(|| MapperError::PidNotFound {
218                fv: fv.to_string(),
219                variant: variant.to_string(),
220                pid: pid.to_string(),
221            })?;
222        Ok(MappingEngine::from_definitions_with_code_lists(
223            std::sync::Arc::clone(&vc.code_lists),
224            defs.clone(),
225        ))
226    }
227
228    /// The PID's message-level mapping definitions (what its message engine
229    /// writes into the message's `stammdaten`).
230    pub(crate) fn message_definitions(
231        &self,
232        fv: &str,
233        variant: &str,
234        pid: &str,
235    ) -> Result<Vec<mig_bo4e::definition::MappingDefinition>, MapperError> {
236        self.ensure_bundle_loaded(fv)?;
237        let bundles = self.bundles.lock().unwrap();
238        let bundle = bundles.get(fv).unwrap();
239        let vc = bundle
240            .variant(variant)
241            .ok_or_else(|| MapperError::VariantNotFound {
242                fv: fv.to_string(),
243                variant: variant.to_string(),
244            })?;
245        if vc.tx_group(pid).is_none() {
246            return Err(MapperError::PidNotFound {
247                fv: fv.to_string(),
248                variant: variant.to_string(),
249                pid: pid.to_string(),
250            });
251        }
252        Ok(vc.msg_engine(pid).definitions().to_vec())
253    }
254
255    /// Return the [`PidRequirements`] for a specific PID within a format version and variant.
256    ///
257    /// Requirements describe every entity and field the PID expects, including
258    /// AHB status, cardinality, valid code values, and message vs transaction scope.
259    pub fn pid_requirements(
260        &self,
261        fv: &str,
262        variant: &str,
263        pid: &str,
264    ) -> Result<mig_bo4e::pid_requirements::PidRequirements, MapperError> {
265        self.ensure_bundle_loaded(fv)?;
266        let bundles = self.bundles.lock().unwrap();
267        let bundle = bundles.get(fv).unwrap();
268        let vc = bundle
269            .variant(variant)
270            .ok_or_else(|| MapperError::VariantNotFound {
271                fv: fv.to_string(),
272                variant: variant.to_string(),
273            })?;
274        let pid_key = format!("pid_{pid}");
275        vc.pid_requirements
276            .get(&pid_key)
277            .cloned()
278            .ok_or_else(|| MapperError::PidNotFound {
279                fv: fv.to_string(),
280                variant: variant.to_string(),
281                pid: pid.to_string(),
282            })
283    }
284
285    /// Return the PID-agnostic [`Bo4eCatalog`] for a format version.
286    ///
287    /// The catalog contains one entry per BO4E type (BO, COM, Enum) parsed from
288    /// `bo4e-german` source at compile-mappings time. Used by Stammdatenaufbau in
289    /// downstream services.
290    pub fn bo4e_catalog(
291        &self,
292        fv: &str,
293    ) -> Result<mig_bo4e::bo4e_catalog::Bo4eCatalog, MapperError> {
294        self.ensure_bundle_loaded(fv)?;
295        let bundles = self.bundles.lock().unwrap();
296        let bundle = bundles.get(fv).unwrap();
297        Ok(bundle.bo4e_catalog.clone())
298    }
299
300    /// List all PIDs available across all format versions found in the data directory.
301    ///
302    /// Scans for `edifact-data-{FV}.bin` files, loads each bundle, and returns
303    /// one entry per PID per variant. Results are sorted by PID.
304    pub fn list_pids(&self) -> Result<Vec<PidListEntry>, MapperError> {
305        let dir = self.data_dir.data_path();
306        let read_dir = std::fs::read_dir(dir).map_err(|_| MapperError::DataDirNotFound {
307            path: dir.display().to_string(),
308        })?;
309
310        let mut result = Vec::new();
311
312        for entry in read_dir.flatten() {
313            let path = entry.path();
314            if path.extension().is_some_and(|e| e == "bin") {
315                let stem = path
316                    .file_stem()
317                    .and_then(|s| s.to_str())
318                    .unwrap_or("")
319                    .to_string();
320                let fv = match stem.strip_prefix("edifact-data-") {
321                    Some(v) => v.to_string(),
322                    None => continue,
323                };
324                self.ensure_bundle_loaded(&fv)?;
325                let bundles = self.bundles.lock().unwrap();
326                if let Some(bundle) = bundles.get(&fv) {
327                    for (variant, vc) in &bundle.variants {
328                        for (pid_key, req) in &vc.pid_requirements {
329                            let pid = pid_key.strip_prefix("pid_").unwrap_or(pid_key).to_string();
330                            result.push(PidListEntry {
331                                fv: fv.clone(),
332                                variant: variant.clone(),
333                                pid,
334                                beschreibung: req.beschreibung.clone(),
335                            });
336                        }
337                    }
338                }
339            }
340        }
341
342        result.sort_by(|a, b| a.pid.cmp(&b.pid));
343        Ok(result)
344    }
345
346    /// Validate a BO4E JSON object against PID requirements.
347    ///
348    /// Returns a list of validation errors. Empty list = valid.
349    /// The `json` should be the transaction-level stammdaten (the entity map).
350    pub fn validate_pid(
351        &self,
352        json: &serde_json::Value,
353        fv: &str,
354        variant: &str,
355        pid: &str,
356    ) -> Result<Vec<mig_bo4e::PidValidationError>, MapperError> {
357        self.ensure_bundle_loaded(fv)?;
358        let bundles = self.bundles.lock().unwrap();
359        let bundle = bundles.get(fv).unwrap();
360        let vc = bundle
361            .variant(variant)
362            .ok_or_else(|| MapperError::VariantNotFound {
363                fv: fv.to_string(),
364                variant: variant.to_string(),
365            })?;
366        let pid_key = format!("pid_{pid}");
367        let requirements =
368            vc.pid_requirements
369                .get(&pid_key)
370                .ok_or_else(|| MapperError::PidNotFound {
371                    fv: fv.to_string(),
372                    variant: variant.to_string(),
373                    pid: pid.to_string(),
374                })?;
375
376        Ok(mig_bo4e::pid_validation::validate_pid_json(
377            json,
378            requirements,
379        ))
380    }
381
382    /// Validate a typed BO4E struct against PID requirements.
383    ///
384    /// Convenience wrapper that serializes the struct to JSON first.
385    /// Works with any `Pid*Interchange` or `Pid*MessageStammdaten` type.
386    ///
387    /// # Example
388    /// ```ignore
389    /// let interchange = build_55001_interchange();
390    /// let errors = mapper.validate_pid_struct(&interchange, "FV2504", "UTILMD_Strom", "55001")?;
391    /// assert!(errors.is_empty(), "Errors:\n{}", ValidationReport(errors));
392    /// ```
393    pub fn validate_pid_struct(
394        &self,
395        value: &impl serde::Serialize,
396        fv: &str,
397        variant: &str,
398        pid: &str,
399    ) -> Result<Vec<mig_bo4e::PidValidationError>, MapperError> {
400        let json = serde_json::to_value(value).map_err(|e| {
401            MapperError::Mapping(mig_bo4e::MappingError::TypeConversion(e.to_string()))
402        })?;
403        self.validate_pid(&json, fv, variant, pid)
404    }
405
406    /// Validate with AHB condition awareness.
407    ///
408    /// Reverse-maps the JSON to EDIFACT segments, evaluates AHB conditions,
409    /// and reports fields as required/optional based on the actual data present.
410    ///
411    /// Falls back to basic validation (without conditions) if no condition
412    /// evaluator is available for the given variant/format version combination.
413    pub fn validate_pid_with_conditions(
414        &self,
415        json: &serde_json::Value,
416        fv: &str,
417        variant: &str,
418        pid: &str,
419    ) -> Result<Vec<mig_bo4e::PidValidationError>, MapperError> {
420        self.ensure_bundle_loaded(fv)?;
421        let bundles = self.bundles.lock().unwrap();
422        let bundle = bundles.get(fv).unwrap();
423        let vc = bundle
424            .variant(variant)
425            .ok_or_else(|| MapperError::VariantNotFound {
426                fv: fv.to_string(),
427                variant: variant.to_string(),
428            })?;
429        let pid_key = format!("pid_{pid}");
430
431        let requirements =
432            vc.pid_requirements
433                .get(&pid_key)
434                .ok_or_else(|| MapperError::PidNotFound {
435                    fv: fv.to_string(),
436                    variant: variant.to_string(),
437                    pid: pid.to_string(),
438                })?;
439
440        // Try to get a condition evaluator for this variant
441        let evaluator = crate::evaluator_factory::create_evaluator(variant, fv);
442
443        if let Some(evaluator) = evaluator {
444            // Reverse-map JSON to EDIFACT segments for condition evaluation context
445            let defs = vc
446                .combined_defs
447                .get(&pid_key)
448                .ok_or_else(|| MapperError::PidNotFound {
449                    fv: fv.to_string(),
450                    variant: variant.to_string(),
451                    pid: pid.to_string(),
452                })?;
453            let engine = MappingEngine::from_definitions_with_code_lists(
454                std::sync::Arc::clone(&vc.code_lists),
455                defs.clone(),
456            );
457            let tree = engine.map_all_reverse(json, None);
458
459            // Convert AssembledTree to flat OwnedSegments for EvaluationContext
460            let segments = crate::tree_to_segments::tree_to_owned_segments(&tree);
461
462            // Evaluate each entity element in the group instance it becomes:
463            // "in dieser SG8" is its SG8, not any SG8 of the message.
464            let navigator = mig_assembly::navigator::AssembledTreeNavigator::new(&tree);
465            let scopes = crate::element_scopes::entity_element_scopes(&engine, json, &tree);
466            let nested = crate::element_scopes::nested_element_scopes(&engine, json, &tree);
467
468            // Validate with condition awareness
469            Ok(crate::evaluator_factory::validate_with_boxed_evaluator(
470                evaluator.as_ref(),
471                json,
472                requirements,
473                pid,
474                &segments,
475                Some((&navigator, &scopes, &nested)),
476            ))
477        } else {
478            // No evaluator available — fall back to basic validation
479            Ok(mig_bo4e::pid_validation::validate_pid_json_transaction(
480                json,
481                requirements,
482            ))
483        }
484    }
485
486    /// Convert BO4E JSON back to an EDIFACT string.
487    ///
488    /// Takes message-level stammdaten, a slice of per-transaction stammdaten,
489    /// and produces an EDIFACT message body (UNH through UNT content segments,
490    /// without UNB/UNZ interchange envelope).
491    ///
492    /// # Arguments
493    ///
494    /// * `msg_stammdaten` — message-level entities (e.g., Marktteilnehmer from SG2)
495    /// * `tx_stammdaten` — per-transaction entities (one per transaction/SG4 instance)
496    /// * `fv` — format version (e.g., "FV2504")
497    /// * `variant` — message variant (e.g., "UTILMD_Strom")
498    /// * `pid` — Pruefidentifikator (e.g., "55001")
499    ///
500    /// # Round-tripping output of [`from_edifact`](Self::from_edifact)
501    ///
502    /// `msg_stammdaten` is only half of what the forward direction produced.
503    /// The message header — `nachrichtentyp`, `nachrichtennummer`,
504    /// `erstellungsdatum`, i.e. the wire's `BGM` and `DTM+137` — is in
505    /// `nachrichtendaten`, not in `stammdaten`, so passing `stammdaten` alone
506    /// renders a body without its header and reports nothing (issue #158).
507    /// Use [`to_edifact_nachricht`](Self::to_edifact_nachricht), which takes
508    /// both halves.
509    ///
510    /// # Code fields: names or raw codes
511    ///
512    /// Where the guide gives a code list, [`from_edifact`](Self::from_edifact)
513    /// writes a code as its name (`NAD+Z65` → `"partnerrolle": "kundeDesLf"`);
514    /// the name is the canonical form. This method accepts either: a name is
515    /// written back as its code, and any other value — the raw code `"Z65"`
516    /// included — is written as it is, so both render the same message. No
517    /// code table has a code that is also one of its names, so the two cannot
518    /// be confused. Pinned by `tests/raw_codes_render_like_names.rs`.
519    ///
520    /// Names belong to the release that wrote them; codes do not. A release
521    /// may rename a code (to its AHB meaning) or start naming it, and a name
522    /// the current table no longer has is written as it is — onto the wire.
523    /// Store or replay raw codes across releases, or re-read the message with
524    /// the release that renders it. [`from_edifact_with`](Self::from_edifact_with)
525    /// with [`CodeForm::Raw`] reads them.
526    ///
527    /// # Example
528    ///
529    /// ```ignore
530    /// let edifact = mapper.to_edifact(
531    ///     &msg_json,
532    ///     &[tx_json],
533    ///     "FV2504",
534    ///     "UTILMD_Strom",
535    ///     "55001",
536    /// )?;
537    /// ```
538    ///
539    /// # Errors
540    ///
541    /// Besides lookup failures, returns [`MapperError::MissingGroupEntrySegment`]
542    /// when the BO4E fills some of a segment group's fields but not the one its
543    /// entry segment is built from — e.g. a `zaehler` with `geraeteNummer` but no
544    /// `zaehlertypMerkmal`, which would render SG10 `CAV` without `CCI`. Such a
545    /// message cannot be parsed back; its group content would be lost.
546    pub fn to_edifact(
547        &self,
548        msg_stammdaten: &serde_json::Value,
549        tx_stammdaten: &[serde_json::Value],
550        fv: &str,
551        variant: &str,
552        pid: &str,
553    ) -> Result<String, MapperError> {
554        self.render_message_body(
555            msg_stammdaten,
556            tx_stammdaten,
557            fv,
558            variant,
559            pid,
560            EntrySegmentCheck::Refuse,
561        )
562    }
563
564    /// Render one message body from a [`Nachricht`] as [`from_edifact`] produced it.
565    ///
566    /// The forward direction splits a message in two: the business objects go to
567    /// `stammdaten`, and the message header — `nachrichtentyp`,
568    /// `nachrichtennummer`, `erstellungsdatum`, which are the `BGM` and
569    /// `DTM+137` of the wire — goes to `nachrichtendaten` beside it.
570    /// [`to_edifact`] takes only the first half, so handing it `stammdaten`
571    /// alone renders a body without its header and says nothing (issue #158).
572    ///
573    /// This takes both, so a caller can give back what it was given:
574    ///
575    /// ```ignore
576    /// let interchange = mapper.from_edifact::<Value, Value>(&edifact, fv, variant, pid)?;
577    /// let body = mapper.to_edifact_nachricht(&interchange.nachrichten[0], fv, variant, pid)?;
578    /// ```
579    ///
580    /// Only the body: the `UNB`/`UNH`/`UNT`/`UNZ` envelope is
581    /// [`to_edifact_interchange`](Self::to_edifact_interchange)'s job.
582    ///
583    /// # Errors
584    ///
585    /// As [`to_edifact`].
586    ///
587    /// [`to_edifact`]: Self::to_edifact
588    /// [`from_edifact`]: Self::from_edifact
589    /// [`Nachricht`]: mig_bo4e::model::Nachricht
590    pub fn to_edifact_nachricht(
591        &self,
592        nachricht: &mig_bo4e::model::Nachricht<serde_json::Value, serde_json::Value>,
593        fv: &str,
594        variant: &str,
595        pid: &str,
596    ) -> Result<String, MapperError> {
597        let mut msg_stammdaten = nachricht.stammdaten.clone();
598        mig_bo4e::model::restore_message_metadata(&mut msg_stammdaten, &nachricht.nachrichtendaten);
599        self.to_edifact(&msg_stammdaten, &nachricht.transaktionen, fv, variant, pid)
600    }
601
602    /// Reverse-map and render one message body. `check` decides what happens to
603    /// a group instance lacking its MIG entry segment: [`to_edifact`] refuses
604    /// it, [`validate_bo4e`] renders it so the validator can report the defect
605    /// as findings instead of failing the whole validation.
606    ///
607    /// [`to_edifact`]: Self::to_edifact
608    /// [`validate_bo4e`]: Self::validate_bo4e
609    fn render_message_body(
610        &self,
611        msg_stammdaten: &serde_json::Value,
612        tx_stammdaten: &[serde_json::Value],
613        fv: &str,
614        variant: &str,
615        pid: &str,
616        check: EntrySegmentCheck,
617    ) -> Result<String, MapperError> {
618        self.ensure_bundle_loaded(fv)?;
619        let bundles = self.bundles.lock().unwrap();
620        let bundle = bundles.get(fv).unwrap();
621        let vc = bundle
622            .variant(variant)
623            .ok_or_else(|| MapperError::VariantNotFound {
624                fv: fv.to_string(),
625                variant: variant.to_string(),
626            })?;
627
628        let tx_group = vc.tx_group(pid).ok_or_else(|| MapperError::PidNotFound {
629            fv: fv.to_string(),
630            variant: variant.to_string(),
631            pid: pid.to_string(),
632        })?;
633
634        let msg_engine = vc.msg_engine(pid);
635        let tx_engine = vc.tx_engine(pid).ok_or_else(|| MapperError::PidNotFound {
636            fv: fv.to_string(),
637            variant: variant.to_string(),
638            pid: pid.to_string(),
639        })?;
640
641        let filtered_mig = vc
642            .filtered_mig(pid)
643            .ok_or_else(|| MapperError::NoMigSchema {
644                fv: fv.to_string(),
645                variant: variant.to_string(),
646            })?;
647
648        // Build MappedMessage from the provided JSON
649        let transaktionen: Vec<mig_bo4e::model::MappedTransaktion> =
650            tx_stammdaten.iter().map(split_transaktion).collect();
651        let mapped = mig_bo4e::model::MappedMessage {
652            nachricht_meta: serde_json::Value::Null,
653            stammdaten: msg_stammdaten.clone(),
654            transaktionen,
655            nesting_info: Default::default(),
656            inter_group_segments: Default::default(),
657        };
658
659        // Reverse map → AssembledTree
660        let tree = MappingEngine::map_interchange_reverse(
661            &msg_engine,
662            &tx_engine,
663            &mapped,
664            tx_group,
665            Some(&filtered_mig),
666        );
667
668        // Disassemble → ordered segments. A group instance whose MIG entry
669        // segment is missing (e.g. SG10 with CAV but no CCI because the BO4E
670        // lacks the field the CCI is built from) renders EDIFACT that no
671        // receiver can assemble, so by default it is refused (#103).
672        let disassembler = mig_assembly::disassembler::Disassembler::new(&filtered_mig);
673        let checked = match check {
674            EntrySegmentCheck::Refuse => disassembler.disassemble_checked(&tree),
675            EntrySegmentCheck::Render => Ok(disassembler.disassemble(&tree)),
676        };
677        let segments = checked.map_err(|e| match e {
678            mig_assembly::AssemblyError::MissingGroupEntrySegment {
679                group_path,
680                source_path,
681                entry_segment,
682                present_segments,
683            } => {
684                let (entities, entry_fields) = describe_entry_segment_mappings(
685                    [msg_engine.definitions(), tx_engine.definitions()],
686                    &source_path,
687                    &entry_segment,
688                );
689                MapperError::MissingGroupEntrySegment(Box::new(
690                    crate::error::GroupEntrySegmentError {
691                        pid: pid.to_string(),
692                        group_path,
693                        source_path,
694                        entry_segment,
695                        present_segments,
696                        entities,
697                        entry_fields,
698                    },
699                ))
700            }
701            other => MapperError::Assembly(other),
702        })?;
703
704        // Render to EDIFACT string with default delimiters
705        let delimiters = edifact_primitives::EdifactDelimiters::default();
706        Ok(mig_assembly::renderer::render_edifact(
707            &segments,
708            &delimiters,
709        ))
710    }
711
712    /// Convert a typed BO4E struct to an EDIFACT string.
713    ///
714    /// Convenience wrapper that serializes the struct to JSON first.
715    /// The struct should serialize to the `Nachricht` shape:
716    /// `{ "stammdaten": {...}, "transaktionen": [{...}] }`
717    pub fn to_edifact_struct(
718        &self,
719        nachricht: &impl serde::Serialize,
720        fv: &str,
721        variant: &str,
722        pid: &str,
723    ) -> Result<String, MapperError> {
724        let json = serde_json::to_value(nachricht)
725            .map_err(|e| MapperError::Serialization(e.to_string()))?;
726
727        let msg_stammdaten = json
728            .get("stammdaten")
729            .cloned()
730            .unwrap_or(serde_json::Value::Object(Default::default()));
731
732        let tx_stammdaten: Vec<serde_json::Value> = json
733            .get("transaktionen")
734            .and_then(|v| v.as_array())
735            .cloned()
736            .unwrap_or_default();
737
738        self.to_edifact(&msg_stammdaten, &tx_stammdaten, fv, variant, pid)
739    }
740
741    /// Parse an EDIFACT interchange string into a typed PID interchange struct.
742    ///
743    /// Runs the full pipeline: tokenize → split messages → assemble → forward-map → deserialize.
744    /// The type parameters `M` and `T` are the message-level and transaction-level
745    /// stammdaten types from the generated PID module.
746    ///
747    /// # Example
748    ///
749    /// ```ignore
750    /// use bo4e_edifact_types::generated::fv2504::utilmd::pids::pid_55001::*;
751    ///
752    /// let interchange: Interchange<Pid55001MsgStammdaten, Pid55001TxStammdaten> =
753    ///     mapper.from_edifact(edifact_str, "FV2504", "UTILMD_Strom", "55001")?;
754    ///
755    /// let tx = &interchange.nachrichten[0].transaktionen[0];
756    /// println!("Vorgang: {}", tx.prozessdaten.vorgang_id);
757    /// ```
758    ///
759    /// Mapping is lossy for content the assembler cannot place: segments the
760    /// PID's AHB does not cover, and segments whose group lacks its entry segment
761    /// (e.g. SG10 `CAV` without `CCI`). They have no BO4E representation and are
762    /// dropped. The conversion still succeeds, so that everything else in the
763    /// message is available; each dropped segment is logged as a `tracing`
764    /// warning. Use [`from_edifact_with_diagnostics`] to inspect them in code
765    /// (e.g. to reject such messages).
766    ///
767    /// [`from_edifact_with_diagnostics`]: Self::from_edifact_with_diagnostics
768    pub fn from_edifact<M, T>(
769        &self,
770        edifact: &str,
771        fv: &str,
772        variant: &str,
773        pid: &str,
774    ) -> Result<mig_bo4e::model::Interchange<M, T>, MapperError>
775    where
776        M: serde::de::DeserializeOwned,
777        T: serde::de::DeserializeOwned,
778    {
779        let (interchange, diagnostics) =
780            self.from_edifact_with_diagnostics(edifact, fv, variant, pid)?;
781        // This signature has no room for diagnostics, and dropped content must
782        // not go unnoticed (#103): log it for callers that don't ask for it.
783        for d in &diagnostics {
784            tracing::warn!(
785                fv,
786                variant,
787                pid,
788                kind = ?d.kind,
789                segment = %d.segment_id,
790                position = d.position,
791                "from_edifact: {}",
792                d.message
793            );
794        }
795        Ok(interchange)
796    }
797
798    /// [`from_edifact`], plus the structure diagnostics raised while assembling.
799    ///
800    /// A non-empty diagnostic list does not mean the conversion failed — it means
801    /// the BO4E result does not represent everything the EDIFACT carried. In
802    /// particular [`SkippedUnknownSegment`] marks a segment outside the PID's AHB
803    /// that the assembler advanced past, and [`OrphanedGroupSegment`] a segment
804    /// the MIG defines but whose group's entry segment is missing; in both cases
805    /// its content is absent from the result.
806    ///
807    /// [`from_edifact`]: Self::from_edifact
808    /// [`SkippedUnknownSegment`]: mig_assembly::StructureDiagnosticKind::SkippedUnknownSegment
809    /// [`OrphanedGroupSegment`]: mig_assembly::StructureDiagnosticKind::OrphanedGroupSegment
810    pub fn from_edifact_with_diagnostics<M, T>(
811        &self,
812        edifact: &str,
813        fv: &str,
814        variant: &str,
815        pid: &str,
816    ) -> Result<
817        (
818            mig_bo4e::model::Interchange<M, T>,
819            Vec<mig_assembly::StructureDiagnostic>,
820        ),
821        MapperError,
822    >
823    where
824        M: serde::de::DeserializeOwned,
825        T: serde::de::DeserializeOwned,
826    {
827        self.from_edifact_with_options_and_diagnostics(
828            edifact,
829            fv,
830            variant,
831            pid,
832            &FromEdifactOptions::default(),
833        )
834    }
835
836    /// [`from_edifact`](Self::from_edifact) with [`FromEdifactOptions`] — e.g.
837    /// `CodeForm::Raw` to read codes as they stand on the wire.
838    ///
839    /// ```ignore
840    /// use edifact_mapper::{CodeForm, FromEdifactOptions};
841    /// let raw = FromEdifactOptions { codes: CodeForm::Raw };
842    /// let ic = mapper.from_edifact_with::<Value, Value>(&edifact, fv, variant, pid, &raw)?;
843    /// // "partnerrolle": "Z65" instead of "kundeDesLf"; to_edifact accepts it.
844    /// ```
845    pub fn from_edifact_with<M, T>(
846        &self,
847        edifact: &str,
848        fv: &str,
849        variant: &str,
850        pid: &str,
851        options: &FromEdifactOptions,
852    ) -> Result<mig_bo4e::model::Interchange<M, T>, MapperError>
853    where
854        M: serde::de::DeserializeOwned,
855        T: serde::de::DeserializeOwned,
856    {
857        let (interchange, diagnostics) =
858            self.from_edifact_with_options_and_diagnostics(edifact, fv, variant, pid, options)?;
859        for d in &diagnostics {
860            tracing::warn!(
861                fv,
862                variant,
863                pid,
864                kind = ?d.kind,
865                segment = %d.segment_id,
866                position = d.position,
867                "from_edifact: {}",
868                d.message
869            );
870        }
871        Ok(interchange)
872    }
873
874    /// [`from_edifact_with`](Self::from_edifact_with), plus the structure
875    /// diagnostics described on
876    /// [`from_edifact_with_diagnostics`](Self::from_edifact_with_diagnostics).
877    pub fn from_edifact_with_options_and_diagnostics<M, T>(
878        &self,
879        edifact: &str,
880        fv: &str,
881        variant: &str,
882        pid: &str,
883        options: &FromEdifactOptions,
884    ) -> Result<
885        (
886            mig_bo4e::model::Interchange<M, T>,
887            Vec<mig_assembly::StructureDiagnostic>,
888        ),
889        MapperError,
890    >
891    where
892        M: serde::de::DeserializeOwned,
893        T: serde::de::DeserializeOwned,
894    {
895        self.ensure_bundle_loaded(fv)?;
896        let bundles = self.bundles.lock().unwrap();
897        let bundle = bundles.get(fv).unwrap();
898        let vc = bundle
899            .variant(variant)
900            .ok_or_else(|| MapperError::VariantNotFound {
901                fv: fv.to_string(),
902                variant: variant.to_string(),
903            })?;
904
905        let tx_group = vc.tx_group(pid).ok_or_else(|| MapperError::PidNotFound {
906            fv: fv.to_string(),
907            variant: variant.to_string(),
908            pid: pid.to_string(),
909        })?;
910
911        let raw = options.codes == CodeForm::Raw;
912        let msg_engine = vc.msg_engine(pid).with_raw_codes(raw);
913        let tx_engine = vc
914            .tx_engine(pid)
915            .ok_or_else(|| MapperError::PidNotFound {
916                fv: fv.to_string(),
917                variant: variant.to_string(),
918                pid: pid.to_string(),
919            })?
920            .with_raw_codes(raw);
921
922        let filtered_mig = vc
923            .filtered_mig(pid)
924            .ok_or_else(|| MapperError::NoMigSchema {
925                fv: fv.to_string(),
926                variant: variant.to_string(),
927            })?;
928
929        // Tokenize → split → assemble. Same assembler config as the v2 `convert`
930        // route: `strict_code_matching` disambiguates merged sibling slots, and
931        // `skip_unknown_segments` keeps the cursor moving past AHB-foreign
932        // segments — without it the cursor stalls on the first one and the whole
933        // message tail is silently dropped from the BO4E result.
934        let svc = ConversionService::from_mig(filtered_mig);
935        let (chunks, trees, assembly_diagnostics) = svc
936            .convert_interchange_to_trees_with_diagnostics(
937                edifact,
938                mig_assembly::assembler::AssemblerConfig {
939                    strict_code_matching: true,
940                    skip_unknown_segments: true,
941                    ..Default::default()
942                },
943            )?;
944
945        let tree = trees.first().ok_or_else(|| {
946            MapperError::Assembly(mig_assembly::AssemblyError::ParseError(
947                "No messages in interchange".to_string(),
948            ))
949        })?;
950
951        // Extract envelope metadata
952        let interchangedaten = mig_bo4e::model::extract_interchangedaten(&chunks.envelope);
953        let msg_chunk = chunks.messages.first().ok_or_else(|| {
954            MapperError::Assembly(mig_assembly::AssemblyError::ParseError(
955                "No message chunks".to_string(),
956            ))
957        })?;
958        let nachrichtendaten = mig_bo4e::model::extract_message_header(&msg_chunk.unh);
959
960        // Forward-map to typed interchange
961        let interchange = MappingEngine::map_interchange_typed::<M, T>(
962            &msg_engine,
963            &tx_engine,
964            tree,
965            tx_group,
966            true,
967            nachrichtendaten,
968            interchangedaten,
969        )
970        .map_err(|e| MapperError::Serialization(e.to_string()))?;
971
972        Ok((interchange, assembly_diagnostics))
973    }
974
975    /// Detect the PID (Pruefidentifikator) from a raw EDIFACT interchange.
976    ///
977    /// Tokenizes the input, splits into messages, and extracts the PID from the
978    /// first message using the RFF+Z13 segment (primary) or BGM+STS fallback.
979    ///
980    /// This enables inbound message processing where the PID is not known upfront:
981    ///
982    /// ```ignore
983    /// let pid = mapper.detect_pid(edifact_str)?;
984    /// let interchange: MyType = mapper.from_edifact(edifact_str, "FV2504", "UTILMD_Strom", &pid)?;
985    /// ```
986    pub fn detect_pid(&self, edifact: &str) -> Result<String, MapperError> {
987        let segments = mig_assembly::tokenize::parse_to_segments(edifact.as_bytes())?;
988        let chunks = mig_assembly::split_messages(segments)?;
989        let msg_chunk = chunks.messages.first().ok_or_else(|| {
990            MapperError::Assembly(mig_assembly::AssemblyError::ParseError(
991                "No messages found in EDIFACT content".to_string(),
992            ))
993        })?;
994        let msg_segments = msg_chunk.message_segments();
995        mig_assembly::pid_detect::detect_pid(&msg_segments).map_err(MapperError::Assembly)
996    }
997
998    /// Validate raw EDIFACT against its AHB rules.
999    ///
1000    /// This is the same pipeline as the v2 API's `POST /api/v2/validate`
1001    /// (`run_validation`) — both call [`validate_edifact_message`] — exposed here
1002    /// as a library call so consumers (e.g. mako.hive) get full raw-EDIFACT
1003    /// validation without running the API server. Detects the PID, resolves the
1004    /// owning variant + its pre-built [`AhbWorkflow`] from the loaded bundle,
1005    /// assembles the message, and runs the shared validation core.
1006    ///
1007    /// Requires the bundle for `fv` to carry `pid_ahb_workflows` (baked in at
1008    /// compile-mappings). Returns [`MapperError::PidNotFound`] if no loaded variant
1009    /// has a workflow for the detected PID.
1010    ///
1011    /// [`validate_edifact_message`]: automapper_validation::validate_edifact_message
1012    /// [`AhbWorkflow`]: automapper_validation::AhbWorkflow
1013    pub fn validate_edifact(
1014        &self,
1015        edifact: &str,
1016        fv: &str,
1017        level: automapper_validation::ValidationLevel,
1018    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1019        self.validate_edifact_inner(edifact, fv, None, level)
1020    }
1021
1022    /// [`validate_edifact`], but validating against a PID the caller already knows.
1023    ///
1024    /// Use this when the PID comes from somewhere other than the message — a form,
1025    /// a route, a job definition. It skips PID detection, which only works for
1026    /// message types that carry the Prüfidentifikator in `RFF+Z13` (UTILMD); for
1027    /// ORDERS, MSCONS, IFTSTA and the rest, detection cannot recover a PID that the
1028    /// caller already has.
1029    ///
1030    /// [`validate_edifact`]: Self::validate_edifact
1031    pub fn validate_edifact_for_pid(
1032        &self,
1033        edifact: &str,
1034        fv: &str,
1035        variant: &str,
1036        pid: &str,
1037        level: automapper_validation::ValidationLevel,
1038    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1039        self.validate_edifact_inner(edifact, fv, Some((variant, pid)), level)
1040    }
1041
1042    fn validate_edifact_inner(
1043        &self,
1044        edifact: &str,
1045        fv: &str,
1046        known: Option<(&str, &str)>,
1047        level: automapper_validation::ValidationLevel,
1048    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1049        self.ensure_bundle_loaded(fv)?;
1050        let bundles = self.bundles.lock().unwrap();
1051        let bundle = bundles.get(fv).unwrap();
1052
1053        // Tokenize → split → first message (same as `detect_pid`).
1054        let segments = mig_assembly::tokenize::parse_to_segments(edifact.as_bytes())?;
1055        let chunks = mig_assembly::split_messages(segments)?;
1056        let msg_chunk = chunks.messages.first().ok_or_else(|| {
1057            MapperError::Assembly(mig_assembly::AssemblyError::ParseError(
1058                "No messages found in EDIFACT content".to_string(),
1059            ))
1060        })?;
1061
1062        // Resolve the PID: detect it when the caller doesn't know it, and resolve
1063        // the owning variant from the bundle. When the caller does know both (the
1064        // `validate_bo4e` path), take them as given — detection only works for
1065        // message types that carry the PID in RFF+Z13 (UTILMD), so re-deriving a
1066        // PID the caller already supplied would fail on ORDERS, MSCONS, IFTSTA, …
1067        let (pid, variant, vc) = match known {
1068            Some((variant, pid)) => {
1069                let vc = bundle
1070                    .variant(variant)
1071                    .ok_or_else(|| MapperError::VariantNotFound {
1072                        fv: fv.to_string(),
1073                        variant: variant.to_string(),
1074                    })?;
1075                (pid.to_string(), variant.to_string(), vc)
1076            }
1077            None => {
1078                let pid = mig_assembly::pid_detect::detect_pid(&msg_chunk.message_segments())
1079                    .map_err(MapperError::Assembly)?;
1080                let pid_key = format!("pid_{pid}");
1081                let (variant, vc) = bundle
1082                    .variants
1083                    .iter()
1084                    .find(|(_, vc)| vc.pid_ahb_workflows.contains_key(&pid_key))
1085                    .ok_or_else(|| MapperError::PidNotFound {
1086                        fv: fv.to_string(),
1087                        variant: "?".to_string(),
1088                        pid: pid.clone(),
1089                    })?;
1090                (pid, variant.clone(), vc)
1091            }
1092        };
1093        let pid_key = format!("pid_{pid}");
1094
1095        let workflow =
1096            vc.pid_ahb_workflows
1097                .get(&pid_key)
1098                .ok_or_else(|| MapperError::PidNotFound {
1099                    fv: fv.to_string(),
1100                    variant: variant.clone(),
1101                    pid: pid.clone(),
1102                })?;
1103        let filtered_mig = vc
1104            .filtered_mig(&pid)
1105            .ok_or_else(|| MapperError::NoMigSchema {
1106                fv: fv.to_string(),
1107                variant: variant.clone(),
1108            })?;
1109
1110        // Segments the validator sees: this message's body for the filtered MIG,
1111        // plus the interchange UNZ when the MIG covers it (e.g. MSCONS).
1112        let mut all_segments = msg_chunk.segments_for_mig(&filtered_mig);
1113        if filtered_mig.segments.iter().any(|s| s.id == "UNZ") {
1114            if let Some(unz) = &chunks.unz {
1115                all_segments.push(unz.clone());
1116            }
1117        }
1118
1119        // Same evaluator resolution + fallback the v2 route uses. The explicit
1120        // target type lets each arm coerce (Box<dyn> → Arc<dyn>; Arc<Concrete> →
1121        // Arc<dyn> unsize) — a `.map(Arc::from)` chain can't infer that.
1122        let evaluator: std::sync::Arc<dyn automapper_validation::ConditionEvaluator> =
1123            match crate::evaluator_factory::create_evaluator(&variant, fv) {
1124                Some(boxed) => std::sync::Arc::from(boxed),
1125                None => std::sync::Arc::new(
1126                    automapper_validation::UtilmdStromConditionEvaluatorFV2504::default(),
1127                ),
1128            };
1129        let external = automapper_validation::eval::NoOpExternalProvider;
1130
1131        let pid_mig = vc.pid_mig_unmerged(&pid);
1132        let mut report = automapper_validation::validate_edifact_message_with_structure(
1133            &all_segments,
1134            &filtered_mig,
1135            pid_mig.as_ref(),
1136            workflow,
1137            evaluator,
1138            &external,
1139            level,
1140        );
1141
1142        // Enrich findings with BO4E field paths so consumers can map the
1143        // segment-path findings back to the BO4E form (same enrichment the v2
1144        // `validate-bo4e` route applies). Sourced entirely from the bundle: the
1145        // combined mapping defs, the PID-filtered MIG, and a reverse resolver
1146        // built from the full MIG — no generated schema files needed.
1147        if let (Some(mig), Some(defs)) = (vc.mig_schema.as_ref(), vc.combined_defs.get(&pid_key)) {
1148            let reverse = mig_bo4e::path_resolver::ReversePathResolver::from_mig(mig);
1149            let field_index =
1150                mig_bo4e::Bo4eFieldIndex::build_with_resolver(defs, &filtered_mig, &reverse);
1151            report.enrich_bo4e_paths(|path, hint| field_index.resolve(path, hint));
1152        }
1153
1154        Ok(report)
1155    }
1156
1157    /// [`validate_bo4e`], for a whole message rather than its `stammdaten`.
1158    ///
1159    /// `validate_bo4e` sees only the business objects, so the message header
1160    /// reaches the rendered EDIFACT with `UNH` rebuilt from the variant's
1161    /// metadata alone. For the 53 Pruefidentifikatoren whose guide requires
1162    /// `UNH` 0068 or `S010`, that made the BO4E look as though it were missing
1163    /// a field it in fact carries — in `nachrichtendaten`, where this call
1164    /// reads it from (issue #166).
1165    ///
1166    /// Prefer this whenever the caller holds the message `from_edifact`
1167    /// produced. Everything else is as [`validate_bo4e`].
1168    ///
1169    /// [`validate_bo4e`]: Self::validate_bo4e
1170    pub fn validate_bo4e_nachricht(
1171        &self,
1172        nachricht: &mig_bo4e::model::Nachricht<serde_json::Value, serde_json::Value>,
1173        fv: &str,
1174        variant: &str,
1175        pid: &str,
1176        envelope: Option<&InterchangeEnvelope>,
1177        level: automapper_validation::ValidationLevel,
1178    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1179        // The forward pass moved the `Nachricht` entity out of `stammdaten`;
1180        // the reverse resolves definitions against the flat entity map, so it
1181        // has to go back before rendering.
1182        let mut msg_stammdaten = nachricht.stammdaten.clone();
1183        mig_bo4e::model::restore_message_metadata(&mut msg_stammdaten, &nachricht.nachrichtendaten);
1184
1185        let header = &nachricht.nachrichtendaten;
1186        self.validate_rendered(
1187            InterchangeMessage {
1188                message_ref: "1".to_string(),
1189                msg_stammdaten,
1190                tx_stammdaten: nachricht.transaktionen.clone(),
1191                fv: fv.to_string(),
1192                variant: variant.to_string(),
1193                pid: pid.to_string(),
1194                zuordnungsreferenz: header.zuordnungsreferenz.clone(),
1195                uebermittlungsfolgenummer: header.uebermittlungsfolgenummer.clone(),
1196                uebermittlungsabschnitt: header.uebermittlungsabschnitt,
1197            },
1198            fv,
1199            variant,
1200            pid,
1201            envelope,
1202            level,
1203        )
1204    }
1205
1206    /// Render one message to EDIFACT and validate it — the shared body of
1207    /// [`validate_bo4e`](Self::validate_bo4e) and
1208    /// [`validate_bo4e_nachricht`](Self::validate_bo4e_nachricht).
1209    fn validate_rendered(
1210        &self,
1211        message: InterchangeMessage,
1212        fv: &str,
1213        variant: &str,
1214        pid: &str,
1215        envelope: Option<&InterchangeEnvelope>,
1216        level: automapper_validation::ValidationLevel,
1217    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1218        let placeholder;
1219        let envelope = match envelope {
1220            Some(e) => e,
1221            None => {
1222                placeholder = InterchangeEnvelope {
1223                    sender: EdifactParty::bdew("9900000000001"),
1224                    receiver: EdifactParty::bdew("9900000000002"),
1225                    interchange_ref: "1".to_string(),
1226                };
1227                &placeholder
1228            }
1229        };
1230
1231        // Rendered without the entry-segment check `to_edifact_interchange`
1232        // applies: a group missing its entry segment is exactly the kind of
1233        // defect validation exists to report (as missing-field and structure
1234        // findings), so it must not abort the validation.
1235        let edifact = self.render_interchange(
1236            envelope,
1237            &[message],
1238            EntrySegmentCheck::Render,
1239            &EnvelopeOptions::default(),
1240        )?;
1241
1242        // The PID is given, not detected: for every message type but UTILMD the
1243        // rendered EDIFACT carries no RFF+Z13 to detect it from.
1244        self.validate_edifact_for_pid(&edifact, fv, variant, pid, level)
1245    }
1246
1247    /// Validate BO4E JSON against the AHB rules of its Prüfidentifikator.
1248    ///
1249    /// This is [`validate_edifact`] with a reverse-mapping front end: the BO4E
1250    /// input is rendered to a complete EDIFACT interchange
1251    /// ([`to_edifact_interchange`]) and that interchange is validated. Because it
1252    /// is literally the same call, the findings are the ones the EDIFACT
1253    /// validation reports for the message this BO4E describes — including the
1254    /// `bo4e_path` enrichment that points each finding back at the BO4E field it
1255    /// came from. Callers working in BO4E (forms, assistants) therefore do not
1256    /// need their own EDIFACT-path-to-BO4E-path translation.
1257    ///
1258    /// `envelope` fills UNB/UNZ. Pass `None` unless the message type's MIG covers
1259    /// the interchange envelope (e.g. MSCONS) — for the others the envelope is
1260    /// outside the AHB and a neutral placeholder is used.
1261    ///
1262    /// Two classes of finding cannot appear here, because the BO4E input has no
1263    /// counterpart for them: the UNT segment-count check (the trailer is
1264    /// regenerated) and skipped-unknown-segment diagnostics (segments outside the
1265    /// AHB have no BO4E representation).
1266    ///
1267    /// [`validate_edifact`]: Self::validate_edifact
1268    /// [`to_edifact_interchange`]: Self::to_edifact_interchange
1269    pub fn validate_bo4e(
1270        &self,
1271        msg_stammdaten: &serde_json::Value,
1272        tx_stammdaten: &[serde_json::Value],
1273        fv: &str,
1274        variant: &str,
1275        pid: &str,
1276        envelope: Option<&InterchangeEnvelope>,
1277        level: automapper_validation::ValidationLevel,
1278    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1279        self.validate_rendered(
1280            InterchangeMessage {
1281                message_ref: "1".to_string(),
1282                msg_stammdaten: msg_stammdaten.clone(),
1283                tx_stammdaten: tx_stammdaten.to_vec(),
1284                fv: fv.to_string(),
1285                variant: variant.to_string(),
1286                pid: pid.to_string(),
1287                ..Default::default()
1288            },
1289            fv,
1290            variant,
1291            pid,
1292            envelope,
1293            level,
1294        )
1295    }
1296
1297    /// Get the UNH association code for a variant (e.g., `"S2.1"`, `"2.4c"`).
1298    ///
1299    /// This is the version string from the MIG schema, used as the last component
1300    /// of the UNH S009 composite: `UTILMD:D:11A:UN:S2.1`.
1301    ///
1302    /// # Example
1303    /// ```ignore
1304    /// let code = mapper.association_code("FV2604", "UTILMD_Strom")?;
1305    /// assert_eq!(code, "S2.1");
1306    /// ```
1307    pub fn association_code(&self, fv: &str, variant: &str) -> Result<String, MapperError> {
1308        let meta = self.message_metadata(fv, variant)?;
1309        Ok(meta.association_code)
1310    }
1311
1312    /// Get full message metadata for a variant, including the UNH S009 components.
1313    ///
1314    /// Returns the message type, UN/EDIFACT release code, and association code
1315    /// needed to construct UNH segments.
1316    pub fn message_metadata(
1317        &self,
1318        fv: &str,
1319        variant: &str,
1320    ) -> Result<MessageMetadata, MapperError> {
1321        self.ensure_bundle_loaded(fv)?;
1322        let bundles = self.bundles.lock().unwrap();
1323        let bundle = bundles.get(fv).unwrap();
1324        let vc = bundle
1325            .variant(variant)
1326            .ok_or_else(|| MapperError::VariantNotFound {
1327                fv: fv.to_string(),
1328                variant: variant.to_string(),
1329            })?;
1330        let mig = vc
1331            .mig_schema
1332            .as_ref()
1333            .ok_or_else(|| MapperError::NoMigSchema {
1334                fv: fv.to_string(),
1335                variant: variant.to_string(),
1336            })?;
1337        Ok(MessageMetadata {
1338            message_type: mig.message_type.clone(),
1339            release: release_code_for_message_type(&mig.message_type),
1340            association_code: mig.version.clone(),
1341        })
1342    }
1343
1344    /// Convert BO4E JSON to a complete EDIFACT interchange with envelope segments.
1345    ///
1346    /// Produces a full interchange including UNA, UNB, UNH, message body, UNT, and UNZ.
1347    ///
1348    /// # The envelope is regenerated, not reproduced
1349    ///
1350    /// This always emits a `UNA` service string advice and stamps the `UNB`
1351    /// date and time from the clock, so a render is never byte-identical to the
1352    /// interchange it came from: an input carrying no `UNA` gains one, and its
1353    /// interchange date becomes today (issue #161). That is right for a
1354    /// re-send, and wrong for a caller checking that a conversion did not
1355    /// change the message.
1356    ///
1357    /// Two ways to check that instead:
1358    ///
1359    /// - compare message **bodies**, which
1360    ///   [`to_edifact_nachricht`](Self::to_edifact_nachricht) renders without
1361    ///   any envelope;
1362    /// - or reproduce the envelope with
1363    ///   [`to_edifact_interchange_with`](Self::to_edifact_interchange_with) and
1364    ///   [`EnvelopeOptions`], which take the `UNA` decision and the `UNB` date
1365    ///   and time from the caller.
1366    ///
1367    /// Neither reproduces non-default delimiters: the whole render uses
1368    /// [`EdifactDelimiters::default`](edifact_primitives::EdifactDelimiters::default).
1369    ///
1370    /// # Example
1371    /// ```ignore
1372    /// let edifact = mapper.to_edifact_interchange(
1373    ///     &InterchangeEnvelope {
1374    ///         sender: EdifactParty::bdew("9900000000003"),
1375    ///         receiver: EdifactParty::bdew("9900000000001"),
1376    ///         interchange_ref: "REF001".to_string(),
1377    ///     },
1378    ///     &[InterchangeMessage {
1379    ///         message_ref: "MSG001".to_string(),
1380    ///         msg_stammdaten: serde_json::json!({"marktteilnehmer": []}),
1381    ///         tx_stammdaten: vec![serde_json::json!({"prozessdaten": {"pruefidentifikator": "55001"}})],
1382    ///         fv: "FV2604".to_string(),
1383    ///         variant: "UTILMD_Strom".to_string(),
1384    ///         pid: "55001".to_string(),
1385    ///         ..Default::default()
1386    ///     }],
1387    /// )?;
1388    /// assert!(edifact.starts_with("UNA:+.? '"));
1389    /// ```
1390    ///
1391    /// # Errors
1392    ///
1393    /// Fails like [`to_edifact`](Self::to_edifact), including
1394    /// [`MapperError::MissingGroupEntrySegment`] for a group that would be
1395    /// rendered without its entry segment.
1396    pub fn to_edifact_interchange(
1397        &self,
1398        envelope: &InterchangeEnvelope,
1399        messages: &[InterchangeMessage],
1400    ) -> Result<String, MapperError> {
1401        self.render_interchange(
1402            envelope,
1403            messages,
1404            EntrySegmentCheck::Refuse,
1405            &EnvelopeOptions::default(),
1406        )
1407    }
1408
1409    /// Like [`to_edifact_interchange`](Self::to_edifact_interchange), with
1410    /// control over how the envelope is built.
1411    ///
1412    /// The default regenerates it — a fresh `UNA` and a `UNB` timestamped from
1413    /// the clock — which is right for a re-send but means a render can never
1414    /// equal its input. [`EnvelopeOptions`] lets a caller that has the original
1415    /// ask for it back instead (issue #161).
1416    ///
1417    /// # Errors
1418    ///
1419    /// As [`to_edifact_interchange`](Self::to_edifact_interchange).
1420    pub fn to_edifact_interchange_with(
1421        &self,
1422        envelope: &InterchangeEnvelope,
1423        messages: &[InterchangeMessage],
1424        options: &EnvelopeOptions,
1425    ) -> Result<String, MapperError> {
1426        self.render_interchange(envelope, messages, EntrySegmentCheck::Refuse, options)
1427    }
1428
1429    fn render_interchange(
1430        &self,
1431        envelope: &InterchangeEnvelope,
1432        messages: &[InterchangeMessage],
1433        check: EntrySegmentCheck,
1434        options: &EnvelopeOptions,
1435    ) -> Result<String, MapperError> {
1436        let delimiters = edifact_primitives::EdifactDelimiters::default();
1437        let sep = delimiters.component as char;
1438        let elem = delimiters.element as char;
1439        let seg_term = delimiters.segment as char;
1440
1441        let mut output = String::new();
1442
1443        // UNA — Service string advice. Omitted on request: an input that
1444        // carried none should not gain one (issue #161).
1445        if options.emit_una {
1446            output.push_str(&format!(
1447                "UNA{}{}{}{}{}{}",
1448                sep,                        // component separator
1449                elem,                       // element separator
1450                delimiters.decimal as char, // decimal notation
1451                delimiters.release as char, // release/escape character
1452                ' ',                        // reserved (space)
1453                seg_term,                   // segment terminator
1454            ));
1455        }
1456
1457        // UNB — Interchange header. The caller's date and time when it has
1458        // them, the clock otherwise.
1459        //
1460        // Checked here rather than in the builder: `datum_zeit` returns `Self`
1461        // so it cannot fail without spoiling the chaining, and this is the only
1462        // place that knows both values are present. A width-and-digits check is
1463        // all that is possible and all that is needed — it cannot know whether
1464        // a date is the right one, but it catches the two mistakes that happen,
1465        // an ISO date and a human-formatted time.
1466        check_unb_field("datum", "yymmdd", 6, options.datum.as_deref())?;
1467        check_unb_field("zeit", "hhmm", 4, options.zeit.as_deref())?;
1468
1469        let now = chrono::Utc::now();
1470        let date_str = options
1471            .datum
1472            .clone()
1473            .unwrap_or_else(|| now.format("%y%m%d").to_string());
1474        let time_str = options
1475            .zeit
1476            .clone()
1477            .unwrap_or_else(|| now.format("%H%M").to_string());
1478        let sender = &envelope.sender;
1479        let receiver = &envelope.receiver;
1480        let interchange_ref = &envelope.interchange_ref;
1481        output.push_str(&format!(
1482            "UNB{elem}UNOC{sep}3{elem}{sid}{sep}{sq}{elem}{rid}{sep}{rq}{elem}{date_str}{sep}{time_str}{elem}{interchange_ref}{seg_term}",
1483            sid = sender.id,
1484            sq = sender.qualifier,
1485            rid = receiver.id,
1486            rq = receiver.qualifier,
1487        ));
1488
1489        let mut message_count = 0u32;
1490
1491        for msg in messages {
1492            let meta = self.message_metadata(&msg.fv, &msg.variant)?;
1493
1494            // Generate body segments
1495            let body = self.render_message_body(
1496                &msg.msg_stammdaten,
1497                &msg.tx_stammdaten,
1498                &msg.fv,
1499                &msg.variant,
1500                &msg.pid,
1501                check,
1502            )?;
1503
1504            // Count segments in body (split by segment terminator, filter empty)
1505            let body_seg_count = body
1506                .split(seg_term)
1507                .filter(|s: &&str| !s.is_empty())
1508                .count();
1509            // UNH + body segments + UNT = total segment count
1510            let segment_count = body_seg_count + 2;
1511
1512            // UNH — Message header. Built by the one UNH builder rather than
1513            // formatted here a second time: the two drifted apart, and this
1514            // copy was the one that never learned about 0068 and S010.
1515            let header = mig_bo4e::model::Nachrichtendaten {
1516                unh_referenz: msg.message_ref.clone(),
1517                nachrichten_typ: meta.message_type.clone(),
1518                zuordnungsreferenz: msg.zuordnungsreferenz.clone(),
1519                uebermittlungsfolgenummer: msg.uebermittlungsfolgenummer.clone(),
1520                uebermittlungsabschnitt: msg.uebermittlungsabschnitt,
1521                nachricht: Default::default(),
1522            };
1523            let unh = mig_bo4e::model::rebuild_unh(&header, &meta.release, &meta.association_code);
1524            output.push_str(&unh.id);
1525            for element in &unh.elements {
1526                output.push(elem);
1527                output.push_str(&element.join(&sep.to_string()));
1528            }
1529            output.push(seg_term);
1530
1531            // Body segments
1532            output.push_str(&body);
1533
1534            // UNT — Message trailer
1535            output.push_str(&format!(
1536                "UNT{elem}{segment_count}{elem}{ref}{seg_term}",
1537                ref = msg.message_ref,
1538            ));
1539
1540            message_count += 1;
1541        }
1542
1543        // UNZ — Interchange trailer
1544        output.push_str(&format!(
1545            "UNZ{elem}{message_count}{elem}{interchange_ref}{seg_term}",
1546        ));
1547
1548        Ok(output)
1549    }
1550
1551    /// List all format versions currently loaded in memory.
1552    pub fn loaded_format_versions(&self) -> Vec<String> {
1553        self.bundles.lock().unwrap().keys().cloned().collect()
1554    }
1555
1556    /// List all variants available in a format version's bundle.
1557    ///
1558    /// Loads the bundle if not already loaded.
1559    pub fn variants(&self, fv: &str) -> Result<Vec<String>, MapperError> {
1560        self.ensure_bundle_loaded(fv)?;
1561        let bundles = self.bundles.lock().unwrap();
1562        let bundle = bundles.get(fv).unwrap();
1563        Ok(bundle.variants.keys().cloned().collect())
1564    }
1565}
1566
1567/// Metadata about a message type needed for constructing UNH segments.
1568#[derive(Debug, Clone)]
1569pub struct MessageMetadata {
1570    /// EDIFACT message type (e.g., `"UTILMD"`, `"MSCONS"`).
1571    pub message_type: String,
1572    /// UN/EDIFACT directory release code (e.g., `"11A"`, `"04B"`).
1573    pub release: String,
1574    /// Association-assigned code / MIG version (e.g., `"S2.1"`, `"2.4c"`).
1575    pub association_code: String,
1576}
1577
1578/// Envelope parameters for [`Mapper::to_edifact_interchange`].
1579#[derive(Debug, Clone)]
1580pub struct InterchangeEnvelope {
1581    /// Sender party (UNB S002).
1582    pub sender: EdifactParty,
1583    /// Receiver party (UNB S003).
1584    pub receiver: EdifactParty,
1585    /// Unique interchange reference (UNB 0020 / UNZ 0020).
1586    pub interchange_ref: String,
1587}
1588
1589/// Reject an `UNB` date or time that is not `digits` digits.
1590///
1591/// `None` means the caller did not supply one and the clock is used, which is
1592/// always well formed.
1593fn check_unb_field(
1594    field: &'static str,
1595    expected: &'static str,
1596    digits: usize,
1597    value: Option<&str>,
1598) -> Result<(), MapperError> {
1599    let Some(value) = value else {
1600        return Ok(());
1601    };
1602    if value.len() == digits && value.bytes().all(|b| b.is_ascii_digit()) {
1603        return Ok(());
1604    }
1605    Err(MapperError::MalformedEnvelopeDateTime {
1606        field,
1607        expected,
1608        digits,
1609        value: value.to_string(),
1610    })
1611}
1612
1613/// How [`Mapper::to_edifact_interchange_with`] builds the interchange envelope.
1614///
1615/// The default is to **regenerate**: emit a `UNA` service string advice and
1616/// stamp the `UNB` date and time from the clock. That is right for a re-send,
1617/// and it is what [`Mapper::to_edifact_interchange`] does.
1618///
1619/// It is wrong for a caller comparing a render against its input, because the
1620/// two differences are not about the message (issue #161). Such a caller has
1621/// the original — the forward direction hands it back as `Interchangedaten` —
1622/// and can ask for it here.
1623///
1624/// ```ignore
1625/// let options = EnvelopeOptions::default()
1626///     .emit_una(false)
1627///     .datum_zeit_from(&interchange.interchangedaten);
1628/// ```
1629///
1630/// # What this cannot reproduce
1631///
1632/// Non-default delimiters. The whole render — envelope and body alike — uses
1633/// [`EdifactDelimiters::default`], so an input whose `UNA` declared other
1634/// delimiters cannot be reproduced, and `emit_una(true)` always advertises the
1635/// defaults. Suppressing the `UNA` is honest about that; claiming delimiters
1636/// the body does not honour would not be.
1637///
1638/// [`EdifactDelimiters::default`]: edifact_primitives::EdifactDelimiters::default
1639#[derive(Debug, Clone)]
1640pub struct EnvelopeOptions {
1641    emit_una: bool,
1642    datum: Option<String>,
1643    zeit: Option<String>,
1644}
1645
1646impl Default for EnvelopeOptions {
1647    fn default() -> Self {
1648        Self {
1649            emit_una: true,
1650            datum: None,
1651            zeit: None,
1652        }
1653    }
1654}
1655
1656impl EnvelopeOptions {
1657    /// Whether to emit the `UNA` service string advice. Default `true`.
1658    ///
1659    /// An input that carried no `UNA` gains one unless this is `false`.
1660    pub fn emit_una(mut self, emit: bool) -> Self {
1661        self.emit_una = emit;
1662        self
1663    }
1664
1665    /// Interchange date (`yymmdd`) and time (`hhmm`) for `UNB`, instead of the
1666    /// clock.
1667    ///
1668    /// Both go into the header verbatim. A value that is not the right number
1669    /// of digits is refused when the interchange is rendered — with
1670    /// [`MapperError::MalformedEnvelopeDateTime`], not silently — because `UNB`
1671    /// is the segment whose defects surface at the receiving gateway rather
1672    /// than anywhere the sender looks.
1673    pub fn datum_zeit(mut self, datum: impl Into<String>, zeit: impl Into<String>) -> Self {
1674        self.datum = Some(datum.into());
1675        self.zeit = Some(zeit.into());
1676        self
1677    }
1678
1679    /// Take the `UNB` date and time from the `Interchangedaten` the forward
1680    /// direction produced. Fields it does not carry are left to the clock.
1681    pub fn datum_zeit_from(mut self, daten: &mig_bo4e::model::Interchangedaten) -> Self {
1682        self.datum = daten.datum.clone();
1683        self.zeit = daten.zeit.clone();
1684        self
1685    }
1686}
1687
1688/// An EDIFACT interchange party (sender or receiver) with codelist qualifier.
1689#[derive(Debug, Clone)]
1690pub struct EdifactParty {
1691    /// Party identification (e.g., MP-ID `"9900000000003"` or GLN `"4045458000000"`).
1692    pub id: String,
1693    /// Codelist qualifier: `"500"` = BDEW, `"14"` = GS1/EAN.
1694    pub qualifier: String,
1695}
1696
1697impl EdifactParty {
1698    /// Create a party with BDEW codelist qualifier (500).
1699    pub fn bdew(id: &str) -> Self {
1700        Self {
1701            id: id.to_string(),
1702            qualifier: "500".to_string(),
1703        }
1704    }
1705
1706    /// Create a party with GS1/EAN codelist qualifier (14).
1707    pub fn gs1(id: &str) -> Self {
1708        Self {
1709            id: id.to_string(),
1710            qualifier: "14".to_string(),
1711        }
1712    }
1713}
1714
1715/// A single message to include in an interchange built by
1716/// [`Mapper::to_edifact_interchange`].
1717///
1718/// `Default` is what lets a caller name only the fields it has: the three UNH
1719/// header options are absent from most messages, and spelling `None` three
1720/// times at every construction site is how they would come to be forgotten.
1721#[derive(Debug, Clone, Default)]
1722pub struct InterchangeMessage {
1723    /// Unique message reference number (used in UNH/UNT).
1724    pub message_ref: String,
1725    /// Message-level stammdaten (e.g., marktteilnehmer).
1726    pub msg_stammdaten: serde_json::Value,
1727    /// Transaction-level stammdaten (one per transaction).
1728    pub tx_stammdaten: Vec<serde_json::Value>,
1729    /// Format version (e.g., `"FV2604"`).
1730    pub fv: String,
1731    /// Message variant (e.g., `"UTILMD_Strom"`).
1732    pub variant: String,
1733    /// Pruefidentifikator (e.g., `"55001"`).
1734    pub pid: String,
1735    /// UNH 0068 — Allgemeine Zuordnungs-Referenz, when the message carries one.
1736    pub zuordnungsreferenz: Option<String>,
1737    /// UNH S010/0070 — Übermittlungsfolgenummer, when the message carries one.
1738    pub uebermittlungsfolgenummer: Option<String>,
1739    /// UNH S010/0073 — which end of a split message this transmission is.
1740    pub uebermittlungsabschnitt: Option<mig_bo4e::model::Uebermittlungsabschnitt>,
1741}
1742
1743/// What rendering does with a group instance that lacks its MIG entry segment.
1744#[derive(Debug, Clone, Copy)]
1745enum EntrySegmentCheck {
1746    /// Fail with [`MapperError::MissingGroupEntrySegment`].
1747    Refuse,
1748    /// Render it anyway (for validation, which reports the defect).
1749    Render,
1750}
1751
1752/// Find the mapping definitions for a group that rendered without its entry
1753/// segment, for the error message: the BO4E entities they fill, and the BO4E
1754/// fields the entry segment is built from (the data the caller has to supply).
1755///
1756/// `source_path` comes from the filtered MIG, where the variant qualifier of a
1757/// group may be absent (a PID with a single variant, or an instance whose
1758/// variant is unknown because its entry segment is missing: `sg4.sg8.sg10`)
1759/// while definitions carry one (`sg4.sg8_z03.sg10`), or the other way round.
1760/// An unqualified part therefore matches any variant of the same group.
1761fn describe_entry_segment_mappings<'d>(
1762    definition_sets: impl IntoIterator<Item = &'d [mig_bo4e::definition::MappingDefinition]>,
1763    source_path: &str,
1764    entry_segment: &str,
1765) -> (Vec<String>, Vec<String>) {
1766    fn qualifies(unqualified: &str, qualified: &str) -> bool {
1767        !unqualified.contains('_')
1768            && qualified.len() > unqualified.len()
1769            && qualified.is_char_boundary(unqualified.len())
1770            && qualified[..unqualified.len()].eq_ignore_ascii_case(unqualified)
1771            && qualified.as_bytes()[unqualified.len()] == b'_'
1772    }
1773    fn part_matches(mig_part: &str, def_part: &str) -> bool {
1774        def_part.eq_ignore_ascii_case(mig_part)
1775            || qualifies(mig_part, def_part)
1776            || qualifies(def_part, mig_part)
1777    }
1778    let mig_parts: Vec<&str> = source_path.split('.').collect();
1779
1780    let mut entities: Vec<String> = Vec::new();
1781    let mut entry_fields: Vec<String> = Vec::new();
1782    for def in definition_sets.into_iter().flatten() {
1783        let Some(def_path) = def.meta.source_path.as_deref() else {
1784            continue;
1785        };
1786        let def_parts: Vec<&str> = def_path.split('.').collect();
1787        if def_parts.len() != mig_parts.len()
1788            || !mig_parts
1789                .iter()
1790                .zip(&def_parts)
1791                .all(|(m, d)| part_matches(m, d))
1792        {
1793            continue;
1794        }
1795        if !entities.contains(&def.meta.entity) {
1796            entities.push(def.meta.entity.clone());
1797        }
1798        for (path, mapping) in &def.fields {
1799            let tag = path
1800                .split(['.', '['])
1801                .next()
1802                .unwrap_or_default()
1803                .to_ascii_uppercase();
1804            let target = match mapping {
1805                mig_bo4e::definition::FieldMapping::Simple(t) => t.as_str(),
1806                mig_bo4e::definition::FieldMapping::Structured(f) => f.target.as_str(),
1807                mig_bo4e::definition::FieldMapping::Nested(_) => continue,
1808            };
1809            if tag == entry_segment && !target.is_empty() {
1810                // A nested rule's fields sit in the elements of its parent's
1811                // list field (`SummenzeitreihenDaten.zuordnungen[].klasse`).
1812                let field = match def.meta.parent_field.as_deref() {
1813                    Some(list) => format!("{}.{list}[].{target}", def.meta.entity),
1814                    None => format!("{}.{target}", def.meta.entity),
1815                };
1816                if !entry_fields.contains(&field) {
1817                    entry_fields.push(field);
1818                }
1819            }
1820        }
1821    }
1822    (entities, entry_fields)
1823}
1824
1825/// UN/EDIFACT directory release code for a message type.
1826///
1827/// These are stable per-message-type constants from the BDEW/DVGW specifications.
1828fn release_code_for_message_type(msg_type: &str) -> String {
1829    mig_bo4e::model::release_code_for_message_type(msg_type).to_string()
1830}
1831
1832#[cfg(test)]
1833mod tests {
1834    use super::*;
1835    use std::path::Path;
1836
1837    fn data_dir() -> Option<std::path::PathBuf> {
1838        // Try dist/ first (pre-built data bundles), then cache/mappings/
1839        let dist = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../dist");
1840        if dist.join("edifact-data-FV2504.bin").exists() {
1841            return Some(dist);
1842        }
1843        let cache = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../cache/mappings");
1844        if cache.join("FV2504").exists() {
1845            return Some(cache);
1846        }
1847        eprintln!("Skipping test: no DataBundle files found");
1848        None
1849    }
1850
1851    #[test]
1852    fn test_to_edifact_produces_edifact_output() {
1853        let Some(data_dir) = data_dir() else {
1854            return;
1855        };
1856        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1857
1858        let msg_stammdaten = serde_json::json!({
1859            "marktteilnehmer": [{
1860                "marktrolle": "MS",
1861                "rollencodenummer": "9900123456789",
1862                "codepflegeCode": "293"
1863            }]
1864        });
1865        let tx_stammdaten = serde_json::json!({
1866            "prozessdaten": {
1867                "pruefidentifikator": "55001",
1868                "vorgangId": "ABC123",
1869                "transaktionsgrund": "E01"
1870            }
1871        });
1872
1873        let result = mapper.to_edifact(
1874            &msg_stammdaten,
1875            &[tx_stammdaten],
1876            "FV2504",
1877            "UTILMD_Strom",
1878            "55001",
1879        );
1880        assert!(result.is_ok(), "to_edifact failed: {:?}", result.err());
1881        let edifact = result.unwrap();
1882        assert!(!edifact.is_empty(), "EDIFACT output should not be empty");
1883        // Should produce NAD segment from marktteilnehmer
1884        assert!(edifact.contains("NAD"), "Should contain NAD segment");
1885        // Should produce IDE segment from prozessdaten
1886        assert!(edifact.contains("IDE"), "Should contain IDE segment");
1887    }
1888
1889    #[test]
1890    fn test_to_edifact_struct_produces_edifact_output() {
1891        let Some(data_dir) = data_dir() else {
1892            return;
1893        };
1894        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1895
1896        let nachricht = serde_json::json!({
1897            "stammdaten": {
1898                "marktteilnehmer": [{
1899                    "marktrolle": "MS",
1900                    "rollencodenummer": "9900123456789",
1901                    "codepflegeCode": "293"
1902                }]
1903            },
1904            "transaktionen": [{
1905                "prozessdaten": {
1906                    "pruefidentifikator": "55001",
1907                    "vorgangId": "ABC123"
1908                }
1909            }]
1910        });
1911
1912        let result = mapper.to_edifact_struct(&nachricht, "FV2504", "UTILMD_Strom", "55001");
1913        assert!(
1914            result.is_ok(),
1915            "to_edifact_struct failed: {:?}",
1916            result.err()
1917        );
1918        let edifact = result.unwrap();
1919        assert!(!edifact.is_empty(), "EDIFACT output should not be empty");
1920    }
1921
1922    #[test]
1923    fn test_to_edifact_invalid_fv_returns_error() {
1924        let Some(data_dir) = data_dir() else {
1925            return;
1926        };
1927        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1928
1929        let result = mapper.to_edifact(
1930            &serde_json::json!({}),
1931            &[serde_json::json!({})],
1932            "FV9999",
1933            "UTILMD_Strom",
1934            "55001",
1935        );
1936        assert!(result.is_err());
1937    }
1938
1939    #[test]
1940    fn test_to_edifact_invalid_variant_returns_error() {
1941        let Some(data_dir) = data_dir() else {
1942            return;
1943        };
1944        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1945
1946        let result = mapper.to_edifact(
1947            &serde_json::json!({}),
1948            &[serde_json::json!({})],
1949            "FV2504",
1950            "NONEXISTENT",
1951            "55001",
1952        );
1953        assert!(result.is_err());
1954    }
1955
1956    #[test]
1957    fn test_to_edifact_invalid_pid_returns_error() {
1958        let Some(data_dir) = data_dir() else {
1959            return;
1960        };
1961        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1962
1963        let result = mapper.to_edifact(
1964            &serde_json::json!({}),
1965            &[serde_json::json!({})],
1966            "FV2504",
1967            "UTILMD_Strom",
1968            "99999",
1969        );
1970        assert!(result.is_err());
1971    }
1972
1973    #[test]
1974    fn test_association_code() {
1975        let Some(data_dir) = data_dir() else {
1976            return;
1977        };
1978        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1979
1980        let code = mapper.association_code("FV2504", "UTILMD_Strom").unwrap();
1981        assert_eq!(code, "S2.1");
1982
1983        let code = mapper.association_code("FV2504", "MSCONS").unwrap();
1984        assert_eq!(code, "2.4c");
1985    }
1986
1987    #[test]
1988    fn test_message_metadata() {
1989        let Some(data_dir) = data_dir() else {
1990            return;
1991        };
1992        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1993
1994        let meta = mapper.message_metadata("FV2504", "UTILMD_Strom").unwrap();
1995        assert_eq!(meta.message_type, "UTILMD");
1996        assert_eq!(meta.release, "11A");
1997        assert_eq!(meta.association_code, "S2.1");
1998    }
1999
2000    #[test]
2001    fn test_to_edifact_interchange() {
2002        let Some(data_dir) = data_dir() else {
2003            return;
2004        };
2005        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2006
2007        let result = mapper.to_edifact_interchange(
2008            &InterchangeEnvelope {
2009                sender: EdifactParty::bdew("9900000000003"),
2010                receiver: EdifactParty::bdew("9900000000001"),
2011                interchange_ref: "REF001".to_string(),
2012            },
2013            &[InterchangeMessage {
2014                message_ref: "MSG001".to_string(),
2015                msg_stammdaten: serde_json::json!({
2016                    "marktteilnehmer": [{
2017                        "marktrolle": "MS",
2018                        "rollencodenummer": "9900123456789",
2019                        "codepflegeCode": "293"
2020                    }]
2021                }),
2022                tx_stammdaten: vec![serde_json::json!({
2023                    "prozessdaten": {
2024                        "pruefidentifikator": "55001",
2025                        "vorgangId": "ABC123",
2026                        "transaktionsgrund": "E01"
2027                    }
2028                })],
2029                fv: "FV2504".to_string(),
2030                variant: "UTILMD_Strom".to_string(),
2031                pid: "55001".to_string(),
2032                ..Default::default()
2033            }],
2034        );
2035        assert!(
2036            result.is_ok(),
2037            "to_edifact_interchange failed: {:?}",
2038            result.err()
2039        );
2040        let edifact = result.unwrap();
2041
2042        // Verify envelope structure
2043        assert!(edifact.starts_with("UNA:+.? '"), "Should start with UNA");
2044        assert!(
2045            edifact.contains("UNB+UNOC:3+9900000000003:500+9900000000001:500+"),
2046            "Should contain UNB with sender/receiver"
2047        );
2048        assert!(
2049            edifact.contains("UNH+MSG001+UTILMD:D:11A:UN:S2.1'"),
2050            "Should contain UNH with correct S009"
2051        );
2052        assert!(edifact.contains("NAD"), "Should contain body NAD segment");
2053        assert!(edifact.contains("UNT+"), "Should contain UNT");
2054        assert!(
2055            edifact.contains("+MSG001'"),
2056            "UNT should reference message ref"
2057        );
2058        assert!(
2059            edifact.contains("UNZ+1+REF001'"),
2060            "Should contain UNZ with count and ref"
2061        );
2062    }
2063
2064    #[test]
2065    fn test_detect_pid_from_rff_z13() {
2066        let Some(data_dir) = data_dir() else {
2067            return;
2068        };
2069        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2070
2071        let edifact = "\
2072            UNB+UNOC:3+9978842000002:500+9900269000000:500+250331:1329+REF001'\
2073            UNH+MSG001+UTILMD:D:11A:UN:S2.1'\
2074            BGM+E01+DOC001'\
2075            DTM+137:202503311329?+00:303'\
2076            NAD+MS+9978842000002::293'\
2077            NAD+MR+9900269000000::293'\
2078            IDE+24+TX001'\
2079            DTM+92:202505312200?+00:303'\
2080            DTM+93:202512312300?+00:303'\
2081            STS+7++E01+ZW4+E03'\
2082            LOC+Z16+12345678900'\
2083            RFF+Z13:55001'\
2084            UNT+12+MSG001'\
2085            UNZ+1+REF001'";
2086
2087        let pid = mapper.detect_pid(edifact).unwrap();
2088        assert_eq!(pid, "55001");
2089    }
2090
2091    #[test]
2092    fn test_detect_pid_no_messages_returns_error() {
2093        let Some(data_dir) = data_dir() else {
2094            return;
2095        };
2096        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2097
2098        let edifact = "UNB+UNOC:3+SENDER:500+RECEIVER:500+250401:1200+REF'\
2099                        UNZ+0+REF'";
2100        assert!(mapper.detect_pid(edifact).is_err());
2101    }
2102
2103    #[test]
2104    fn test_list_pids_returns_entries() {
2105        let Some(data_dir) = data_dir() else {
2106            return;
2107        };
2108        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir)).unwrap();
2109        let pids = mapper.list_pids().expect("list_pids should succeed");
2110        assert!(!pids.is_empty(), "should return at least one PID");
2111        assert!(
2112            pids.iter().any(|p| p.pid == "55001"),
2113            "should include PID 55001"
2114        );
2115        assert!(
2116            pids.iter().any(|p| p.fv == "FV2504"),
2117            "should include FV2504"
2118        );
2119        assert!(
2120            pids.iter().any(|p| p.variant == "UTILMD_Strom"),
2121            "should include UTILMD_Strom"
2122        );
2123    }
2124
2125    #[test]
2126    fn test_pid_requirements_returns_requirements() {
2127        let Some(data_dir) = data_dir() else {
2128            return;
2129        };
2130        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2131
2132        let req = mapper
2133            .pid_requirements("FV2504", "UTILMD_Strom", "55001")
2134            .expect("pid_requirements should succeed");
2135
2136        assert_eq!(req.pid, "55001");
2137        assert!(
2138            !req.entities.is_empty(),
2139            "55001 should have at least one entity"
2140        );
2141        assert!(
2142            req.entities.iter().any(|e| e.entity == "Prozessdaten"),
2143            "55001 should have a Prozessdaten entity"
2144        );
2145    }
2146}