edi-energy 0.15.0

EDI@Energy EDIFACT parser and validator for the German energy market
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
/// Profile registry for EDI@Energy release-specific validation rules.
///
/// The registry maps `(MessageType, Release)` pairs to a [`Profile`] implementation
/// that provides MIG/AHB rule packs used during validation.
///
/// Use [`ReleaseRegistry::global()`] to access the process-global singleton.
/// It is populated once by `xtask codegen`-generated code via a `std::sync::OnceLock`.
use std::sync::{Arc, OnceLock};

use edifact_rs::directory_validator::SegmentDefinition;
use edifact_rs::{DirectoryValidator, ProfileRulePack};

use crate::{Error, MessageType, Pruefidentifikator, Release, generated};
// ── PidSource ─────────────────────────────────────────────────────────────────

/// Specifies where the Prüfidentifikator is located in a given EDIFACT message type.
///
/// Used by `dispatch_message` in `parse.rs` to select the correct extraction
/// strategy at parse time, driven by the profile registry rather than a
/// hardcoded message-type list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PidSource {
    /// The Prüfidentifikator is in BGM element 1 (DE 1004). This is the default
    /// for all EDI@Energy message types.
    #[default]
    BgmDe1004,
    /// The Prüfidentifikator is in the first top-level RFF segment with qualifier Z13
    /// (composite component 1 of element 0). Used by COMDIS and PRICAT.
    RffZ13,
}

// ── Profile trait ─────────────────────────────────────────────────────────────

/// A set of validation rules for one `(MessageType, Release)` combination.
///
/// Implementors are generated by `cargo xtask codegen` and registered at
/// process startup.
pub trait Profile: Send + Sync {
    /// The EDIFACT message type this profile applies to.
    fn message_type(&self) -> MessageType;

    /// The EDI@Energy release this profile applies to (e.g. `"5.5.3a"`).
    fn release(&self) -> &Release;

    /// First calendar date on which this profile is normatively valid.
    ///
    /// Derived from the profile directory name (`fv<YYYYMMDD>`).  Returns
    /// `None` for legacy profiles whose directory does not embed a date.
    fn valid_from(&self) -> Option<time::Date>;

    /// Last calendar date on which this profile is normatively valid.
    ///
    /// Derived from `valid_until` in `mig.json`.  Returns `None` when the
    /// profile has no published expiry date (open-ended).
    fn valid_until(&self) -> Option<time::Date> {
        None
    }

    /// AHB revision identifier for this profile (e.g. `"3.2"`, `"2.0h"`).
    ///
    /// May carry a correction letter that differs from the wire release code
    /// when BDEW issues an AHB correction without a MIG change.
    /// Returns `None` for profiles where no AHB revision is tracked.
    fn ahb_revision(&self) -> Option<&'static str> {
        None
    }

    /// BDEW source document title this profile was derived from.
    ///
    /// E.g. `"MSCONS AHB 3.2, Stand 01.10.2025"`. Returns `None` when not tracked.
    fn source_document(&self) -> Option<&'static str> {
        None
    }

    /// Where the Prüfidentifikator is located in messages of this type.
    ///
    /// The default implementation returns [`PidSource::BgmDe1004`], which is
    /// correct for all EDI@Energy message types except COMDIS and PRICAT.
    /// Generated profile implementations override this when the `mig.json`
    /// specifies `"pid_source": "rff_z13"`.
    fn pid_source(&self) -> PidSource {
        PidSource::BgmDe1004
    }

    /// The MIG (Marktkommunikation Implementation Guide) rule pack.
    ///
    /// Applied to every message of this type/release regardless of
    /// Pruefidentifikator.  Returns an `Arc` so callers can share the
    /// cached static pack without allocation.
    fn mig_rule_pack(&self) -> Arc<ProfileRulePack>;

    /// The AHB (Anwendungshandbuch) rule pack.
    ///
    /// When `pid` is `Some`, returns rules scoped to that process code only.
    /// When `pid` is `None`, returns the union of all PID-specific rules.
    /// An empty (zero-rule) pack is returned for unknown PIDs.
    /// Returns an `Arc` so callers share the cached static pack without allocation.
    fn ahb_rule_pack(&self, pid: Option<Pruefidentifikator>) -> Arc<ProfileRulePack>;

    /// Check whether `code` is a valid value for data element `de_id`.
    ///
    /// Returns `true` for unknown data elements (unknown ≠ invalid).
    fn is_code_valid(&self, de_id: &str, code: &str) -> bool;

    /// Return the alphabetically nearest allowed code for `de_id` as a spelling suggestion.
    ///
    /// Uses `partition_point` on the sorted code list to find the insertion point for `code`,
    /// then returns the adjacent entry.  The result is *alphabetically* (not semantically)
    /// nearest — callers should present it as "did you mean?" rather than a guaranteed match.
    ///
    /// Returns `None` when the element is unknown or has no registered values.
    fn suggest_code(&self, de_id: &str, code: &str) -> Option<&'static str>;

    /// Look up the static segment definition for `tag`, if known.
    fn segment_lookup(&self, tag: &str) -> Option<&'static SegmentDefinition>;

    /// Return the exhaustive list of allowed values for `de_id`,
    /// or `None` when the element is not in this release's code lists.
    fn code_list(&self, de_id: &str) -> Option<&'static [&'static str]>;

    /// Return a reference to the cached [`DirectoryValidator`] wired with this
    /// profile's segment definitions, code-list hooks, and expected-component counts.
    ///
    /// The validator is constructed once (at first access) and stored in a
    /// `static LazyLock` inside each generated profile module.  Returning a
    /// `&'static` reference eliminates per-call allocation on hot validation
    /// paths (resolves.
    ///
    /// Used by Layer 2 validation in the validation engine.
    fn directory_validator(&self) -> &'static DirectoryValidator;

    /// Static segment-group hierarchy schema for this profile.
    ///
    /// Used by [`edifact_rs::group_segments_indexed`] to build a
    /// [`edifact_rs::SegmentGroupIndexed`] tree, enabling group-aware validation
    /// (`validate_lenient_grouped`). Each scoped group rule closure receives only
    /// the segments within its specific group occurrence via `group.total_span`,
    /// implementing the per-SG-instance segment window.
    ///
    /// Returns an empty slice for profiles with no segment groups.
    fn group_schema(&self) -> &'static [edifact_rs::GroupDef] {
        &[]
    }
}

// Object-safety assertion.
const _: () = {
    fn _assert_object_safe(_: &dyn Profile) {}
};

// ── TransitionState ───────────────────────────────────────────────────────────

/// Number of calendar days on each side of a release-boundary date during which
/// both the outgoing and incoming format versions are accepted simultaneously.
///
/// This reflects the Übergangsfrist (transition grace period) specified in
/// GPKE §10 and `WiM` §12 (7 calendar days).
pub const TRANSITION_GRACE_DAYS: i64 = 7;

/// The normative dispatch state for a `(MessageType, date, track)` triple.
///
/// Produced by [`ReleaseRegistry::transition_state`] and
/// [`ProcessContext::transition_state`].  Callers should use this to decide
/// which profile(s) to accept when validating incoming messages.
///
/// # Usage
///
/// ```rust,ignore
/// match ctx.transition_state(MessageType::Mscons, None) {
///     TransitionState::Stable { profile } => {
///         // Exactly one active profile — validate against it.
///     }
///     TransitionState::Transition { outgoing, incoming } => {
///         // Grace period: accept messages conforming to either version.
///         // Both profiles must be tried; reject only when both fail.
///     }
///     TransitionState::None => {
///         // No profile active yet — pre-launch period.
///     }
/// }
/// ```
pub enum TransitionState<'r> {
    /// Exactly one profile is active on this date.
    Stable {
        /// The currently active profile.
        profile: &'r dyn Profile,
    },
    /// Two profiles overlap on this date (Übergangsfrist / transition grace period).
    ///
    /// Both `outgoing` and `incoming` must be accepted for incoming messages.
    /// For outgoing messages prefer `incoming` (the new standard), but `outgoing`
    /// is still conformant until the grace period ends.
    Transition {
        /// The profile expiring soon (`valid_until + TRANSITION_GRACE_DAYS ≥ date`).
        outgoing: &'r dyn Profile,
        /// The profile newly taking effect (`valid_from - TRANSITION_GRACE_DAYS ≤ date`).
        incoming: &'r dyn Profile,
    },
    /// No profile with `valid_from ≤ date` exists for this `(type, track)`.
    None,
}

impl std::fmt::Debug for TransitionState<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TransitionState::Stable { profile } => f
                .debug_struct("Stable")
                .field("release", &profile.release().as_str())
                .field("message_type", &profile.message_type())
                .finish(),
            TransitionState::Transition { outgoing, incoming } => f
                .debug_struct("Transition")
                .field("outgoing", &outgoing.release().as_str())
                .field("incoming", &incoming.release().as_str())
                .finish(),
            TransitionState::None => write!(f, "None"),
        }
    }
}

// ── Registry ──────────────────────────────────────────────────────────────────

/// Process-global registry mapping `(MessageType, Release)` → `&'static dyn Profile`.
#[derive(Clone)]
pub struct ReleaseRegistry {
    profiles: Vec<&'static dyn Profile>,
    /// Two-level index: `MessageType` → `release_str` → sorted list of profile indices.
    ///
    /// Multiple profiles may share the same wire release code (same `release` string)
    /// when BDEW issues a format revision without changing the EDIFACT version code
    /// (e.g. COMDIS `"1.0g"` appears in both `fv20251001` and `fv20261001`).
    /// The list is sorted ascending by `valid_from` so the date-aware selector can
    /// pick the correct entry efficiently.
    index: std::collections::HashMap<MessageType, std::collections::HashMap<Box<str>, Vec<usize>>>,
    /// Number of calendar days on each side of a release-boundary date during
    /// which both the outgoing and incoming versions are accepted simultaneously.
    ///
    /// Defaults to [`TRANSITION_GRACE_DAYS`] (7).  Override via
    /// [`ReleaseRegistry::with_transition_grace_days`] when contract or test
    /// requirements differ from the BDEW default.
    transition_grace_days: i64,
}

static REGISTRY: OnceLock<std::sync::Arc<ReleaseRegistry>> = OnceLock::new();

impl ReleaseRegistry {
    /// Build a new, empty registry and populate it with `profiles`.
    ///
    /// Use this in tests and benchmarks that need an isolated registry.
    /// Application code should use [`ReleaseRegistry::global()`] instead.
    #[must_use]
    pub fn new(profiles: Vec<&'static dyn Profile>) -> Self {
        let mut index: std::collections::HashMap<
            MessageType,
            std::collections::HashMap<Box<str>, Vec<usize>>,
        > = std::collections::HashMap::new();
        for (i, p) in profiles.iter().enumerate() {
            index
                .entry(p.message_type())
                .or_default()
                .entry(p.release().as_str().into())
                .or_default()
                .push(i);
        }
        // Sort each candidate list ascending by valid_from so date-range selection
        // (pick the latest valid_from that is ≤ query date) can use a simple scan.
        for type_map in index.values_mut() {
            for candidates in type_map.values_mut() {
                candidates.sort_by(|&a, &b| {
                    let va = profiles[a].valid_from();
                    let vb = profiles[b].valid_from();
                    va.cmp(&vb)
                });
            }
        }
        Self {
            profiles,
            index,
            transition_grace_days: TRANSITION_GRACE_DAYS,
        }
    }

    /// Override the grace period for this registry.
    ///
    /// The returned registry is independent of the global singleton.  Use this
    /// when building a [`crate::Platform`] for a specific tenant or test scenario
    /// that requires a different Übergangsfrist.
    ///
    /// # Example
    /// ```rust,no_run
    /// use edi_energy::registry::ReleaseRegistry;
    ///
    /// // Clone the global registry and apply a custom 14-day grace period.
    /// let custom = ReleaseRegistry::global().clone().with_transition_grace_days(14);
    /// assert_eq!(custom.transition_grace_days(), 14);
    /// ```
    #[must_use]
    pub fn with_transition_grace_days(mut self, days: i64) -> Self {
        self.transition_grace_days = days;
        self
    }

    /// The configured transition grace period in calendar days.
    #[must_use]
    pub fn transition_grace_days(&self) -> i64 {
        self.transition_grace_days
    }

    /// Return a reference to the global registry.
    ///
    /// Initialises the registry on first call (via `cargo xtask codegen`-generated
    /// profile stubs). Subsequent calls are lock-free reads.
    #[must_use]
    pub fn global() -> &'static Self {
        Self::global_arc()
    }

    /// Return an `Arc` clone of the global registry.
    ///
    /// Use this when you need an owned `Arc<ReleaseRegistry>` — for instance when
    /// constructing a [`ProcessContext`] or spawning tasks that need registry access
    /// without borrowing from a `'static` reference.
    #[must_use]
    pub fn global_arc() -> &'static std::sync::Arc<ReleaseRegistry> {
        REGISTRY.get_or_init(|| {
            let mut profiles: Vec<&'static dyn Profile> = Vec::new();
            generated::register_profiles(&mut profiles);
            std::sync::Arc::new(Self::new(profiles))
        })
    }

    /// Look up the profile for a `(message_type, release)` pair.
    ///
    /// When the same wire release code identifies multiple profiles (e.g. COMDIS
    /// `"1.0g"` is used for both `fv20251001` and `fv20261001`), the profile with
    /// the greatest `valid_from` that is ≤ today's UTC date is returned.  When all
    /// candidate profiles lack a `valid_from`, the last registered one is returned.
    ///
    /// For an explicit date query use [`profile_on`][Self::profile_on].
    ///
    /// # Errors
    ///
    /// Returns [`Error::ProfileNotFound`] when no profile has been registered for
    /// the given combination.
    pub fn profile(
        &self,
        message_type: MessageType,
        release: &Release,
    ) -> Result<&dyn Profile, Error> {
        self.profile_on(
            message_type,
            release,
            time::OffsetDateTime::now_utc().date(),
        )
    }

    /// Like [`profile`][Self::profile] but disambiguates same-wire-code profiles
    /// against `date` rather than today.
    ///
    /// Returns the profile with the greatest `valid_from ≤ date`.
    ///
    /// When all candidate profiles lack a `valid_from` (legacy profiles), the
    /// last registered one is returned as before.  When all candidates have a
    /// `valid_from` that is strictly in the future relative to `date`,
    /// [`Error::ProfileNotYetActive`] is returned — the previous behaviour of
    /// silently returning the most-future-dated profile is gone.
    ///
    /// # Wire-code collisions
    ///
    /// BDEW occasionally reuses the same EDIFACT release string across two
    /// consecutive format versions.  The date parameter is therefore **required**
    /// for correct dispatch — `profile()` falls back to today when called without
    /// an explicit date.
    ///
    /// Known collisions (as of 2026):
    ///
    /// | Message type | Wire code | Profiles |
    /// |--------------|-----------|---------|
    /// | INVOIC       | `"2.8e"`  | `fv20251001` (valid from 2025-10-01) and `fv20260401` (valid from 2026-04-01) |
    /// | UTILTS       | `"1.1e"`  | `fv20241001` (valid from 2024-10-01) and `fv20260401` (valid from 2026-04-01) |
    ///
    /// UTILMD Strom and Gas do **not** have collisions: the FV2024-10-01 profiles
    /// carry wire codes `"S1.1a"` / `"G1.0a"`, while `fv20251001` uses `"S2.1"` /
    /// `"G1.1"` — distinct codes, no disambiguation needed.
    ///
    /// When a collision is resolved by date, a `DEBUG`-level trace event is
    /// emitted (requires the `tracing` feature):
    ///
    /// ```text
    /// edi_energy::registry: wire_code_collision_resolved
    ///   message_type=INVOIC release="2.8e" date=2025-11-01
    ///   resolved_to="fv20251001" candidates=2
    /// ```
    ///
    /// # Errors
    ///
    /// - [`Error::ProfileNotFound`] — no profile has been registered for the
    ///   given message type + release combination.
    /// - [`Error::ProfileNotYetActive`] — profiles are registered but none has
    ///   `valid_from ≤ date`; the nearest future profile is reported as context.
    ///
    /// # Panics
    ///
    /// Panics if the internal candidate index is inconsistent (should be
    /// unreachable with a correctly built registry).
    pub fn profile_on(
        &self,
        message_type: MessageType,
        release: &Release,
        date: time::Date,
    ) -> Result<&dyn Profile, Error> {
        let candidates = self
            .index
            .get(&message_type)
            .and_then(|m| m.get(release.as_str()))
            .ok_or_else(|| {
                // Before returning a generic `ProfileNotFound`, check whether
                // the combination is a known archived profile gated behind a
                // disabled feature so we can surface a more actionable error.
                let mt_str = message_type.as_str();
                if let Some(feat) =
                    crate::generated::archived_profile_feature(mt_str, release.as_str())
                {
                    Error::ProfileArchived {
                        message_type,
                        release: release.clone(),
                        feature_flag: feat,
                    }
                } else {
                    Error::ProfileNotFound {
                        message_type,
                        release: release.clone(),
                    }
                }
            })?;

        // Pick the candidate with the greatest valid_from ≤ date.
        if let Some(&idx) = candidates
            .iter()
            .rfind(|&&i| self.profiles[i].valid_from().is_none_or(|vf| vf <= date))
        {
            // When multiple profiles share the same wire code (collision), emit a
            // debug trace so operators can verify the correct profile was selected.
            #[cfg(feature = "tracing")]
            if candidates.len() > 1 {
                tracing::debug!(
                    message_type = ?message_type,
                    release = release.as_str(),
                    date = %date,
                    resolved_to = self.profiles[idx].release().as_str(),
                    candidates = candidates.len(),
                    "wire_code_collision_resolved",
                );
            }
            return Ok(self.profiles[idx]);
        }

        // No candidate satisfied valid_from ≤ date.
        // If every candidate lacks a valid_from, they are legacy/undated profiles;
        // return the last one (pre-existing behaviour for legacy profiles).
        let all_undated = candidates
            .iter()
            .all(|&i| self.profiles[i].valid_from().is_none());
        if all_undated {
            let idx = *candidates.last().expect("candidates is non-empty");
            return Ok(self.profiles[idx]);
        }

        // At least one candidate has a valid_from, but all are in the future.
        // Return ProfileNotYetActive with the earliest future profile as context.
        let (_earliest_idx, earliest_vf) = candidates
            .iter()
            .filter_map(|&i| self.profiles[i].valid_from().map(|vf| (i, vf)))
            .min_by_key(|(_, vf)| *vf)
            .expect("at least one dated candidate exists");
        Err(Error::ProfileNotYetActive {
            message_type,
            release: release.clone(),
            valid_from: earliest_vf,
            date,
        })
    }

    /// Return all registered profiles.
    #[must_use]
    pub fn all_profiles(&self) -> &[&'static dyn Profile] {
        &self.profiles
    }

    /// Return all profiles for a given message type.
    pub fn profiles_for(&self, message_type: MessageType) -> impl Iterator<Item = &dyn Profile> {
        self.profiles
            .iter()
            .filter(move |p| p.message_type() == message_type)
            .copied()
    }

    /// Returns `true` if at least one registered profile for `message_type`
    /// has one or more AHB rules for `pid`.
    ///
    /// Returns `false` when no profile exists for `message_type`, or when all
    /// matching profiles return an empty rule pack for `pid` — which is the
    /// case for unknown or not-yet-imported Prüfidentifikatoren.
    ///
    /// Use this to detect **vacuous validation**: `msg.validate()` always
    /// returns `Ok(report)` with `report.is_valid() == true` when the AHB
    /// rule pack for a PID is empty, making it impossible from the report
    /// alone to distinguish a genuinely-validated message from one that
    /// passed only because no rules were checked.
    ///
    /// # Example
    /// ```rust,no_run
    /// use edi_energy::{MessageType, Pruefidentifikator, registry::ReleaseRegistry};
    ///
    /// let has_rules = ReleaseRegistry::global()
    ///     .pid_has_ahb_rules(MessageType::Utilmd, Pruefidentifikator::new(55001).unwrap());
    /// assert!(has_rules, "PID 55001 must have an AHB profile");
    /// ```
    #[must_use]
    pub fn pid_has_ahb_rules(&self, message_type: MessageType, pid: Pruefidentifikator) -> bool {
        self.profiles_for(message_type)
            .any(|p| p.ahb_rule_pack(Some(pid)).rule_count() > 0)
    }

    /// Return all known releases for a message type in ascending semantic order.
    ///
    /// Within-track releases (e.g. `"2.5a"` → `"2.10a"`) are ordered correctly
    /// by their numeric components.  Cross-track releases fall back to byte order.
    ///
    /// Returns an empty vec when no profiles are registered for `message_type`.
    #[must_use]
    pub fn releases(&self, message_type: MessageType) -> Vec<&Release> {
        let mut releases: Vec<&Release> = self
            .profiles
            .iter()
            .filter(|p| p.message_type() == message_type)
            .map(|p| p.release())
            .collect();
        releases.sort();
        releases.dedup_by_key(|r| r.as_str());
        releases
    }

    /// Return all distinct BDEW format-version strings present in the registry,
    /// sorted chronologically.
    ///
    /// A format version is derived from each profile's [`Profile::valid_from`]
    /// date: a profile with `valid_from = 2025-10-01` contributes
    /// `"FV2025-10-01"`.  Profiles without a `valid_from` date are skipped.
    ///
    /// The returned strings are suitable for passing directly to
    /// `FormatVersion::parse` in `mako-engine`.
    ///
    /// # Example
    /// ```rust,no_run
    /// use edi_energy::registry::ReleaseRegistry;
    ///
    /// let fvs = ReleaseRegistry::global().format_versions();
    /// assert!(fvs.iter().any(|v| v == "FV2025-10-01"));
    /// ```
    #[must_use]
    pub fn format_versions(&self) -> Vec<String> {
        let mut dates: Vec<time::Date> = self
            .profiles
            .iter()
            .filter_map(|p| p.valid_from())
            .collect();
        dates.sort();
        dates.dedup();
        dates
            .into_iter()
            .map(|d| format!("FV{:04}-{:02}-{:02}", d.year(), d.month() as u8, d.day()))
            .collect()
    }

    /// Return the semantically greatest (latest) release for `message_type`
    /// within the same release track as `reference`.
    ///
    /// Only profiles whose release kind matches `reference.kind()` are
    /// considered, avoiding the undefined cross-track ordering that
    /// [`latest_for_track`][Self::latest_for_track] can produce.
    ///
    /// Returns `None` when no profiles on the same track are registered.
    #[must_use]
    pub fn latest_for_track(
        &self,
        message_type: MessageType,
        reference: &Release,
    ) -> Option<&Release> {
        let kind = reference.kind();
        let mut releases: Vec<&Release> = self
            .profiles
            .iter()
            .filter(|p| p.message_type() == message_type && p.release().kind().same_track(&kind))
            .map(|p| p.release())
            .collect();
        releases.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        releases.into_iter().next_back()
    }

    /// Find the profile active on `date` for messages on a specific release track.
    ///
    /// Use this when a message type has multiple parallel format tracks —
    /// for example UTILMD Strom (`ReleaseTrack::Strom`) and UTILMD Gas
    /// (`ReleaseTrack::Gas`).
    ///
    /// Resolves  uses the explicit `ReleaseTrack` enum for dispatch
    /// instead of string-prefix matching, ensuring forward-compatibility when
    /// BDEW introduces new tracks with codes that share prefixes.
    ///
    /// Returns the profile with the greatest `valid_from ≤ date` among those
    /// on the given track.  Returns `None` when no matching profile is found.
    #[must_use]
    pub fn profile_for_date_and_track(
        &self,
        message_type: MessageType,
        date: time::Date,
        track: &crate::release::ReleaseTrack,
    ) -> Option<&dyn Profile> {
        // Deterministic tie-breaking: latest valid_from wins; release string as secondary key.
        self.profiles
            .iter()
            .filter(|p| p.message_type() == message_type)
            .filter(|p| &p.release().track() == track)
            .filter_map(|p| p.valid_from().map(|vf| (vf, *p)))
            .filter(|(vf, _)| *vf <= date)
            .max_by(|(va, pa), (vb, pb)| {
                va.cmp(vb)
                    .then(pa.release().as_str().cmp(pb.release().as_str()))
            })
            .map(|(_, p)| p)
    }

    /// Determine whether a message with the given wire `release` code is normatively
    /// acceptable on `date`, considering the [`TRANSITION_GRACE_DAYS`] window.
    ///
    /// Returns `true` when:
    /// - The profile for `(message_type, release)` has `valid_from ≤ date` **and**
    ///   either no `valid_until` or `valid_until + TRANSITION_GRACE_DAYS ≥ date`.
    /// - The profile is not yet expired (past its grace window).
    ///
    /// Returns `false` when no such profile is registered or the profile is
    /// outside the acceptable date window.
    #[must_use]
    pub fn is_acceptable_on(
        &self,
        message_type: MessageType,
        release: &Release,
        date: time::Date,
    ) -> bool {
        let Ok(profile) = self.profile_on(message_type, release, date) else {
            return false;
        };
        let Some(valid_from) = profile.valid_from() else {
            // No date information — assume always valid (legacy profile).
            return true;
        };
        if valid_from > date {
            return false;
        }
        if let Some(valid_until) = profile.valid_until() {
            // Accept during the grace period: valid_until + transition_grace_days.
            let grace_end = valid_until + time::Duration::days(self.transition_grace_days);
            if date > grace_end {
                return false;
            }
        }
        true
    }

    /// Return the [`TransitionState`] for `(message_type, date)`.
    ///
    /// When `track_prefix` is `Some`, only profiles whose release code begins
    /// with that prefix are considered (e.g. `"S"` for UTILMD Strom).
    ///
    /// # Algorithm
    ///
    /// 1. Find the profile with the greatest `valid_from ≤ date` — this is the
    ///    "current" profile.
    /// 2. Check whether the current profile is in its outgoing grace window:
    ///    `valid_until` is set and `valid_until + TRANSITION_GRACE_DAYS ≥ date`.
    /// 3. If so, look for a successor profile whose `valid_from` is within the
    ///    grace window: `valid_from - TRANSITION_GRACE_DAYS ≤ date ≤ valid_from`.
    /// 4. Return `Transition { outgoing, incoming }` when both conditions hold,
    ///    `Stable { profile }` otherwise.
    ///
    /// # Panics
    ///
    /// Panics if a profile whose `valid_from` was verified non-`None` in step 1
    /// returns `None` in step 3 (should be unreachable).
    #[must_use]
    pub fn transition_state(
        &self,
        message_type: MessageType,
        date: time::Date,
        track_prefix: Option<&str>,
    ) -> TransitionState<'_> {
        // Candidate profiles restricted to the given track (if any).
        let candidates: Vec<&dyn Profile> = self
            .profiles
            .iter()
            .filter(|p| p.message_type() == message_type)
            .filter(|p| track_prefix.is_none_or(|pfx| p.release().as_str().starts_with(pfx)))
            .copied()
            .collect();

        // Step 1: current = profile with greatest valid_from ≤ date.
        // Tie-break by release string (descending) for determinism.
        let current = candidates
            .iter()
            .filter_map(|p| p.valid_from().map(|vf| (vf, *p)))
            .filter(|(vf, _)| *vf <= date)
            .max_by(|(va, pa), (vb, pb)| {
                va.cmp(vb)
                    .then(pa.release().as_str().cmp(pb.release().as_str()))
            })
            .map(|(_, p)| p);

        let Some(current) = current else {
            return TransitionState::None;
        };

        // Step 2: is the current profile in its outgoing grace window?
        let in_outgoing_grace = current.valid_until().is_some_and(|vu| {
            let grace_end = vu + time::Duration::days(self.transition_grace_days);
            date >= vu && date <= grace_end
        });

        if !in_outgoing_grace {
            return TransitionState::Stable { profile: current };
        }

        // Step 3: look for a successor whose valid_from is within the grace window.
        let current_valid_from = current.valid_from().unwrap();
        let incoming = candidates
            .iter()
            .filter_map(|p| p.valid_from().map(|vf| (vf, *p)))
            // Must be strictly after the current profile.
            .filter(|(vf, _)| *vf > current_valid_from)
            // Its valid_from must fall within date ± GRACE_DAYS.
            .filter(|(vf, _)| {
                let earliest = *vf - time::Duration::days(self.transition_grace_days);
                date >= earliest
            })
            .min_by_key(|(vf, _)| *vf)
            .map(|(_, p)| p);

        match incoming {
            Some(incoming) => TransitionState::Transition {
                outgoing: current,
                incoming,
            },
            None => TransitionState::Stable { profile: current },
        }
    }
}

// ── ProcessContext ────────────────────────────────────────────────────────────

/// A calendar-date-aware dispatch context for building and validating
/// EDI@Energy messages.
///
/// `ProcessContext` selects the normatively-active profile for each message
/// type based on a date, so callers never need to hard-code release strings.
/// When BDEW publishes a new format version and the profile is registered,
/// `ProcessContext::current()` automatically switches to it on the effective
/// date — **no code change at the call site is required**.
///
/// Both global and isolated registries are supported:
/// - [`ProcessContext::current()`] / [`ProcessContext::for_date()`] use the
///   process-global registry (suitable for single-process applications).
/// - [`Platform::process_context()`][crate::Platform::process_context] creates a
///   context backed by the platform's own isolated registry (required for
///   multi-tenant servers and test isolation).
///
/// # Example
///
/// ```rust,no_run
/// use edi_energy::ProcessContext;
///
/// let ctx = ProcessContext::current();
/// let release = ctx.active_release(edi_energy::MessageType::Mscons)
///     .expect("MSCONS profile must be registered");
/// assert!(!release.as_str().is_empty());
/// ```
#[derive(Clone)]
pub struct ProcessContext {
    date: time::Date,
    registry: std::sync::Arc<ReleaseRegistry>,
}

impl ProcessContext {
    /// Create a context for messages valid on a specific `date`, backed by
    /// the process-global registry.
    ///
    /// Use [`Platform::process_context()`][crate::Platform::process_context] instead
    /// when working with an isolated registry.
    #[must_use]
    pub fn for_date(date: time::Date) -> Self {
        Self {
            date,
            registry: std::sync::Arc::clone(ReleaseRegistry::global_arc()),
        }
    }

    /// Create a context for `date` backed by an explicit registry.
    ///
    /// This is the low-level constructor used by
    /// [`Platform::process_context()`][crate::Platform::process_context].
    /// Most application code should use [`ProcessContext::for_date`] or
    /// [`ProcessContext::current`].
    #[must_use]
    pub fn for_date_with_registry(
        date: time::Date,
        registry: std::sync::Arc<ReleaseRegistry>,
    ) -> Self {
        Self { date, registry }
    }

    /// Create a context using today's UTC date, backed by the global registry.
    #[must_use]
    pub fn current() -> Self {
        Self::for_date(time::OffsetDateTime::now_utc().date())
    }

    /// The date this context is anchored to.
    #[must_use]
    pub fn date(&self) -> time::Date {
        self.date
    }

    /// Return the release that is normatively active for `message_type` on
    /// this context's date.
    ///
    /// Returns `None` when no profile with a `valid_from` ≤ `date` is
    /// registered for the type.  For message types with multiple parallel tracks
    /// (e.g. UTILMD Strom / Gas), use [`active_release_for_track`][Self::active_release_for_track]
    /// to get a deterministic result.
    #[must_use]
    pub fn active_release(&self, message_type: MessageType) -> Option<&Release> {
        self.registry
            .profiles_for(message_type)
            .filter_map(|p| p.valid_from().map(|vf| (vf, p)))
            .filter(|(vf, _)| *vf <= self.date)
            .max_by(|(va, pa), (vb, pb)| {
                va.cmp(vb)
                    .then(pa.release().as_str().cmp(pb.release().as_str()))
            })
            .map(|(_, p)| p.release())
    }

    /// Return the profile that is normatively active for `message_type` on
    /// this context's date.
    ///
    /// Returns `None` when no profile is active on this date.  For message types
    /// with multiple parallel tracks, use [`active_profile_for_track`][Self::active_profile_for_track].
    #[must_use]
    pub fn active_profile(&self, message_type: MessageType) -> Option<&dyn Profile> {
        self.registry
            .profiles_for(message_type)
            .filter_map(|p| p.valid_from().map(|vf| (vf, p)))
            .filter(|(vf, _)| *vf <= self.date)
            .max_by(|(va, pa), (vb, pb)| {
                va.cmp(vb)
                    .then(pa.release().as_str().cmp(pb.release().as_str()))
            })
            .map(|(_, p)| p)
    }

    /// Return the release active for `message_type` on this date, restricted
    /// to profiles on the given `track`.
    ///
    /// Use this when a message type has parallel format tracks:
    /// - UTILMD Strom: `track = ReleaseTrack::Strom`
    /// - UTILMD Gas:   `track = ReleaseTrack::Gas`
    ///
    /// Returns `None` when no profile on the given track is active on this date.
    #[must_use]
    pub fn active_release_for_track(
        &self,
        message_type: MessageType,
        track: &crate::release::ReleaseTrack,
    ) -> Option<&Release> {
        self.registry
            .profile_for_date_and_track(message_type, self.date, track)
            .map(Profile::release)
    }

    /// Return the profile active for `message_type` on this date, restricted
    /// to the given release track.  See [`active_release_for_track`][Self::active_release_for_track].
    #[must_use]
    pub fn active_profile_for_track(
        &self,
        message_type: MessageType,
        track: &crate::release::ReleaseTrack,
    ) -> Option<&dyn Profile> {
        self.registry
            .profile_for_date_and_track(message_type, self.date, track)
    }

    /// Return the [`TransitionState`] for `message_type` on this context's date.
    ///
    /// When `track_prefix` is `Some`, only profiles on that release track are
    /// considered (e.g. `Some("S")` for UTILMD Strom, `Some("G")` for Gas).
    /// Pass `None` for message types with a single release track.
    ///
    /// See [`TransitionState`] for the three possible outcomes and their
    /// handling implications.
    #[must_use]
    pub fn transition_state(
        &self,
        message_type: MessageType,
        track_prefix: Option<&str>,
    ) -> TransitionState<'_> {
        self.registry
            .transition_state(message_type, self.date, track_prefix)
    }

    /// Check whether a message carrying the given wire `release` code is
    /// normatively acceptable on this context's date.
    ///
    /// Delegates to [`ReleaseRegistry::is_acceptable_on`].
    #[must_use]
    pub fn is_acceptable(&self, message_type: MessageType, release: &Release) -> bool {
        self.registry
            .is_acceptable_on(message_type, release, self.date)
    }
}