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