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 mut options = EnvelopeOptions::default();
1220        let envelope = match envelope {
1221            Some(e) => e,
1222            None => {
1223                let (envelope, anwendungsreferenz) = self.placeholder_envelope(fv, variant, pid)?;
1224                if let Some(referenz) = anwendungsreferenz {
1225                    options = options.anwendungsreferenz(referenz);
1226                }
1227                placeholder = envelope;
1228                &placeholder
1229            }
1230        };
1231
1232        // Rendered without the entry-segment check `to_edifact_interchange`
1233        // applies: a group missing its entry segment is exactly the kind of
1234        // defect validation exists to report (as missing-field and structure
1235        // findings), so it must not abort the validation.
1236        let edifact =
1237            self.render_interchange(envelope, &[message], EntrySegmentCheck::Render, &options)?;
1238
1239        // The PID is given, not detected: for every message type but UTILMD the
1240        // rendered EDIFACT carries no RFF+Z13 to detect it from.
1241        self.validate_edifact_for_pid(&edifact, fv, variant, pid, level)
1242    }
1243
1244    /// The envelope `validate_rendered` uses when the caller gives none.
1245    ///
1246    /// Neutral where the AHB says nothing, but where the PID's AHB covers `UNB`
1247    /// (MSCONS) it holds to it: the code-list qualifiers of S002/S003 and the
1248    /// Anwendungsreferenz (0026) are the first codes the AHB allows. A fixed
1249    /// `500` with no 0026 would be reported against a message that carries
1250    /// neither error.
1251    fn placeholder_envelope(
1252        &self,
1253        fv: &str,
1254        variant: &str,
1255        pid: &str,
1256    ) -> Result<(InterchangeEnvelope, Option<String>), MapperError> {
1257        self.ensure_bundle_loaded(fv)?;
1258        let bundles = self.bundles.lock().unwrap();
1259        let rules = bundles
1260            .get(fv)
1261            .and_then(|b| b.variant(variant))
1262            .and_then(|vc| vc.pid_ahb_workflows.get(&format!("pid_{pid}")))
1263            .map(|w| w.fields.as_slice())
1264            .unwrap_or_default();
1265        let first_code = |path: &str| {
1266            rules
1267                .iter()
1268                .find(|r| r.segment_path == path)
1269                .and_then(|r| r.codes.first())
1270                .map(|c| c.value.clone())
1271        };
1272        let party = |id: &str, path: &str| EdifactParty {
1273            id: id.to_string(),
1274            qualifier: first_code(path).unwrap_or_else(|| "500".to_string()),
1275        };
1276        Ok((
1277            InterchangeEnvelope {
1278                sender: party("9900000000001", "UNB/S002/0007"),
1279                receiver: party("9900000000002", "UNB/S003/0007"),
1280                interchange_ref: "1".to_string(),
1281            },
1282            first_code("UNB/0026"),
1283        ))
1284    }
1285
1286    /// Validate BO4E JSON against the AHB rules of its Prüfidentifikator.
1287    ///
1288    /// This is [`validate_edifact`] with a reverse-mapping front end: the BO4E
1289    /// input is rendered to a complete EDIFACT interchange
1290    /// ([`to_edifact_interchange`]) and that interchange is validated. Because it
1291    /// is literally the same call, the findings are the ones the EDIFACT
1292    /// validation reports for the message this BO4E describes — including the
1293    /// `bo4e_path` enrichment that points each finding back at the BO4E field it
1294    /// came from. Callers working in BO4E (forms, assistants) therefore do not
1295    /// need their own EDIFACT-path-to-BO4E-path translation.
1296    ///
1297    /// `envelope` fills UNB/UNZ. Pass `None` unless the message type's MIG covers
1298    /// the interchange envelope (e.g. MSCONS) — for the others the envelope is
1299    /// outside the AHB and a neutral placeholder is used.
1300    ///
1301    /// Two classes of finding cannot appear here, because the BO4E input has no
1302    /// counterpart for them: the UNT segment-count check (the trailer is
1303    /// regenerated) and skipped-unknown-segment diagnostics (segments outside the
1304    /// AHB have no BO4E representation).
1305    ///
1306    /// [`validate_edifact`]: Self::validate_edifact
1307    /// [`to_edifact_interchange`]: Self::to_edifact_interchange
1308    pub fn validate_bo4e(
1309        &self,
1310        msg_stammdaten: &serde_json::Value,
1311        tx_stammdaten: &[serde_json::Value],
1312        fv: &str,
1313        variant: &str,
1314        pid: &str,
1315        envelope: Option<&InterchangeEnvelope>,
1316        level: automapper_validation::ValidationLevel,
1317    ) -> Result<automapper_validation::ValidationReport, MapperError> {
1318        self.validate_rendered(
1319            InterchangeMessage {
1320                message_ref: "1".to_string(),
1321                msg_stammdaten: msg_stammdaten.clone(),
1322                tx_stammdaten: tx_stammdaten.to_vec(),
1323                fv: fv.to_string(),
1324                variant: variant.to_string(),
1325                pid: pid.to_string(),
1326                ..Default::default()
1327            },
1328            fv,
1329            variant,
1330            pid,
1331            envelope,
1332            level,
1333        )
1334    }
1335
1336    /// Get the UNH association code for a variant (e.g., `"S2.1"`, `"2.4c"`).
1337    ///
1338    /// This is the version string from the MIG schema, used as the last component
1339    /// of the UNH S009 composite: `UTILMD:D:11A:UN:S2.1`.
1340    ///
1341    /// # Example
1342    /// ```ignore
1343    /// let code = mapper.association_code("FV2604", "UTILMD_Strom")?;
1344    /// assert_eq!(code, "S2.1");
1345    /// ```
1346    pub fn association_code(&self, fv: &str, variant: &str) -> Result<String, MapperError> {
1347        let meta = self.message_metadata(fv, variant)?;
1348        Ok(meta.association_code)
1349    }
1350
1351    /// Get full message metadata for a variant, including the UNH S009 components.
1352    ///
1353    /// Returns the message type, UN/EDIFACT release code, and association code
1354    /// needed to construct UNH segments.
1355    pub fn message_metadata(
1356        &self,
1357        fv: &str,
1358        variant: &str,
1359    ) -> Result<MessageMetadata, MapperError> {
1360        self.ensure_bundle_loaded(fv)?;
1361        let bundles = self.bundles.lock().unwrap();
1362        let bundle = bundles.get(fv).unwrap();
1363        let vc = bundle
1364            .variant(variant)
1365            .ok_or_else(|| MapperError::VariantNotFound {
1366                fv: fv.to_string(),
1367                variant: variant.to_string(),
1368            })?;
1369        let mig = vc
1370            .mig_schema
1371            .as_ref()
1372            .ok_or_else(|| MapperError::NoMigSchema {
1373                fv: fv.to_string(),
1374                variant: variant.to_string(),
1375            })?;
1376        Ok(MessageMetadata {
1377            message_type: mig.message_type.clone(),
1378            release: release_code_for_message_type(&mig.message_type),
1379            association_code: mig.version.clone(),
1380        })
1381    }
1382
1383    /// Convert BO4E JSON to a complete EDIFACT interchange with envelope segments.
1384    ///
1385    /// Produces a full interchange including UNA, UNB, UNH, message body, UNT, and UNZ.
1386    ///
1387    /// # The envelope is regenerated, not reproduced
1388    ///
1389    /// This always emits a `UNA` service string advice and stamps the `UNB`
1390    /// date and time from the clock, so a render is never byte-identical to the
1391    /// interchange it came from: an input carrying no `UNA` gains one, and its
1392    /// interchange date becomes today (issue #161). That is right for a
1393    /// re-send, and wrong for a caller checking that a conversion did not
1394    /// change the message.
1395    ///
1396    /// Two ways to check that instead:
1397    ///
1398    /// - compare message **bodies**, which
1399    ///   [`to_edifact_nachricht`](Self::to_edifact_nachricht) renders without
1400    ///   any envelope;
1401    /// - or reproduce the envelope with
1402    ///   [`to_edifact_interchange_with`](Self::to_edifact_interchange_with) and
1403    ///   [`EnvelopeOptions`], which take the `UNA` decision and the `UNB` date
1404    ///   and time from the caller.
1405    ///
1406    /// Neither reproduces non-default delimiters: the whole render uses
1407    /// [`EdifactDelimiters::default`](edifact_primitives::EdifactDelimiters::default).
1408    ///
1409    /// # Example
1410    /// ```ignore
1411    /// let edifact = mapper.to_edifact_interchange(
1412    ///     &InterchangeEnvelope {
1413    ///         sender: EdifactParty::bdew("9900000000003"),
1414    ///         receiver: EdifactParty::bdew("9900000000001"),
1415    ///         interchange_ref: "REF001".to_string(),
1416    ///     },
1417    ///     &[InterchangeMessage {
1418    ///         message_ref: "MSG001".to_string(),
1419    ///         msg_stammdaten: serde_json::json!({"marktteilnehmer": []}),
1420    ///         tx_stammdaten: vec![serde_json::json!({"prozessdaten": {"pruefidentifikator": "55001"}})],
1421    ///         fv: "FV2604".to_string(),
1422    ///         variant: "UTILMD_Strom".to_string(),
1423    ///         pid: "55001".to_string(),
1424    ///         ..Default::default()
1425    ///     }],
1426    /// )?;
1427    /// assert!(edifact.starts_with("UNA:+.? '"));
1428    /// ```
1429    ///
1430    /// # Errors
1431    ///
1432    /// Fails like [`to_edifact`](Self::to_edifact), including
1433    /// [`MapperError::MissingGroupEntrySegment`] for a group that would be
1434    /// rendered without its entry segment.
1435    pub fn to_edifact_interchange(
1436        &self,
1437        envelope: &InterchangeEnvelope,
1438        messages: &[InterchangeMessage],
1439    ) -> Result<String, MapperError> {
1440        self.render_interchange(
1441            envelope,
1442            messages,
1443            EntrySegmentCheck::Refuse,
1444            &EnvelopeOptions::default(),
1445        )
1446    }
1447
1448    /// Like [`to_edifact_interchange`](Self::to_edifact_interchange), with
1449    /// control over how the envelope is built.
1450    ///
1451    /// The default regenerates it — a fresh `UNA` and a `UNB` timestamped from
1452    /// the clock — which is right for a re-send but means a render can never
1453    /// equal its input. [`EnvelopeOptions`] lets a caller that has the original
1454    /// ask for it back instead (issue #161).
1455    ///
1456    /// # Errors
1457    ///
1458    /// As [`to_edifact_interchange`](Self::to_edifact_interchange).
1459    pub fn to_edifact_interchange_with(
1460        &self,
1461        envelope: &InterchangeEnvelope,
1462        messages: &[InterchangeMessage],
1463        options: &EnvelopeOptions,
1464    ) -> Result<String, MapperError> {
1465        self.render_interchange(envelope, messages, EntrySegmentCheck::Refuse, options)
1466    }
1467
1468    fn render_interchange(
1469        &self,
1470        envelope: &InterchangeEnvelope,
1471        messages: &[InterchangeMessage],
1472        check: EntrySegmentCheck,
1473        options: &EnvelopeOptions,
1474    ) -> Result<String, MapperError> {
1475        let delimiters = edifact_primitives::EdifactDelimiters::default();
1476        let sep = delimiters.component as char;
1477        let elem = delimiters.element as char;
1478        let seg_term = delimiters.segment as char;
1479
1480        let mut output = String::new();
1481
1482        // UNA — Service string advice. Omitted on request: an input that
1483        // carried none should not gain one (issue #161).
1484        if options.emit_una {
1485            output.push_str(&format!(
1486                "UNA{}{}{}{}{}{}",
1487                sep,                        // component separator
1488                elem,                       // element separator
1489                delimiters.decimal as char, // decimal notation
1490                delimiters.release as char, // release/escape character
1491                ' ',                        // reserved (space)
1492                seg_term,                   // segment terminator
1493            ));
1494        }
1495
1496        // UNB — Interchange header. The caller's date and time when it has
1497        // them, the clock otherwise.
1498        //
1499        // Checked here rather than in the builder: `datum_zeit` returns `Self`
1500        // so it cannot fail without spoiling the chaining, and this is the only
1501        // place that knows both values are present. A width-and-digits check is
1502        // all that is possible and all that is needed — it cannot know whether
1503        // a date is the right one, but it catches the two mistakes that happen,
1504        // an ISO date and a human-formatted time.
1505        check_unb_field("datum", "yymmdd", 6, options.datum.as_deref())?;
1506        check_unb_field("zeit", "hhmm", 4, options.zeit.as_deref())?;
1507
1508        let now = chrono::Utc::now();
1509        let date_str = options
1510            .datum
1511            .clone()
1512            .unwrap_or_else(|| now.format("%y%m%d").to_string());
1513        let time_str = options
1514            .zeit
1515            .clone()
1516            .unwrap_or_else(|| now.format("%H%M").to_string());
1517        let sender = &envelope.sender;
1518        let receiver = &envelope.receiver;
1519        let interchange_ref = &envelope.interchange_ref;
1520        output.push_str(&format!(
1521            "UNB{elem}UNOC{sep}3{elem}{sid}{sep}{sq}{elem}{rid}{sep}{rq}{elem}{date_str}{sep}{time_str}{elem}{interchange_ref}{anwendungsreferenz}{seg_term}",
1522            sid = sender.id,
1523            sq = sender.qualifier,
1524            rid = receiver.id,
1525            rq = receiver.qualifier,
1526            anwendungsreferenz = options
1527                .anwendungsreferenz
1528                .as_deref()
1529                .map(|r| format!("{elem}{elem}{r}"))
1530                .unwrap_or_default(),
1531        ));
1532
1533        let mut message_count = 0u32;
1534
1535        for msg in messages {
1536            let meta = self.message_metadata(&msg.fv, &msg.variant)?;
1537
1538            // Generate body segments
1539            let body = self.render_message_body(
1540                &msg.msg_stammdaten,
1541                &msg.tx_stammdaten,
1542                &msg.fv,
1543                &msg.variant,
1544                &msg.pid,
1545                check,
1546            )?;
1547
1548            // Count segments in body (split by segment terminator, filter empty)
1549            let body_seg_count = body
1550                .split(seg_term)
1551                .filter(|s: &&str| !s.is_empty())
1552                .count();
1553            // UNH + body segments + UNT = total segment count
1554            let segment_count = body_seg_count + 2;
1555
1556            // UNH — Message header. Built by the one UNH builder rather than
1557            // formatted here a second time: the two drifted apart, and this
1558            // copy was the one that never learned about 0068 and S010.
1559            let header = mig_bo4e::model::Nachrichtendaten {
1560                unh_referenz: msg.message_ref.clone(),
1561                nachrichten_typ: meta.message_type.clone(),
1562                zuordnungsreferenz: msg.zuordnungsreferenz.clone(),
1563                uebermittlungsfolgenummer: msg.uebermittlungsfolgenummer.clone(),
1564                uebermittlungsabschnitt: msg.uebermittlungsabschnitt,
1565                nachricht: Default::default(),
1566            };
1567            let unh = mig_bo4e::model::rebuild_unh(&header, &meta.release, &meta.association_code);
1568            output.push_str(&unh.id);
1569            for element in &unh.elements {
1570                output.push(elem);
1571                output.push_str(&element.join(&sep.to_string()));
1572            }
1573            output.push(seg_term);
1574
1575            // Body segments
1576            output.push_str(&body);
1577
1578            // UNT — Message trailer
1579            output.push_str(&format!(
1580                "UNT{elem}{segment_count}{elem}{ref}{seg_term}",
1581                ref = msg.message_ref,
1582            ));
1583
1584            message_count += 1;
1585        }
1586
1587        // UNZ — Interchange trailer
1588        output.push_str(&format!(
1589            "UNZ{elem}{message_count}{elem}{interchange_ref}{seg_term}",
1590        ));
1591
1592        Ok(output)
1593    }
1594
1595    /// List all format versions currently loaded in memory.
1596    pub fn loaded_format_versions(&self) -> Vec<String> {
1597        self.bundles.lock().unwrap().keys().cloned().collect()
1598    }
1599
1600    /// List all variants available in a format version's bundle.
1601    ///
1602    /// Loads the bundle if not already loaded.
1603    pub fn variants(&self, fv: &str) -> Result<Vec<String>, MapperError> {
1604        self.ensure_bundle_loaded(fv)?;
1605        let bundles = self.bundles.lock().unwrap();
1606        let bundle = bundles.get(fv).unwrap();
1607        Ok(bundle.variants.keys().cloned().collect())
1608    }
1609}
1610
1611/// Metadata about a message type needed for constructing UNH segments.
1612#[derive(Debug, Clone)]
1613pub struct MessageMetadata {
1614    /// EDIFACT message type (e.g., `"UTILMD"`, `"MSCONS"`).
1615    pub message_type: String,
1616    /// UN/EDIFACT directory release code (e.g., `"11A"`, `"04B"`).
1617    pub release: String,
1618    /// Association-assigned code / MIG version (e.g., `"S2.1"`, `"2.4c"`).
1619    pub association_code: String,
1620}
1621
1622/// Envelope parameters for [`Mapper::to_edifact_interchange`].
1623#[derive(Debug, Clone)]
1624pub struct InterchangeEnvelope {
1625    /// Sender party (UNB S002).
1626    pub sender: EdifactParty,
1627    /// Receiver party (UNB S003).
1628    pub receiver: EdifactParty,
1629    /// Unique interchange reference (UNB 0020 / UNZ 0020).
1630    pub interchange_ref: String,
1631}
1632
1633/// Reject an `UNB` date or time that is not `digits` digits.
1634///
1635/// `None` means the caller did not supply one and the clock is used, which is
1636/// always well formed.
1637fn check_unb_field(
1638    field: &'static str,
1639    expected: &'static str,
1640    digits: usize,
1641    value: Option<&str>,
1642) -> Result<(), MapperError> {
1643    let Some(value) = value else {
1644        return Ok(());
1645    };
1646    if value.len() == digits && value.bytes().all(|b| b.is_ascii_digit()) {
1647        return Ok(());
1648    }
1649    Err(MapperError::MalformedEnvelopeDateTime {
1650        field,
1651        expected,
1652        digits,
1653        value: value.to_string(),
1654    })
1655}
1656
1657/// How [`Mapper::to_edifact_interchange_with`] builds the interchange envelope.
1658///
1659/// The default is to **regenerate**: emit a `UNA` service string advice and
1660/// stamp the `UNB` date and time from the clock. That is right for a re-send,
1661/// and it is what [`Mapper::to_edifact_interchange`] does.
1662///
1663/// It is wrong for a caller comparing a render against its input, because the
1664/// two differences are not about the message (issue #161). Such a caller has
1665/// the original — the forward direction hands it back as `Interchangedaten` —
1666/// and can ask for it here.
1667///
1668/// ```ignore
1669/// let options = EnvelopeOptions::default()
1670///     .emit_una(false)
1671///     .datum_zeit_from(&interchange.interchangedaten);
1672/// ```
1673///
1674/// # What this cannot reproduce
1675///
1676/// Non-default delimiters. The whole render — envelope and body alike — uses
1677/// [`EdifactDelimiters::default`], so an input whose `UNA` declared other
1678/// delimiters cannot be reproduced, and `emit_una(true)` always advertises the
1679/// defaults. Suppressing the `UNA` is honest about that; claiming delimiters
1680/// the body does not honour would not be.
1681///
1682/// [`EdifactDelimiters::default`]: edifact_primitives::EdifactDelimiters::default
1683#[derive(Debug, Clone)]
1684pub struct EnvelopeOptions {
1685    emit_una: bool,
1686    datum: Option<String>,
1687    zeit: Option<String>,
1688    anwendungsreferenz: Option<String>,
1689}
1690
1691impl Default for EnvelopeOptions {
1692    fn default() -> Self {
1693        Self {
1694            emit_una: true,
1695            datum: None,
1696            zeit: None,
1697            anwendungsreferenz: None,
1698        }
1699    }
1700}
1701
1702impl EnvelopeOptions {
1703    /// Whether to emit the `UNA` service string advice. Default `true`.
1704    ///
1705    /// An input that carried no `UNA` gains one unless this is `false`.
1706    pub fn emit_una(mut self, emit: bool) -> Self {
1707        self.emit_una = emit;
1708        self
1709    }
1710
1711    /// Interchange date (`yymmdd`) and time (`hhmm`) for `UNB`, instead of the
1712    /// clock.
1713    ///
1714    /// Both go into the header verbatim. A value that is not the right number
1715    /// of digits is refused when the interchange is rendered — with
1716    /// [`MapperError::MalformedEnvelopeDateTime`], not silently — because `UNB`
1717    /// is the segment whose defects surface at the receiving gateway rather
1718    /// than anywhere the sender looks.
1719    pub fn datum_zeit(mut self, datum: impl Into<String>, zeit: impl Into<String>) -> Self {
1720        self.datum = Some(datum.into());
1721        self.zeit = Some(zeit.into());
1722        self
1723    }
1724
1725    /// The Anwendungsreferenz (`UNB` 0026), e.g. `VL` for an MSCONS
1726    /// Lastgang. Omitted by default; the AHB of some message types requires it.
1727    pub fn anwendungsreferenz(mut self, referenz: impl Into<String>) -> Self {
1728        self.anwendungsreferenz = Some(referenz.into());
1729        self
1730    }
1731
1732    /// Take the `UNB` date and time from the `Interchangedaten` the forward
1733    /// direction produced. Fields it does not carry are left to the clock.
1734    pub fn datum_zeit_from(mut self, daten: &mig_bo4e::model::Interchangedaten) -> Self {
1735        self.datum = daten.datum.clone();
1736        self.zeit = daten.zeit.clone();
1737        self
1738    }
1739}
1740
1741/// An EDIFACT interchange party (sender or receiver) with codelist qualifier.
1742#[derive(Debug, Clone)]
1743pub struct EdifactParty {
1744    /// Party identification (e.g., MP-ID `"9900000000003"` or GLN `"4045458000000"`).
1745    pub id: String,
1746    /// Codelist qualifier: `"500"` = BDEW, `"14"` = GS1/EAN.
1747    pub qualifier: String,
1748}
1749
1750impl EdifactParty {
1751    /// Create a party with BDEW codelist qualifier (500).
1752    pub fn bdew(id: &str) -> Self {
1753        Self {
1754            id: id.to_string(),
1755            qualifier: "500".to_string(),
1756        }
1757    }
1758
1759    /// Create a party with GS1/EAN codelist qualifier (14).
1760    pub fn gs1(id: &str) -> Self {
1761        Self {
1762            id: id.to_string(),
1763            qualifier: "14".to_string(),
1764        }
1765    }
1766}
1767
1768/// A single message to include in an interchange built by
1769/// [`Mapper::to_edifact_interchange`].
1770///
1771/// `Default` is what lets a caller name only the fields it has: the three UNH
1772/// header options are absent from most messages, and spelling `None` three
1773/// times at every construction site is how they would come to be forgotten.
1774#[derive(Debug, Clone, Default)]
1775pub struct InterchangeMessage {
1776    /// Unique message reference number (used in UNH/UNT).
1777    pub message_ref: String,
1778    /// Message-level stammdaten (e.g., marktteilnehmer).
1779    pub msg_stammdaten: serde_json::Value,
1780    /// Transaction-level stammdaten (one per transaction).
1781    pub tx_stammdaten: Vec<serde_json::Value>,
1782    /// Format version (e.g., `"FV2604"`).
1783    pub fv: String,
1784    /// Message variant (e.g., `"UTILMD_Strom"`).
1785    pub variant: String,
1786    /// Pruefidentifikator (e.g., `"55001"`).
1787    pub pid: String,
1788    /// UNH 0068 — Allgemeine Zuordnungs-Referenz, when the message carries one.
1789    pub zuordnungsreferenz: Option<String>,
1790    /// UNH S010/0070 — Übermittlungsfolgenummer, when the message carries one.
1791    pub uebermittlungsfolgenummer: Option<String>,
1792    /// UNH S010/0073 — which end of a split message this transmission is.
1793    pub uebermittlungsabschnitt: Option<mig_bo4e::model::Uebermittlungsabschnitt>,
1794}
1795
1796/// What rendering does with a group instance that lacks its MIG entry segment.
1797#[derive(Debug, Clone, Copy)]
1798enum EntrySegmentCheck {
1799    /// Fail with [`MapperError::MissingGroupEntrySegment`].
1800    Refuse,
1801    /// Render it anyway (for validation, which reports the defect).
1802    Render,
1803}
1804
1805/// Find the mapping definitions for a group that rendered without its entry
1806/// segment, for the error message: the BO4E entities they fill, and the BO4E
1807/// fields the entry segment is built from (the data the caller has to supply).
1808///
1809/// `source_path` comes from the filtered MIG, where the variant qualifier of a
1810/// group may be absent (a PID with a single variant, or an instance whose
1811/// variant is unknown because its entry segment is missing: `sg4.sg8.sg10`)
1812/// while definitions carry one (`sg4.sg8_z03.sg10`), or the other way round.
1813/// An unqualified part therefore matches any variant of the same group.
1814fn describe_entry_segment_mappings<'d>(
1815    definition_sets: impl IntoIterator<Item = &'d [mig_bo4e::definition::MappingDefinition]>,
1816    source_path: &str,
1817    entry_segment: &str,
1818) -> (Vec<String>, Vec<String>) {
1819    fn qualifies(unqualified: &str, qualified: &str) -> bool {
1820        !unqualified.contains('_')
1821            && qualified.len() > unqualified.len()
1822            && qualified.is_char_boundary(unqualified.len())
1823            && qualified[..unqualified.len()].eq_ignore_ascii_case(unqualified)
1824            && qualified.as_bytes()[unqualified.len()] == b'_'
1825    }
1826    fn part_matches(mig_part: &str, def_part: &str) -> bool {
1827        def_part.eq_ignore_ascii_case(mig_part)
1828            || qualifies(mig_part, def_part)
1829            || qualifies(def_part, mig_part)
1830    }
1831    let mig_parts: Vec<&str> = source_path.split('.').collect();
1832
1833    let mut entities: Vec<String> = Vec::new();
1834    let mut entry_fields: Vec<String> = Vec::new();
1835    for def in definition_sets.into_iter().flatten() {
1836        let Some(def_path) = def.meta.source_path.as_deref() else {
1837            continue;
1838        };
1839        let def_parts: Vec<&str> = def_path.split('.').collect();
1840        if def_parts.len() != mig_parts.len()
1841            || !mig_parts
1842                .iter()
1843                .zip(&def_parts)
1844                .all(|(m, d)| part_matches(m, d))
1845        {
1846            continue;
1847        }
1848        if !entities.contains(&def.meta.entity) {
1849            entities.push(def.meta.entity.clone());
1850        }
1851        for (path, mapping) in &def.fields {
1852            let tag = path
1853                .split(['.', '['])
1854                .next()
1855                .unwrap_or_default()
1856                .to_ascii_uppercase();
1857            let target = match mapping {
1858                mig_bo4e::definition::FieldMapping::Simple(t) => t.as_str(),
1859                mig_bo4e::definition::FieldMapping::Structured(f) => f.target.as_str(),
1860                mig_bo4e::definition::FieldMapping::Nested(_) => continue,
1861            };
1862            if tag == entry_segment && !target.is_empty() {
1863                // A nested rule's fields sit in the elements of its parent's
1864                // list field (`SummenzeitreihenDaten.zuordnungen[].klasse`).
1865                let field = match def.meta.parent_field.as_deref() {
1866                    Some(list) => format!("{}.{list}[].{target}", def.meta.entity),
1867                    None => format!("{}.{target}", def.meta.entity),
1868                };
1869                if !entry_fields.contains(&field) {
1870                    entry_fields.push(field);
1871                }
1872            }
1873        }
1874    }
1875    (entities, entry_fields)
1876}
1877
1878/// UN/EDIFACT directory release code for a message type.
1879///
1880/// These are stable per-message-type constants from the BDEW/DVGW specifications.
1881fn release_code_for_message_type(msg_type: &str) -> String {
1882    mig_bo4e::model::release_code_for_message_type(msg_type).to_string()
1883}
1884
1885#[cfg(test)]
1886mod tests {
1887    use super::*;
1888    use std::path::Path;
1889
1890    fn data_dir() -> Option<std::path::PathBuf> {
1891        // Try dist/ first (pre-built data bundles), then cache/mappings/
1892        let dist = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../dist");
1893        if dist.join("edifact-data-FV2504.bin").exists() {
1894            return Some(dist);
1895        }
1896        let cache = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../cache/mappings");
1897        if cache.join("FV2504").exists() {
1898            return Some(cache);
1899        }
1900        eprintln!("Skipping test: no DataBundle files found");
1901        None
1902    }
1903
1904    #[test]
1905    fn test_to_edifact_produces_edifact_output() {
1906        let Some(data_dir) = data_dir() else {
1907            return;
1908        };
1909        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1910
1911        let msg_stammdaten = serde_json::json!({
1912            "marktteilnehmer": [{
1913                "marktrolle": "MS",
1914                "rollencodenummer": "9900123456789",
1915                "codepflegeCode": "293"
1916            }]
1917        });
1918        let tx_stammdaten = serde_json::json!({
1919            "prozessdaten": {
1920                "pruefidentifikator": "55001",
1921                "vorgangId": "ABC123",
1922                "transaktionsgrund": "E01"
1923            }
1924        });
1925
1926        let result = mapper.to_edifact(
1927            &msg_stammdaten,
1928            &[tx_stammdaten],
1929            "FV2504",
1930            "UTILMD_Strom",
1931            "55001",
1932        );
1933        assert!(result.is_ok(), "to_edifact failed: {:?}", result.err());
1934        let edifact = result.unwrap();
1935        assert!(!edifact.is_empty(), "EDIFACT output should not be empty");
1936        // Should produce NAD segment from marktteilnehmer
1937        assert!(edifact.contains("NAD"), "Should contain NAD segment");
1938        // Should produce IDE segment from prozessdaten
1939        assert!(edifact.contains("IDE"), "Should contain IDE segment");
1940    }
1941
1942    #[test]
1943    fn test_to_edifact_struct_produces_edifact_output() {
1944        let Some(data_dir) = data_dir() else {
1945            return;
1946        };
1947        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1948
1949        let nachricht = serde_json::json!({
1950            "stammdaten": {
1951                "marktteilnehmer": [{
1952                    "marktrolle": "MS",
1953                    "rollencodenummer": "9900123456789",
1954                    "codepflegeCode": "293"
1955                }]
1956            },
1957            "transaktionen": [{
1958                "prozessdaten": {
1959                    "pruefidentifikator": "55001",
1960                    "vorgangId": "ABC123"
1961                }
1962            }]
1963        });
1964
1965        let result = mapper.to_edifact_struct(&nachricht, "FV2504", "UTILMD_Strom", "55001");
1966        assert!(
1967            result.is_ok(),
1968            "to_edifact_struct failed: {:?}",
1969            result.err()
1970        );
1971        let edifact = result.unwrap();
1972        assert!(!edifact.is_empty(), "EDIFACT output should not be empty");
1973    }
1974
1975    #[test]
1976    fn test_to_edifact_invalid_fv_returns_error() {
1977        let Some(data_dir) = data_dir() else {
1978            return;
1979        };
1980        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1981
1982        let result = mapper.to_edifact(
1983            &serde_json::json!({}),
1984            &[serde_json::json!({})],
1985            "FV9999",
1986            "UTILMD_Strom",
1987            "55001",
1988        );
1989        assert!(result.is_err());
1990    }
1991
1992    #[test]
1993    fn test_to_edifact_invalid_variant_returns_error() {
1994        let Some(data_dir) = data_dir() else {
1995            return;
1996        };
1997        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
1998
1999        let result = mapper.to_edifact(
2000            &serde_json::json!({}),
2001            &[serde_json::json!({})],
2002            "FV2504",
2003            "NONEXISTENT",
2004            "55001",
2005        );
2006        assert!(result.is_err());
2007    }
2008
2009    #[test]
2010    fn test_to_edifact_invalid_pid_returns_error() {
2011        let Some(data_dir) = data_dir() else {
2012            return;
2013        };
2014        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2015
2016        let result = mapper.to_edifact(
2017            &serde_json::json!({}),
2018            &[serde_json::json!({})],
2019            "FV2504",
2020            "UTILMD_Strom",
2021            "99999",
2022        );
2023        assert!(result.is_err());
2024    }
2025
2026    #[test]
2027    fn test_association_code() {
2028        let Some(data_dir) = data_dir() else {
2029            return;
2030        };
2031        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2032
2033        let code = mapper.association_code("FV2504", "UTILMD_Strom").unwrap();
2034        assert_eq!(code, "S2.1");
2035
2036        let code = mapper.association_code("FV2504", "MSCONS").unwrap();
2037        assert_eq!(code, "2.4c");
2038    }
2039
2040    #[test]
2041    fn test_message_metadata() {
2042        let Some(data_dir) = data_dir() else {
2043            return;
2044        };
2045        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2046
2047        let meta = mapper.message_metadata("FV2504", "UTILMD_Strom").unwrap();
2048        assert_eq!(meta.message_type, "UTILMD");
2049        assert_eq!(meta.release, "11A");
2050        assert_eq!(meta.association_code, "S2.1");
2051    }
2052
2053    #[test]
2054    fn test_to_edifact_interchange() {
2055        let Some(data_dir) = data_dir() else {
2056            return;
2057        };
2058        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2059
2060        let result = mapper.to_edifact_interchange(
2061            &InterchangeEnvelope {
2062                sender: EdifactParty::bdew("9900000000003"),
2063                receiver: EdifactParty::bdew("9900000000001"),
2064                interchange_ref: "REF001".to_string(),
2065            },
2066            &[InterchangeMessage {
2067                message_ref: "MSG001".to_string(),
2068                msg_stammdaten: serde_json::json!({
2069                    "marktteilnehmer": [{
2070                        "marktrolle": "MS",
2071                        "rollencodenummer": "9900123456789",
2072                        "codepflegeCode": "293"
2073                    }]
2074                }),
2075                tx_stammdaten: vec![serde_json::json!({
2076                    "prozessdaten": {
2077                        "pruefidentifikator": "55001",
2078                        "vorgangId": "ABC123",
2079                        "transaktionsgrund": "E01"
2080                    }
2081                })],
2082                fv: "FV2504".to_string(),
2083                variant: "UTILMD_Strom".to_string(),
2084                pid: "55001".to_string(),
2085                ..Default::default()
2086            }],
2087        );
2088        assert!(
2089            result.is_ok(),
2090            "to_edifact_interchange failed: {:?}",
2091            result.err()
2092        );
2093        let edifact = result.unwrap();
2094
2095        // Verify envelope structure
2096        assert!(edifact.starts_with("UNA:+.? '"), "Should start with UNA");
2097        assert!(
2098            edifact.contains("UNB+UNOC:3+9900000000003:500+9900000000001:500+"),
2099            "Should contain UNB with sender/receiver"
2100        );
2101        assert!(
2102            edifact.contains("UNH+MSG001+UTILMD:D:11A:UN:S2.1'"),
2103            "Should contain UNH with correct S009"
2104        );
2105        assert!(edifact.contains("NAD"), "Should contain body NAD segment");
2106        assert!(edifact.contains("UNT+"), "Should contain UNT");
2107        assert!(
2108            edifact.contains("+MSG001'"),
2109            "UNT should reference message ref"
2110        );
2111        assert!(
2112            edifact.contains("UNZ+1+REF001'"),
2113            "Should contain UNZ with count and ref"
2114        );
2115    }
2116
2117    #[test]
2118    fn test_detect_pid_from_rff_z13() {
2119        let Some(data_dir) = data_dir() else {
2120            return;
2121        };
2122        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2123
2124        let edifact = "\
2125            UNB+UNOC:3+9978842000002:500+9900269000000:500+250331:1329+REF001'\
2126            UNH+MSG001+UTILMD:D:11A:UN:S2.1'\
2127            BGM+E01+DOC001'\
2128            DTM+137:202503311329?+00:303'\
2129            NAD+MS+9978842000002::293'\
2130            NAD+MR+9900269000000::293'\
2131            IDE+24+TX001'\
2132            DTM+92:202505312200?+00:303'\
2133            DTM+93:202512312300?+00:303'\
2134            STS+7++E01+ZW4+E03'\
2135            LOC+Z16+12345678900'\
2136            RFF+Z13:55001'\
2137            UNT+12+MSG001'\
2138            UNZ+1+REF001'";
2139
2140        let pid = mapper.detect_pid(edifact).unwrap();
2141        assert_eq!(pid, "55001");
2142    }
2143
2144    #[test]
2145    fn test_detect_pid_no_messages_returns_error() {
2146        let Some(data_dir) = data_dir() else {
2147            return;
2148        };
2149        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2150
2151        let edifact = "UNB+UNOC:3+SENDER:500+RECEIVER:500+250401:1200+REF'\
2152                        UNZ+0+REF'";
2153        assert!(mapper.detect_pid(edifact).is_err());
2154    }
2155
2156    #[test]
2157    fn test_list_pids_returns_entries() {
2158        let Some(data_dir) = data_dir() else {
2159            return;
2160        };
2161        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir)).unwrap();
2162        let pids = mapper.list_pids().expect("list_pids should succeed");
2163        assert!(!pids.is_empty(), "should return at least one PID");
2164        assert!(
2165            pids.iter().any(|p| p.pid == "55001"),
2166            "should include PID 55001"
2167        );
2168        assert!(
2169            pids.iter().any(|p| p.fv == "FV2504"),
2170            "should include FV2504"
2171        );
2172        assert!(
2173            pids.iter().any(|p| p.variant == "UTILMD_Strom"),
2174            "should include UTILMD_Strom"
2175        );
2176    }
2177
2178    #[test]
2179    fn test_pid_requirements_returns_requirements() {
2180        let Some(data_dir) = data_dir() else {
2181            return;
2182        };
2183        let mapper = Mapper::from_data_dir(DataDir::path(&data_dir).eager(&["FV2504"])).unwrap();
2184
2185        let req = mapper
2186            .pid_requirements("FV2504", "UTILMD_Strom", "55001")
2187            .expect("pid_requirements should succeed");
2188
2189        assert_eq!(req.pid, "55001");
2190        assert!(
2191            !req.entities.is_empty(),
2192            "55001 should have at least one entity"
2193        );
2194        assert!(
2195            req.entities.iter().any(|e| e.entity == "Prozessdaten"),
2196            "55001 should have a Prozessdaten entity"
2197        );
2198    }
2199}