ferrocat-po 1.2.1

Performance-first PO parsing, serialization, and catalog update primitives for ferrocat.
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
use std::collections::BTreeMap;

use ferrocat_icu::{IcuFormatter, IcuFormatterSupport};

use super::{
    ApiError, CatalogMessageKey, CatalogSemantics, IcuSyntaxPolicy, NormalizedParsedCatalog,
    compile::{
        compiled_catalog_translation_kind_for_message, compiled_key_for,
        describe_compiled_id_catalogs,
    },
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// JSON schema version emitted by [`CompiledCatalogArtifact`] serialization.
pub const COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION: u16 = 1;

/// Translation value stored in a compiled runtime catalog.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(tag = "kind", content = "value", rename_all = "snake_case")
)]
pub enum CompiledTranslation {
    /// Singular runtime value.
    Singular(String),
    /// Structured plural runtime value.
    Plural(BTreeMap<String, String>),
}

/// Built-in key strategy used when compiling runtime catalogs.
///
/// This enum is non-exhaustive so additional stable key strategies can be added
/// without breaking downstream matches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum CompiledKeyStrategy {
    /// `ferrocat` v1 key format: SHA-256 over a versioned, length-delimited
    /// `msgctxt`/`msgid` payload, truncated to 64 bits and encoded as unpadded
    /// `Base64URL`.
    #[default]
    FerrocatV1,
}

/// Callback used to validate runtime support for ICU formatters.
///
/// The callback receives each formatter discovered in a final runtime ICU
/// message and returns whether that runtime supports the formatter kind and
/// style.
///
/// This is intentionally a non-capturing function pointer so ICU options stay
/// cheap to copy.
pub type IcuFormatterSupportPolicy = fn(&IcuFormatter) -> IcuFormatterSupport;

/// Options controlling runtime catalog compilation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileCatalogOptions<'a> {
    /// Built-in strategy used to derive stable runtime keys.
    pub key_strategy: CompiledKeyStrategy,
    /// Whether empty source-locale values should be filled from the source text.
    pub source_fallback: bool,
    /// Source locale used when `source_fallback` is enabled.
    pub source_locale: Option<&'a str>,
    /// High-level semantics used by the input catalog set.
    pub semantics: CatalogSemantics,
}

impl Default for CompileCatalogOptions<'_> {
    fn default() -> Self {
        Self {
            key_strategy: CompiledKeyStrategy::FerrocatV1,
            source_fallback: false,
            source_locale: None,
            semantics: CatalogSemantics::IcuNative,
        }
    }
}

impl CompileCatalogOptions<'_> {
    /// Creates runtime catalog compile options with default behavior.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// Options controlling high-level compiled catalog artifact generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileCatalogArtifactOptions<'a> {
    /// Locale for which the runtime artifact should be produced.
    pub requested_locale: &'a str,
    /// Source locale used for explicit source fallback behavior.
    pub source_locale: &'a str,
    /// Ordered fallback locales consulted after the requested locale.
    pub fallback_chain: &'a [String],
    /// Built-in strategy used to derive stable runtime keys.
    pub key_strategy: CompiledKeyStrategy,
    /// Whether source text should be used when no non-source translation exists.
    pub source_fallback: bool,
    /// Whether invalid final ICU messages should fail compilation instead of producing diagnostics.
    pub strict_icu: bool,
    /// Whether final ICU messages should be checked against source ICU structure.
    pub icu_compatibility: bool,
    /// High-level semantics used by the input catalog set.
    pub semantics: CatalogSemantics,
}

impl<'a> CompileCatalogArtifactOptions<'a> {
    /// Creates artifact compile options with required locales set.
    ///
    /// Optional fields use the same defaults that the previous `Default`
    /// implementation provided.
    #[must_use]
    pub fn new(requested_locale: &'a str, source_locale: &'a str) -> Self {
        Self {
            requested_locale,
            source_locale,
            fallback_chain: &[],
            key_strategy: CompiledKeyStrategy::FerrocatV1,
            source_fallback: false,
            strict_icu: false,
            icu_compatibility: false,
            semantics: CatalogSemantics::IcuNative,
        }
    }
}

/// ICU-specific options used while compiling catalog artifacts.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct CompileCatalogArtifactIcuOptions {
    /// ICU parser behavior used for final runtime message validation.
    pub syntax_policy: IcuSyntaxPolicy,
    /// Optional runtime support policy for ICU formatter kinds and styles.
    pub formatter_support: Option<IcuFormatterSupportPolicy>,
}

impl CompileCatalogArtifactIcuOptions {
    /// Creates artifact ICU options with default strict parser behavior.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns options that parse messages with the given ICU syntax policy.
    #[must_use]
    pub fn with_syntax_policy(mut self, syntax_policy: IcuSyntaxPolicy) -> Self {
        self.syntax_policy = syntax_policy;
        self
    }

    /// Returns options that validate formatter support with the given callback.
    #[must_use]
    pub fn with_formatter_support(mut self, formatter_support: IcuFormatterSupportPolicy) -> Self {
        self.formatter_support = Some(formatter_support);
        self
    }
}

/// Options controlling selected-subset compiled catalog artifact generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileSelectedCatalogArtifactOptions<'a> {
    /// Requested compiled runtime IDs to include in the artifact.
    pub compiled_ids: &'a [String],
    /// Shared artifact compile options applied to the selected IDs.
    pub options: CompileCatalogArtifactOptions<'a>,
}

impl<'a> CompileSelectedCatalogArtifactOptions<'a> {
    /// Creates selected artifact compile options with required locales and IDs set.
    ///
    /// Optional fields use the same defaults that the previous `Default`
    /// implementation provided.
    #[must_use]
    pub fn new(
        requested_locale: &'a str,
        source_locale: &'a str,
        compiled_ids: &'a [String],
    ) -> Self {
        Self {
            compiled_ids,
            options: CompileCatalogArtifactOptions::new(requested_locale, source_locale),
        }
    }
}

/// Message selection for [`super::compile_catalog_artifact_report`].
#[derive(Debug, Clone, Copy)]
pub enum CompileCatalogArtifactReportSelection<'a> {
    /// Compile and report every non-obsolete source identity available in the catalog set.
    All,
    /// Compile and report only the requested compiled runtime IDs.
    Selected {
        /// Stable ID index used to map compiled IDs back to source identities.
        index: &'a CompiledCatalogIdIndex,
        /// Requested compiled runtime IDs to include in the artifact and provenance report.
        compiled_ids: &'a [String],
    },
}

/// Options controlling compiled artifact generation with a sibling provenance report.
#[derive(Debug, Clone)]
pub struct CompileCatalogArtifactReportOptions<'a> {
    /// Shared artifact compile options applied to the generated artifact.
    pub options: CompileCatalogArtifactOptions<'a>,
    /// ICU-specific options applied while validating final runtime messages.
    pub icu_options: CompileCatalogArtifactIcuOptions,
    /// Source identity selection for the generated artifact and provenance report.
    pub selection: CompileCatalogArtifactReportSelection<'a>,
}

impl<'a> CompileCatalogArtifactReportOptions<'a> {
    /// Creates report compile options for every non-obsolete source identity.
    #[must_use]
    pub fn new(requested_locale: &'a str, source_locale: &'a str) -> Self {
        Self {
            options: CompileCatalogArtifactOptions::new(requested_locale, source_locale),
            icu_options: CompileCatalogArtifactIcuOptions::new(),
            selection: CompileCatalogArtifactReportSelection::All,
        }
    }

    /// Creates report compile options for a selected subset of compiled runtime IDs.
    #[must_use]
    pub fn selected(
        requested_locale: &'a str,
        source_locale: &'a str,
        index: &'a CompiledCatalogIdIndex,
        compiled_ids: &'a [String],
    ) -> Self {
        Self {
            options: CompileCatalogArtifactOptions::new(requested_locale, source_locale),
            icu_options: CompileCatalogArtifactIcuOptions::new(),
            selection: CompileCatalogArtifactReportSelection::Selected {
                index,
                compiled_ids,
            },
        }
    }
}

/// High-level translation kind associated with a compiled runtime ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum CompiledCatalogTranslationKind {
    /// Translation is a single string value.
    Singular,
    /// Translation is a plural/category map.
    Plural,
}

/// A compiled runtime message keyed by a derived lookup key.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledMessage {
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Materialized translation payload for runtime lookup.
    pub translation: CompiledTranslation,
}

/// Runtime-oriented lookup structure compiled from a normalized catalog.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalog {
    pub(super) entries: BTreeMap<String, CompiledMessage>,
}

impl CompiledCatalog {
    /// Returns the compiled message for `key`, if present.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&CompiledMessage> {
        self.entries.get(key)
    }

    /// Returns the number of compiled entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` when the compiled catalog has no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Iterates over compiled entries in key order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &CompiledMessage)> + '_ {
        self.entries
            .iter()
            .map(|(key, message)| (key.as_str(), message))
    }
}

/// Stable compiled runtime ID index built from one or more normalized catalogs.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogIdIndex {
    pub(super) ids: BTreeMap<String, CatalogMessageKey>,
}

/// Metadata describing one compiled runtime ID for a specific catalog set.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogIdDescription {
    /// Stable runtime ID derived from the source identity.
    pub compiled_id: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Locales from the provided catalog set that contain this non-obsolete message.
    pub available_locales: Vec<String>,
    /// Whether the message is singular or plural in the provided catalog set.
    pub translation_kind: CompiledCatalogTranslationKind,
}

/// Report returned by [`CompiledCatalogIdIndex::describe_compiled_ids`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct DescribeCompiledIdsReport {
    /// Metadata for requested IDs that were known to the index and present in the provided catalogs.
    pub described: Vec<CompiledCatalogIdDescription>,
    /// Requested compiled IDs that were not known to the index at all.
    pub unknown_compiled_ids: Vec<String>,
    /// Requested compiled IDs that were known to the index but not present in the provided catalogs.
    pub unavailable_compiled_ids: Vec<CompiledCatalogUnavailableId>,
}

/// Known compiled runtime ID that was not present in the provided catalog set.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogUnavailableId {
    /// Stable runtime ID derived from the source identity.
    pub compiled_id: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
}

impl CompiledCatalogIdIndex {
    /// Builds a deterministic compiled-ID index for the union of non-obsolete messages.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError::Conflict`] when two different source identities compile to the same ID.
    pub fn new(
        catalogs: &[&NormalizedParsedCatalog],
        key_strategy: CompiledKeyStrategy,
    ) -> Result<Self, ApiError> {
        Self::new_with_key_generator(catalogs, key_strategy, compiled_key_for)
    }

    pub(super) fn new_with_key_generator<F>(
        catalogs: &[&NormalizedParsedCatalog],
        key_strategy: CompiledKeyStrategy,
        mut key_generator: F,
    ) -> Result<Self, ApiError>
    where
        F: FnMut(CompiledKeyStrategy, &CatalogMessageKey) -> String,
    {
        let mut ids = BTreeMap::<String, CatalogMessageKey>::new();

        for catalog in catalogs {
            for (source_key, message) in catalog.iter() {
                if message.obsolete {
                    continue;
                }
                let compiled_id = key_generator(key_strategy, source_key);
                if let Some(existing) = ids.get(&compiled_id) {
                    if existing != source_key {
                        return Err(ApiError::Conflict(format!(
                            "compiled catalog key collision for {:?} / {:?} and {:?} / {:?} using key {}",
                            existing.msgctxt,
                            existing.msgid,
                            source_key.msgctxt,
                            source_key.msgid,
                            compiled_id
                        )));
                    }
                    continue;
                }
                ids.insert(compiled_id, source_key.clone());
            }
        }

        Ok(Self { ids })
    }

    /// Returns the source key for `compiled_id`, if present.
    #[must_use]
    pub fn get(&self, compiled_id: &str) -> Option<&CatalogMessageKey> {
        self.ids.get(compiled_id)
    }

    /// Returns `true` when the index contains `compiled_id`.
    #[must_use]
    pub fn contains_id(&self, compiled_id: &str) -> bool {
        self.ids.contains_key(compiled_id)
    }

    /// Returns the number of indexed compiled IDs.
    #[must_use]
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    /// Returns `true` when the index contains no compiled IDs.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    /// Iterates over compiled IDs in sorted order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &CatalogMessageKey)> + '_ {
        self.ids
            .iter()
            .map(|(compiled_id, source_key)| (compiled_id.as_str(), source_key))
    }

    /// Returns the underlying ordered compiled-ID map by reference.
    #[must_use]
    pub fn as_btreemap(&self) -> &BTreeMap<String, CatalogMessageKey> {
        &self.ids
    }

    /// Consumes the index and returns the underlying ordered compiled-ID map.
    #[must_use]
    pub fn into_btreemap(self) -> BTreeMap<String, CatalogMessageKey> {
        self.ids
    }

    /// Describes selected compiled IDs against a provided catalog set.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError::InvalidArguments`] when a provided catalog does not declare
    /// a locale, or [`ApiError::Conflict`] when the same compiled ID maps to different
    /// translation kinds across the provided catalogs.
    pub fn describe_compiled_ids(
        &self,
        catalogs: &[&NormalizedParsedCatalog],
        compiled_ids: &[String],
    ) -> Result<DescribeCompiledIdsReport, ApiError> {
        let locales = describe_compiled_id_catalogs(catalogs)?;
        let mut report = DescribeCompiledIdsReport::default();

        for compiled_id in std::collections::BTreeSet::from_iter(compiled_ids.iter().cloned()) {
            let Some(source_key) = self.get(&compiled_id).cloned() else {
                report.unknown_compiled_ids.push(compiled_id);
                continue;
            };

            let mut available_locales = Vec::new();
            let mut translation_kind = None;

            for (locale, catalog) in &locales {
                let Some(message) = catalog.get(&source_key) else {
                    continue;
                };
                if message.obsolete {
                    continue;
                }
                let next_kind = compiled_catalog_translation_kind_for_message(
                    catalog.parsed_catalog().semantics,
                    message,
                );
                if let Some(existing_kind) = translation_kind {
                    if existing_kind != next_kind {
                        return Err(ApiError::Conflict(format!(
                            "compiled ID {:?} resolves to inconsistent translation shapes across the provided catalogs",
                            compiled_id
                        )));
                    }
                } else {
                    translation_kind = Some(next_kind);
                }
                available_locales.push(locale.clone());
            }

            if let Some(translation_kind) = translation_kind {
                report.described.push(CompiledCatalogIdDescription {
                    compiled_id,
                    source_key,
                    available_locales,
                    translation_kind,
                });
            } else {
                report
                    .unavailable_compiled_ids
                    .push(CompiledCatalogUnavailableId {
                        compiled_id,
                        source_key,
                    });
            }
        }

        Ok(report)
    }
}

/// Host-neutral compiled runtime artifact for one requested locale.
///
/// When the `serde` feature is enabled, this type serializes with
/// [`COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION`] as a required
/// `schema_version` field. Deserialization rejects unknown artifact schema
/// versions.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CompiledCatalogArtifact {
    /// Final runtime message map keyed by the derived lookup key.
    pub messages: BTreeMap<String, String>,
    /// Messages that were missing from the requested locale and had to fall back.
    pub missing: Vec<CompiledCatalogMissingMessage>,
    /// Diagnostics collected while validating final runtime messages.
    pub diagnostics: Vec<CompiledCatalogDiagnostic>,
}

/// Result returned by [`super::compile_catalog_artifact_report`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogArtifactReport {
    /// Host-neutral runtime artifact produced by the same compile path as
    /// [`super::compile_catalog_artifact`].
    pub artifact: CompiledCatalogArtifact,
    /// Sibling report describing how each compiled message resolved.
    pub provenance: CompiledCatalogProvenanceReport,
}

/// Provenance metadata for one compiled requested-locale artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogProvenanceReport {
    /// Requested locale used for artifact compilation.
    pub requested_locale: String,
    /// Source locale used for explicit source fallback behavior.
    pub source_locale: String,
    /// Ordered fallback locales configured for this compile request.
    pub fallback_chain: Vec<String>,
    /// Per-message resolution rows in the same deterministic source-key order as compilation.
    pub messages: Vec<CompiledCatalogResolution>,
}

/// Provenance row for one compiled runtime message identity.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogResolution {
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Locale that ultimately provided the runtime value, if any.
    pub resolved_locale: Option<String>,
    /// Resolution category for this message.
    pub kind: CompiledCatalogResolutionKind,
}

/// How one compiled runtime message resolved for a requested-locale artifact.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum CompiledCatalogResolutionKind {
    /// The requested locale provided the final runtime message.
    Requested,
    /// A configured non-source fallback locale provided the final runtime message.
    Fallback,
    /// The source locale provided the final runtime message through source fallback.
    SourceFallback,
    /// No locale provided a final runtime message.
    Unresolved,
}

#[cfg(feature = "serde")]
#[derive(Serialize)]
struct CompiledCatalogArtifactWireRef<'a> {
    schema_version: u16,
    messages: &'a BTreeMap<String, String>,
    missing: &'a [CompiledCatalogMissingMessage],
    diagnostics: &'a [CompiledCatalogDiagnostic],
}

#[cfg(feature = "serde")]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CompiledCatalogArtifactWire {
    schema_version: u16,
    #[serde(default)]
    messages: BTreeMap<String, String>,
    #[serde(default)]
    missing: Vec<CompiledCatalogMissingMessage>,
    #[serde(default)]
    diagnostics: Vec<CompiledCatalogDiagnostic>,
}

#[cfg(feature = "serde")]
impl Serialize for CompiledCatalogArtifact {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        CompiledCatalogArtifactWireRef {
            schema_version: COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION,
            messages: &self.messages,
            missing: &self.missing,
            diagnostics: &self.diagnostics,
        }
        .serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for CompiledCatalogArtifact {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = CompiledCatalogArtifactWire::deserialize(deserializer)?;
        if wire.schema_version != COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION {
            return Err(serde::de::Error::custom(format!(
                "unsupported compiled catalog artifact schema_version {}; expected {}",
                wire.schema_version, COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION
            )));
        }

        Ok(Self {
            messages: wire.messages,
            missing: wire.missing,
            diagnostics: wire.diagnostics,
        })
    }
}

/// Missing-message record emitted by [`super::compile_catalog_artifact`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogMissingMessage {
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Requested locale for this artifact compilation.
    pub requested_locale: String,
    /// Locale that ultimately provided the runtime value, if any.
    pub resolved_locale: Option<String>,
}

/// Diagnostic emitted by [`super::compile_catalog_artifact`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CompiledCatalogDiagnostic {
    /// Severity for the collected diagnostic.
    pub severity: super::DiagnosticSeverity,
    /// Stable machine-readable diagnostic code.
    pub code: String,
    /// Human-readable explanation of the problem.
    pub message: String,
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Source `msgid` associated with the diagnostic.
    pub msgid: String,
    /// Source `msgctxt` associated with the diagnostic.
    pub msgctxt: Option<String>,
    /// Locale whose final runtime message produced the diagnostic.
    pub locale: String,
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::{
        COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION, CompileCatalogArtifactOptions,
        CompileCatalogArtifactReportOptions, CompileCatalogArtifactReportSelection,
        CompileCatalogOptions, CompileSelectedCatalogArtifactOptions, CompiledCatalogArtifact,
        CompiledCatalogDiagnostic, CompiledCatalogMissingMessage, CompiledKeyStrategy,
    };
    use crate::api::{CatalogMessageKey, CatalogSemantics, DiagnosticSeverity};

    #[test]
    fn compile_option_constructors_set_required_fields_and_keep_defaults() {
        let compile = CompileCatalogOptions::new();
        assert_eq!(compile.key_strategy, CompiledKeyStrategy::FerrocatV1);
        assert!(!compile.source_fallback);

        let artifact = CompileCatalogArtifactOptions::new("de", "en");
        assert_eq!(artifact.requested_locale, "de");
        assert_eq!(artifact.source_locale, "en");
        assert_eq!(artifact.key_strategy, CompiledKeyStrategy::FerrocatV1);
        assert_eq!(artifact.semantics, CatalogSemantics::IcuNative);

        let selected_ids = vec!["abc123".to_owned()];
        let selected = CompileSelectedCatalogArtifactOptions::new("de", "en", &selected_ids);
        assert_eq!(selected.options.requested_locale, "de");
        assert_eq!(selected.options.source_locale, "en");
        assert_eq!(selected.compiled_ids, selected_ids.as_slice());
        assert_eq!(
            selected.options.key_strategy,
            CompiledKeyStrategy::FerrocatV1
        );

        let report = CompileCatalogArtifactReportOptions::new("de", "en");
        assert_eq!(report.options.requested_locale, "de");
        assert_eq!(report.options.source_locale, "en");
        assert!(matches!(
            report.selection,
            CompileCatalogArtifactReportSelection::All
        ));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn compiled_catalog_artifact_serde_uses_versioned_wire_contract() {
        let artifact = CompiledCatalogArtifact {
            messages: BTreeMap::from([("runtime-key".to_owned(), "Hallo".to_owned())]),
            missing: vec![CompiledCatalogMissingMessage {
                key: "runtime-key".to_owned(),
                source_key: CatalogMessageKey::new("Hello", None),
                requested_locale: "de".to_owned(),
                resolved_locale: Some("en".to_owned()),
            }],
            diagnostics: vec![CompiledCatalogDiagnostic {
                severity: DiagnosticSeverity::Warning,
                code: "icu.syntax".to_owned(),
                message: "invalid ICU message".to_owned(),
                key: "runtime-key".to_owned(),
                msgid: "Hello".to_owned(),
                msgctxt: None,
                locale: "de".to_owned(),
            }],
        };

        let json = serde_json::to_value(&artifact).expect("artifact serialization must succeed");
        assert_eq!(
            json["schema_version"],
            COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION
        );
        assert_eq!(json["diagnostics"][0]["severity"], "warning");

        let roundtrip: CompiledCatalogArtifact =
            serde_json::from_value(json).expect("artifact deserialization must succeed");
        assert_eq!(roundtrip, artifact);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn compiled_catalog_artifact_serde_rejects_unknown_schema_version() {
        let json = serde_json::json!({
            "schema_version": COMPILED_CATALOG_ARTIFACT_SCHEMA_VERSION + 1,
            "messages": {},
            "missing": [],
            "diagnostics": [],
        });

        let error = serde_json::from_value::<CompiledCatalogArtifact>(json)
            .expect_err("unknown artifact schema versions must be rejected");
        assert!(
            error
                .to_string()
                .contains("unsupported compiled catalog artifact schema_version")
        );
    }
}