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