ferrocat-po 3.0.0

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
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Internal catalog pipeline for the public `ferrocat-po` catalog API.
//!
//! This module owns the higher-level workflow around PO parsing, extracted-message
//! normalization, merge semantics, and export back to PO. The byte-oriented parser
//! and serializer hot paths stay elsewhere; this layer is where we preserve
//! catalog semantics and diagnostics.

use std::fs;
use std::{collections::BTreeMap, mem};

use rustc_hash::FxHashMap;

use crate::diagnostic_codes;

use super::export::export_catalog_content;
use super::file_io::atomic_write;
use super::helpers::{
    dedupe_origins, dedupe_placeholders, dedupe_strings, merge_placeholders, merge_unique_origins,
    merge_unique_strings,
};
use super::mt::{
    MachineMetadata, PO_AI_KEY, PO_LOCK_KEY, parse_ai_descriptor, validate_machine_metadata,
};
use super::plural::{PluralProfile, derive_plural_variable, expected_gettext_nplurals_for_locale};
use super::{
    ApiError, CatalogMessage, CatalogOrigin, CatalogSemantics, CatalogStats, CatalogStorageFormat,
    CatalogUpdateInput, CatalogUpdateResult, Diagnostic, DiagnosticSeverity, ExtractedMessage,
    ObsoleteInfo, ObsoleteStrategy, OrderBy, ParseCatalogOptions, ParsedCatalog, PluralEncoding,
    PluralSource, TranslationShape, UpdateCatalogFileOptions, UpdateCatalogOptions,
};
use crate::{MsgStr, PoFile, PoItem, PoVec, parse_po};

#[derive(Debug, Clone, PartialEq, Default)]
pub(super) struct Catalog {
    pub(super) locale: Option<String>,
    pub(super) headers: BTreeMap<String, String>,
    pub(super) file_comments: Vec<String>,
    pub(super) file_extracted_comments: Vec<String>,
    pub(super) messages: Vec<CanonicalMessage>,
    pub(super) diagnostics: Vec<Diagnostic>,
}

#[derive(Debug, Clone, PartialEq)]
pub(super) struct CanonicalMessage {
    pub(super) msgid: String,
    pub(super) msgctxt: Option<String>,
    pub(super) translation: CanonicalTranslation,
    pub(super) comments: Vec<String>,
    pub(super) origins: PoVec<CatalogOrigin>,
    pub(super) placeholders: BTreeMap<String, Vec<String>>,
    pub(super) obsolete: Option<ObsoleteInfo>,
    pub(super) machine: Option<MachineMetadata>,
}

/// PO metadata key carrying the obsolete-since date (see [`ObsoleteInfo`]).
pub(super) const PO_OBSOLETE_SINCE_KEY: &str = "obsolete-since";

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum CanonicalTranslation {
    Singular {
        value: String,
    },
    Plural {
        source: PluralSource,
        translation_by_category: BTreeMap<String, String>,
        variable: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct NormalizedMessage {
    msgid: String,
    msgctxt: Option<String>,
    kind: NormalizedKind,
    comments: Vec<String>,
    origins: PoVec<CatalogOrigin>,
    placeholders: BTreeMap<String, Vec<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum NormalizedKind {
    Singular,
    Plural {
        source: PluralSource,
        variable: Option<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ParsedPluralFormsHeader {
    raw: Option<String>,
    nplurals: Option<usize>,
    plural: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct MergeCatalogContext<'a> {
    locale: Option<&'a str>,
    source_locale: &'a str,
    semantics: CatalogSemantics,
    overwrite_source_translations: bool,
    obsolete_strategy: ObsoleteStrategy,
    now: Option<&'a str>,
}

/// Merges extracted messages into an existing catalog and returns updated catalog content.
///
/// # Errors
///
/// Returns [`ApiError`] when the source locale is missing, the existing catalog
/// cannot be parsed, or the requested storage format cannot be rendered safely.
///
/// # Examples
///
/// ```rust
/// use ferrocat_po::{
///     CatalogMode, CatalogUpdateInput, SourceExtractedMessage, UpdateCatalogOptions, update_catalog,
/// };
///
/// let result = update_catalog(
///     UpdateCatalogOptions::new(
///         "en",
///         CatalogUpdateInput::SourceFirst(vec![SourceExtractedMessage {
///             msgid: "Checkout".to_owned(),
///             ..SourceExtractedMessage::default()
///         }]),
///     )
///     .with_locale("de"),
/// )?;
///
/// assert!(result.created);
/// assert!(result.content.contains("msgid \"Checkout\""));
/// # Ok::<(), ferrocat_po::ApiError>(())
/// ```
pub fn update_catalog(
    mut options: UpdateCatalogOptions<'_>,
) -> Result<CatalogUpdateResult, ApiError> {
    super::validate_source_locale(options.source_locale)?;

    let input = mem::take(&mut options.input);
    let created = options.existing.is_none();
    let original = options.existing.unwrap_or("");
    let mut existing = match options.existing {
        Some(content) if !content.is_empty() => parse_catalog_to_internal(
            content,
            options.locale,
            options.source_locale,
            options.mode.semantics(),
            options.mode.plural_encoding(),
            false,
            options.mode.storage_format(),
        )?,
        Some(_) | None => Catalog {
            locale: options.locale.map(str::to_owned),
            headers: BTreeMap::new(),
            file_comments: Vec::new(),
            file_extracted_comments: Vec::new(),
            messages: Vec::new(),
            diagnostics: Vec::new(),
        },
    };

    let locale = options
        .locale
        .map(str::to_owned)
        .or_else(|| existing.locale.clone())
        .or_else(|| existing.headers.get("Language").cloned());
    let mut diagnostics = mem::take(&mut existing.diagnostics);
    let normalized = normalize_update_input(input)?;
    let merge_context = MergeCatalogContext {
        locale: locale.as_deref(),
        source_locale: options.source_locale,
        semantics: options.mode.semantics(),
        overwrite_source_translations: options.overwrite_source_translations,
        obsolete_strategy: options.obsolete_strategy.clone(),
        now: options.now,
    };
    let (mut merged, stats) =
        merge_catalogs(existing, normalized, &merge_context, &mut diagnostics);
    merged.locale.clone_from(&locale);
    apply_storage_defaults(&mut merged, &options, locale.as_deref(), &mut diagnostics)?;
    sort_messages(&mut merged.messages, options.render.order_by);
    let content = export_catalog_content(&merged, &options, locale.as_deref(), &mut diagnostics)?;

    Ok(CatalogUpdateResult {
        updated: content != original,
        content,
        created,
        stats,
        diagnostics,
    })
}

/// Updates a catalog on disk and only writes the file when the rendered
/// output changes.
///
/// # Errors
///
/// Returns [`ApiError`] when the input is invalid, when the existing file
/// cannot be read or parsed, or when the updated content cannot be written.
pub fn update_catalog_file(
    options: UpdateCatalogFileOptions<'_>,
) -> Result<CatalogUpdateResult, ApiError> {
    super::validate_source_locale(options.options.source_locale)?;
    if options.target_path.as_os_str().is_empty() {
        return Err(ApiError::InvalidArguments(
            "target_path must not be empty".to_owned(),
        ));
    }

    let existing = match fs::read_to_string(options.target_path) {
        Ok(content) => Some(content),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => return Err(ApiError::io_with_path(options.target_path, error)),
    };

    let mut update_options = options.options;
    update_options.existing = existing.as_deref();
    let result = update_catalog(update_options)?;

    if result.created || result.updated {
        atomic_write(options.target_path, &result.content)?;
    }

    Ok(result)
}

/// Parses catalog content into the higher-level representation used by
/// `ferrocat`'s catalog APIs.
///
/// # Errors
///
/// Returns [`ApiError`] when the catalog content cannot be parsed, the source
/// locale is missing, or strict ICU projection fails.
///
/// # Examples
///
/// ```rust
/// use ferrocat_po::{ParseCatalogOptions, parse_catalog};
///
/// let catalog = parse_catalog(
///     ParseCatalogOptions::new("msgid \"Checkout\"\nmsgstr \"Zur Kasse\"\n", "en")
///         .with_locale("de"),
/// )?;
///
/// assert_eq!(catalog.locale.as_deref(), Some("de"));
/// assert_eq!(catalog.messages.len(), 1);
/// # Ok::<(), ferrocat_po::ApiError>(())
/// ```
#[expect(
    clippy::needless_pass_by_value,
    reason = "Public API takes owned option structs so callers can build and move them ergonomically."
)]
pub fn parse_catalog(options: ParseCatalogOptions<'_>) -> Result<ParsedCatalog, ApiError> {
    super::validate_source_locale(options.source_locale)?;
    let catalog = parse_catalog_to_internal(
        options.content,
        options.locale,
        options.source_locale,
        options.mode.semantics(),
        options.mode.plural_encoding(),
        options.strict,
        options.mode.storage_format(),
    )?;
    let messages = catalog
        .messages
        .into_iter()
        .map(public_message_from_canonical)
        .collect();

    Ok(ParsedCatalog {
        locale: catalog.locale,
        semantics: options.mode.semantics(),
        headers: catalog.headers,
        messages,
        diagnostics: catalog.diagnostics,
    })
}

/// Collapses the accepted extractor input shapes into one merge-oriented form.
///
/// The result keeps only the fields that matter for catalog identity and merge
/// semantics, while also projecting source-first ICU plurals into the same
/// structured plural representation used by `CatalogUpdateInput::Structured`.
fn normalize_update_input(input: CatalogUpdateInput) -> Result<Vec<NormalizedMessage>, ApiError> {
    let mut messages = Vec::<NormalizedMessage>::new();

    match input {
        CatalogUpdateInput::Structured(extracted) => {
            for message in extracted {
                let (msgid, msgctxt, kind, comments, origins, placeholders) = match message {
                    ExtractedMessage::Singular(message) => (
                        message.msgid,
                        message.msgctxt,
                        NormalizedKind::Singular,
                        message.comments,
                        message.origin,
                        message.placeholders,
                    ),
                    ExtractedMessage::Plural(message) => (
                        message.msgid,
                        message.msgctxt,
                        NormalizedKind::Plural {
                            source: message.source,
                            variable: None,
                        },
                        message.comments,
                        message.origin,
                        message.placeholders,
                    ),
                };

                messages.push(NormalizedMessage {
                    msgid,
                    msgctxt,
                    kind,
                    comments: dedupe_strings(comments),
                    origins: dedupe_origins(origins),
                    placeholders: dedupe_placeholders(placeholders),
                });
            }
        }
        CatalogUpdateInput::SourceFirst(source_messages) => {
            for message in source_messages {
                messages.push(NormalizedMessage {
                    msgid: message.msgid,
                    msgctxt: message.msgctxt,
                    kind: NormalizedKind::Singular,
                    comments: dedupe_strings(message.comments),
                    origins: dedupe_origins(message.origin),
                    placeholders: dedupe_placeholders(message.placeholders),
                });
            }
        }
    }

    merge_normalized_messages(messages)
}

/// Merges duplicate extractor entries that refer to the same gettext identity.
///
/// Duplicate singular/plural shape mismatches remain a hard error because they
/// would otherwise make the final catalog shape ambiguous.
fn merge_normalized_messages(
    messages: Vec<NormalizedMessage>,
) -> Result<Vec<NormalizedMessage>, ApiError> {
    let mut index = FxHashMap::<(&str, Option<&str>), usize>::with_capacity_and_hasher(
        messages.len(),
        Default::default(),
    );
    let mut selected_indexes = Vec::with_capacity(messages.len());
    let mut duplicate_sources = vec![None; messages.len()];

    for (message_index, message) in messages.iter().enumerate() {
        if message.msgid.is_empty() {
            return Err(ApiError::InvalidArguments(
                "extracted msgid must not be empty".to_owned(),
            ));
        }

        let key = (message.msgid.as_str(), message.msgctxt.as_deref());
        if let Some(existing_index) = index.get(&key).copied() {
            let existing = &messages[existing_index];
            if existing.kind != message.kind {
                return Err(ApiError::Conflict(format!(
                    "conflicting duplicate extracted message for msgid {:?}",
                    message.msgid
                )));
            }
            duplicate_sources[message_index] = Some(existing_index);
        } else {
            index.insert(key, message_index);
            selected_indexes.push(message_index);
        }
    }

    let mut output_index_by_input = vec![None; messages.len()];
    let mut out = Vec::with_capacity(selected_indexes.len());
    let mut selected_indexes = selected_indexes.into_iter();
    let mut next_selected = selected_indexes.next();

    for (message_index, message) in messages.into_iter().enumerate() {
        if next_selected == Some(message_index) {
            output_index_by_input[message_index] = Some(out.len());
            out.push(message);
            next_selected = selected_indexes.next();
            continue;
        }

        if let Some(existing_input_index) = duplicate_sources[message_index] {
            let existing_output_index = output_index_by_input[existing_input_index]
                .expect("duplicate source should already be emitted");
            let existing = &mut out[existing_output_index];
            merge_unique_strings(&mut existing.comments, message.comments);
            merge_unique_origins(&mut existing.origins, message.origins);
            merge_placeholders(&mut existing.placeholders, message.placeholders);
        }
    }

    Ok(out)
}

/// Applies extracted messages onto an existing canonical catalog and records the
/// coarse-grained update counters used by the high-level API.
fn merge_catalogs(
    existing: Catalog,
    normalized: Vec<NormalizedMessage>,
    context: &MergeCatalogContext<'_>,
    diagnostics: &mut Vec<Diagnostic>,
) -> (Catalog, CatalogStats) {
    let is_source_locale = context
        .locale
        .is_none_or(|value| value == context.source_locale);
    let mut stats = CatalogStats::default();

    let mut matched = vec![false; existing.messages.len()];
    let mut messages = Vec::with_capacity(normalized.len() + existing.messages.len());

    // `locale` and `semantics` are constant for the whole merge, so build the
    // plural profile once instead of per plural message.
    let plural_profile = if context.semantics == CatalogSemantics::GettextCompat {
        PluralProfile::for_gettext_locale(context.locale)
    } else {
        PluralProfile::for_locale(context.locale)
    };

    {
        let mut existing_index = FxHashMap::<(&str, Option<&str>), usize>::with_capacity_and_hasher(
            existing.messages.len(),
            Default::default(),
        );
        for (index, message) in existing.messages.iter().enumerate() {
            existing_index.insert((message.msgid.as_str(), message.msgctxt.as_deref()), index);
        }

        for next in normalized {
            let previous = if let Some(&index) =
                existing_index.get(&(next.msgid.as_str(), next.msgctxt.as_deref()))
            {
                matched[index] = true;
                Some(&existing.messages[index])
            } else {
                None
            };
            let merged = merge_message(
                previous,
                next,
                is_source_locale,
                &plural_profile,
                context.overwrite_source_translations,
                diagnostics,
            );
            if previous.is_none() {
                stats.added += 1;
            } else if previous == Some(&merged) {
                stats.unchanged += 1;
            } else {
                stats.changed += 1;
            }
            messages.push(merged);
        }
    }

    for (index, message) in existing.messages.into_iter().enumerate() {
        if matched[index] {
            continue;
        }
        match &context.obsolete_strategy {
            ObsoleteStrategy::Delete => {
                stats.obsolete_removed += 1;
            }
            ObsoleteStrategy::Mark => {
                let mut message = message;
                mark_obsolete(&mut message, context.now, &mut stats);
                messages.push(message);
            }
            ObsoleteStrategy::Keep => {
                let mut message = message;
                message.obsolete = None;
                messages.push(message);
            }
            ObsoleteStrategy::DropObsoleteBefore(cutoff) => {
                let mut message = message;
                mark_obsolete(&mut message, context.now, &mut stats);
                // Age-based GC: drop dated entries older than the cutoff; keep
                // undated ones since their age is unknown.
                if let Some(ObsoleteInfo { since: Some(since) }) = &message.obsolete
                    && since.as_str() < cutoff.as_str()
                {
                    stats.obsolete_removed += 1;
                    continue;
                }
                messages.push(message);
            }
        }
    }

    stats.total = messages.len();
    (
        Catalog {
            locale: existing.locale,
            headers: existing.headers,
            file_comments: existing.file_comments,
            file_extracted_comments: existing.file_extracted_comments,
            messages,
            diagnostics: existing.diagnostics,
        },
        stats,
    )
}

/// Marks a newly-missing message obsolete, stamping the host-provided `now` as
/// the write-once `since` date. Already-obsolete messages keep their date.
fn mark_obsolete(message: &mut CanonicalMessage, now: Option<&str>, stats: &mut CatalogStats) {
    if message.obsolete.is_none() {
        message.obsolete = Some(ObsoleteInfo {
            since: now.map(str::to_owned),
        });
        stats.obsolete_marked += 1;
    }
}

/// Resolves the final canonical message for one gettext identity.
///
/// This is the central place where source-locale overwrite rules, plural
/// variable inference, and locale-aware plural category materialization meet.
fn merge_message(
    previous: Option<&CanonicalMessage>,
    next: NormalizedMessage,
    is_source_locale: bool,
    plural_profile: &PluralProfile,
    overwrite_source_translations: bool,
    diagnostics: &mut Vec<Diagnostic>,
) -> CanonicalMessage {
    let NormalizedMessage {
        msgid,
        msgctxt,
        kind,
        comments,
        origins,
        placeholders,
    } = next;

    let translation = match (kind, previous) {
        (NormalizedKind::Singular, Some(previous))
            if matches!(previous.translation, CanonicalTranslation::Singular { .. })
                && !(is_source_locale && overwrite_source_translations) =>
        {
            previous.translation.clone()
        }
        (NormalizedKind::Singular, _) => CanonicalTranslation::Singular {
            value: if is_source_locale {
                msgid.clone()
            } else {
                String::new()
            },
        },
        // Reuse an existing plural translation when the source plural is
        // unchanged and we're not overwriting source-locale text. Binding the
        // inner `Plural` here means a non-plural previous simply falls through
        // to the rebuild arm below.
        (
            NormalizedKind::Plural { source, variable },
            Some(CanonicalMessage {
                translation:
                    CanonicalTranslation::Plural {
                        translation_by_category,
                        variable: previous_variable,
                        ..
                    },
                ..
            }),
        ) if !(is_source_locale && overwrite_source_translations) => CanonicalTranslation::Plural {
            source,
            translation_by_category: plural_profile
                .materialize_translation(translation_by_category),
            variable: variable.unwrap_or_else(|| previous_variable.clone()),
        },
        (NormalizedKind::Plural { source, variable }, previous) => {
            let variable = variable
                .or_else(|| previous.and_then(extract_plural_variable))
                .or_else(|| derive_plural_variable(&placeholders))
                .unwrap_or_else(|| {
                    diagnostics.push(
                        Diagnostic::new(
                            DiagnosticSeverity::Warning,
                            diagnostic_codes::plural::ASSUMED_VARIABLE,
                            "Unable to determine plural placeholder name, assuming \"count\".",
                        )
                        .with_identity(&msgid, msgctxt.as_deref()),
                    );
                    "count".to_owned()
                });

            let translation_by_category = if is_source_locale {
                plural_profile.source_locale_translation(&source)
            } else {
                plural_profile.empty_translation()
            };

            CanonicalTranslation::Plural {
                source,
                translation_by_category,
                variable,
            }
        }
    };

    let (machine, obsolete) =
        previous.map_or_else(|| (None, None), |message| (message.machine.clone(), None));

    CanonicalMessage {
        msgid,
        msgctxt,
        translation,
        comments,
        origins,
        placeholders,
        obsolete,
        machine,
    }
}

fn extract_plural_variable(message: &CanonicalMessage) -> Option<String> {
    match &message.translation {
        CanonicalTranslation::Plural { variable, .. } => Some(variable.clone()),
        CanonicalTranslation::Singular { .. } => None,
    }
}

/// Fills in the standard catalog headers and only synthesizes `Plural-Forms`
/// when we have a conservative, locale-safe default.
pub(super) fn apply_header_defaults(
    headers: &mut BTreeMap<String, String>,
    locale: Option<&str>,
    semantics: CatalogSemantics,
    diagnostics: &mut Vec<Diagnostic>,
    custom: &BTreeMap<String, String>,
) {
    headers
        .entry("MIME-Version".to_owned())
        .or_insert_with(|| "1.0".to_owned());
    headers
        .entry("Content-Type".to_owned())
        .or_insert_with(|| "text/plain; charset=utf-8".to_owned());
    headers
        .entry("Content-Transfer-Encoding".to_owned())
        .or_insert_with(|| "8bit".to_owned());
    headers
        .entry("X-Generator".to_owned())
        .or_insert_with(|| "ferrocat".to_owned());
    if let Some(locale) = locale {
        headers.insert("Language".to_owned(), locale.to_owned());
    }
    if semantics == CatalogSemantics::GettextCompat && !custom.contains_key("Plural-Forms") {
        let profile = PluralProfile::for_gettext_locale(locale);
        let parsed_header = parse_plural_forms_from_headers(headers);
        match (parsed_header.raw.as_deref(), profile.gettext_header()) {
            (None, Some(header)) => {
                headers.insert("Plural-Forms".to_owned(), header);
            }
            (None, None) => diagnostics.push(Diagnostic::new(
                DiagnosticSeverity::Info,
                diagnostic_codes::plural::MISSING_PLURAL_FORMS_HEADER,
                "No safe default Plural-Forms header is known for this locale; keeping the header unset.",
            )),
            (Some(_), Some(header))
                if parsed_header.nplurals == Some(profile.nplurals())
                    && parsed_header.plural.is_none() =>
            {
                headers.insert("Plural-Forms".to_owned(), header);
                diagnostics.push(Diagnostic::new(
                    DiagnosticSeverity::Info,
                    diagnostic_codes::plural::COMPLETED_PLURAL_FORMS_HEADER,
                    "Plural-Forms header was missing the plural expression and has been completed using a safe locale default.",
                ));
            }
            _ => {}
        }
    }
    for (key, value) in custom {
        headers.insert(key.clone(), value.clone());
    }
}

pub(super) fn sort_messages(messages: &mut [CanonicalMessage], order_by: OrderBy) {
    match order_by {
        OrderBy::Msgid => messages.sort_by(|left, right| {
            left.msgid
                .cmp(&right.msgid)
                .then_with(|| left.msgctxt.cmp(&right.msgctxt))
                .then_with(|| left.obsolete.cmp(&right.obsolete))
        }),
        OrderBy::Origin => messages.sort_unstable_by(|left, right| {
            first_origin_sort_key(&left.origins)
                .cmp(first_origin_sort_key(&right.origins))
                .then_with(|| left.msgid.cmp(&right.msgid))
                .then_with(|| left.msgctxt.cmp(&right.msgctxt))
                .then_with(|| left.obsolete.cmp(&right.obsolete))
        }),
    }
}

fn first_origin_sort_key(origins: &[CatalogOrigin]) -> &str {
    origins.first().map_or("", |origin| origin.file.as_str())
}

fn apply_storage_defaults(
    catalog: &mut Catalog,
    options: &UpdateCatalogOptions<'_>,
    locale: Option<&str>,
    diagnostics: &mut Vec<Diagnostic>,
) -> Result<(), ApiError> {
    match options.mode.storage_format() {
        CatalogStorageFormat::Po => {
            let empty_custom_headers = BTreeMap::new();
            apply_header_defaults(
                &mut catalog.headers,
                locale,
                options.mode.semantics(),
                diagnostics,
                options
                    .render
                    .custom_header_attributes
                    .unwrap_or(&empty_custom_headers),
            );
            Ok(())
        }
        CatalogStorageFormat::Fcl => {
            if options
                .render
                .custom_header_attributes
                .is_some_and(|headers| !headers.is_empty())
            {
                return Err(ApiError::Unsupported(
                    "custom_header_attributes are not supported for FCL catalogs".to_owned(),
                ));
            }
            catalog.headers.clear();
            Ok(())
        }
    }
}

/// Parses catalog text into the canonical internal catalog representation used by
/// both `parse_catalog` and `update_catalog`.
///
/// Keeping this internal representation stable lets the public APIs share one
/// import path before they diverge into normalized lookup or update/export work.
pub(super) fn parse_catalog_to_internal(
    content: &str,
    locale_override: Option<&str>,
    source_locale: &str,
    semantics: CatalogSemantics,
    plural_encoding: PluralEncoding,
    strict: bool,
    storage_format: CatalogStorageFormat,
) -> Result<Catalog, ApiError> {
    match storage_format {
        CatalogStorageFormat::Po => parse_catalog_to_internal_po(
            content,
            locale_override,
            semantics,
            plural_encoding,
            strict,
        ),
        CatalogStorageFormat::Fcl => super::fcl::parse_catalog_to_internal_fcl(
            content,
            locale_override,
            source_locale,
            semantics,
            strict,
        ),
    }
}

fn parse_catalog_to_internal_po(
    content: &str,
    locale_override: Option<&str>,
    semantics: CatalogSemantics,
    _plural_encoding: PluralEncoding,
    strict: bool,
) -> Result<Catalog, ApiError> {
    let PoFile {
        headers: po_headers,
        items: po_items,
        comments: po_comments,
        extracted_comments: po_extracted_comments,
    } = parse_po(content)?;
    let headers = po_headers
        .into_iter()
        .map(|header| (header.key, header.value))
        .collect::<BTreeMap<_, _>>();
    let locale = locale_override
        .map(str::to_owned)
        .or_else(|| headers.get("Language").cloned());
    let plural_forms = parse_plural_forms_from_headers(&headers);
    let nplurals = plural_forms.nplurals;
    let mut diagnostics = Vec::new();
    validate_plural_forms_header(
        locale.as_deref(),
        &plural_forms,
        semantics,
        &mut diagnostics,
    );
    let mut messages = Vec::with_capacity(po_items.len());

    for item in po_items {
        let mut conversion_diagnostics = Vec::new();
        let message = import_message_from_po(
            item,
            locale.as_deref(),
            nplurals,
            semantics,
            strict,
            &mut conversion_diagnostics,
        )?;
        diagnostics.extend(conversion_diagnostics);
        messages.push(message);
    }

    Ok(Catalog {
        locale,
        headers,
        file_comments: po_comments,
        file_extracted_comments: po_extracted_comments,
        messages,
        diagnostics,
    })
}

/// Converts one parsed `PoItem` into the canonical internal message form.
///
/// The branching is intentionally centralized here so that gettext plural slot
/// import, ICU projection, and all associated diagnostics stay in one semantic
/// decision point.
fn import_message_from_po(
    item: PoItem,
    locale: Option<&str>,
    nplurals: Option<usize>,
    semantics: CatalogSemantics,
    _strict: bool,
    _diagnostics: &mut Vec<Diagnostic>,
) -> Result<CanonicalMessage, ApiError> {
    // Extracted (`#.`) and translator (`#`) comments collapse into one notes list.
    let (mut comments, placeholders) =
        split_placeholder_comments(item.extracted_comments.into_vec());
    comments.extend(item.comments.into_vec());
    let origins = item
        .references
        .into_iter()
        .map(parse_origin_owned)
        .collect();

    let translation = if let Some(msgid_plural) = &item.msgid_plural {
        if semantics == CatalogSemantics::IcuNative {
            return Err(ApiError::Unsupported(
                "classic gettext plural requires compat mode".to_owned(),
            ));
        }
        let plural_profile =
            PluralProfile::for_gettext_slots(locale, nplurals.or(Some(item.msgstr.len())));
        CanonicalTranslation::Plural {
            source: PluralSource {
                one: Some(item.msgid.clone()),
                other: msgid_plural.clone(),
            },
            translation_by_category: plural_profile
                .categories()
                .iter()
                .zip(item.msgstr.iter().chain(std::iter::repeat("")))
                .map(|(category, value)| (category.clone(), value.to_owned()))
                .collect(),
            variable: "count".to_owned(),
        }
    } else {
        if semantics == CatalogSemantics::IcuNative && matches!(item.msgstr, MsgStr::Plural(_)) {
            return Err(ApiError::Unsupported(
                "classic gettext plural requires compat mode".to_owned(),
            ));
        }
        CanonicalTranslation::Singular {
            value: take_first_msgstr(item.msgstr),
        }
    };

    Ok(CanonicalMessage {
        msgid: item.msgid,
        msgctxt: item.msgctxt,
        translation,
        comments,
        origins,
        placeholders,
        obsolete: import_obsolete(item.obsolete, &item.metadata),
        machine: import_machine_metadata(&item.metadata)?,
    })
}

/// Builds the obsolete state from the low-level obsolete flag, reading the
/// optional `#@ obsolete-since:` date from the entry's metadata.
fn import_obsolete(obsolete: bool, metadata: &[(String, String)]) -> Option<ObsoleteInfo> {
    if !obsolete {
        return None;
    }
    let since = metadata
        .iter()
        .find(|(key, _)| key == PO_OBSOLETE_SINCE_KEY)
        .map(|(_, value)| value.clone());
    Some(ObsoleteInfo { since })
}

fn import_machine_metadata(
    metadata: &[(String, String)],
) -> Result<Option<MachineMetadata>, ApiError> {
    let mut lock = None;
    let mut ai = None;
    for (key, value) in metadata {
        if key == PO_LOCK_KEY {
            if lock.replace(value).is_some() {
                return Err(ApiError::InvalidArguments(
                    "duplicate `lock` metadata for PO item".to_owned(),
                ));
            }
        } else if key == PO_AI_KEY && ai.replace(value).is_some() {
            return Err(ApiError::InvalidArguments(
                "duplicate `ai` metadata for PO item".to_owned(),
            ));
        }
    }

    let Some(lock) = lock else {
        if ai.is_some() {
            return Err(ApiError::InvalidArguments(
                "PO `ai` metadata requires a `lock`".to_owned(),
            ));
        }
        return Ok(None);
    };

    let metadata = MachineMetadata {
        lock: lock.clone(),
        ai: ai.map(|value| parse_ai_descriptor(value)),
    };
    validate_machine_metadata(&metadata)?;
    Ok(Some(metadata))
}

/// Splits extractor-style placeholder comments back out of the generic
/// extracted-comment list during PO import.
pub(super) fn split_placeholder_comments(
    extracted_comments: Vec<String>,
) -> (Vec<String>, BTreeMap<String, Vec<String>>) {
    let mut comments = Vec::new();
    let mut placeholders = BTreeMap::<String, Vec<String>>::new();

    for comment in extracted_comments {
        if let Some((name, value)) = parse_placeholder_comment(&comment) {
            placeholders.entry(name).or_default().push(value);
        } else {
            comments.push(comment);
        }
    }

    (comments, dedupe_placeholders(placeholders))
}

/// Parses the internal placeholder comment format emitted by the export helpers.
fn parse_placeholder_comment(comment: &str) -> Option<(String, String)> {
    let rest = comment.strip_prefix("placeholder {")?;
    let end = rest.find("}: ")?;
    Some((rest[..end].to_owned(), rest[end + 3..].to_owned()))
}

/// Parses a reference into a [`CatalogOrigin`]. A trailing `#scope` anchor (the
/// stable enclosing component or function) becomes [`CatalogOrigin::scope`], and
/// a legacy trailing `:line` (as emitted by gettext tools) is stripped so line
/// numbers never enter the catalog model and cannot round-trip into output.
pub(super) fn parse_origin_owned(mut reference: String) -> CatalogOrigin {
    // Anchor first: split on the last `#`, so a `#` earlier in the path stays
    // with the file.
    let scope = match reference.rsplit_once('#') {
        Some((file, scope)) if !scope.is_empty() => {
            let scope = scope.to_owned();
            let file_len = file.len();
            reference.truncate(file_len);
            Some(scope)
        }
        _ => None,
    };

    if let Some((file, line)) = reference.rsplit_once(':')
        && !line.is_empty()
        && line.bytes().all(|byte| byte.is_ascii_digit())
    {
        let file_len = file.len();
        reference.truncate(file_len);
    }

    CatalogOrigin {
        file: reference,
        scope,
    }
}

/// Serializes a [`CatalogOrigin`] to its wire form, shared by PO references and
/// FCL `r=` tags: `file` or `file#scope`.
pub(super) fn format_origin(origin: &CatalogOrigin) -> String {
    match &origin.scope {
        Some(scope) => format!("{}#{scope}", origin.file),
        None => origin.file.clone(),
    }
}

/// Moves the first available translation string out of a [`MsgStr`], matching
/// the `first().unwrap_or_default()` semantics without copying.
fn take_first_msgstr(msgstr: MsgStr) -> String {
    match msgstr {
        MsgStr::Singular(value) => value,
        MsgStr::Plural(values) => values.into_iter().next().unwrap_or_default(),
        MsgStr::None => String::new(),
    }
}

/// Extracts the small `Plural-Forms` subset that Ferrocat needs for diagnostics
/// and gettext-slot interpretation.
fn parse_plural_forms_from_headers(headers: &BTreeMap<String, String>) -> ParsedPluralFormsHeader {
    let Some(plural_forms) = headers.get("Plural-Forms") else {
        return ParsedPluralFormsHeader::default();
    };

    let mut parsed = ParsedPluralFormsHeader {
        raw: Some(plural_forms.clone()),
        ..ParsedPluralFormsHeader::default()
    };
    for part in plural_forms.split(';') {
        let trimmed = part.trim();
        if let Some(value) = trimmed.strip_prefix("nplurals=") {
            parsed.nplurals = value.trim().parse().ok();
        } else if let Some(value) = trimmed.strip_prefix("plural=") {
            let value = value.trim();
            if !value.is_empty() {
                parsed.plural = Some(value.to_owned());
            }
        }
    }

    parsed
}

/// Validates only the invariants that materially affect Ferrocat's plural
/// interpretation, keeping the diagnostics focused on actionable mismatches.
fn validate_plural_forms_header(
    locale: Option<&str>,
    plural_forms: &ParsedPluralFormsHeader,
    semantics: CatalogSemantics,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if semantics != CatalogSemantics::GettextCompat {
        return;
    }

    if let Some(nplurals) = plural_forms.nplurals {
        match expected_gettext_nplurals_for_locale(locale) {
            Some(expected) if nplurals != expected => diagnostics.push(Diagnostic::new(
                DiagnosticSeverity::Warning,
                diagnostic_codes::plural::NPLURALS_LOCALE_MISMATCH,
                format!(
                    "Plural-Forms declares nplurals={nplurals}, but locale-derived categories expect {expected}."
                ),
            )),
            _ => {}
        }
    } else if plural_forms.plural.is_some() {
        diagnostics.push(Diagnostic::new(
            DiagnosticSeverity::Warning,
            diagnostic_codes::parse::INVALID_PLURAL_FORMS_HEADER,
            "Plural-Forms header contains a plural expression but no parseable nplurals value.",
        ));
    }

    if plural_forms.nplurals.is_some() && plural_forms.plural.is_none() {
        diagnostics.push(Diagnostic::new(
            DiagnosticSeverity::Info,
            diagnostic_codes::plural::MISSING_PLURAL_EXPRESSION,
            "Plural-Forms header declares nplurals but omits the plural expression.",
        ));
    }
}

/// Rebuilds the public `CatalogMessage` shape from the canonical internal form.
pub(super) fn public_message_from_canonical(message: CanonicalMessage) -> CatalogMessage {
    let translation = match message.translation {
        CanonicalTranslation::Singular { value } => TranslationShape::Singular { value },
        CanonicalTranslation::Plural {
            source,
            translation_by_category,
            variable,
            ..
        } => TranslationShape::Plural {
            source,
            translation: translation_by_category,
            variable,
        },
    };

    CatalogMessage {
        msgid: message.msgid,
        msgctxt: message.msgctxt,
        translation,
        comments: message.comments,
        origin: message.origins,
        obsolete: message.obsolete,
        machine: message.machine,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CanonicalMessage, CanonicalTranslation, first_origin_sort_key, parse_origin_owned,
        sort_messages, take_first_msgstr,
    };
    use crate::api::{CatalogOrigin, OrderBy};
    use crate::{MsgStr, PoVec};

    #[test]
    fn parse_origin_owned_strips_line_numbers_and_keeps_file() {
        // A trailing numeric `:line` is dropped so line numbers never enter the
        // catalog model or round-trip back into rendered references.
        assert_eq!(
            parse_origin_owned("src/app.rs:42".to_owned()).file,
            "src/app.rs"
        );

        // No colon, and non-numeric or empty suffixes, keep the buffer verbatim.
        assert_eq!(parse_origin_owned("README".to_owned()).file, "README");
        assert_eq!(parse_origin_owned("a:b:rev".to_owned()).file, "a:b:rev");
    }

    #[test]
    fn take_first_msgstr_moves_first_available_value() {
        assert_eq!(take_first_msgstr(MsgStr::Singular("one".to_owned())), "one");
        assert_eq!(
            take_first_msgstr(MsgStr::Plural(vec!["a".to_owned(), "b".to_owned()])),
            "a"
        );
        assert_eq!(take_first_msgstr(MsgStr::Plural(Vec::new())), "");
        assert_eq!(take_first_msgstr(MsgStr::None), "");
    }

    #[test]
    fn first_origin_sort_key_borrows_origin_file() {
        let origins = PoVec::from(vec![CatalogOrigin {
            file: "src/app.rs".to_owned(),
            scope: None,
        }]);

        assert_eq!(first_origin_sort_key(&origins), "src/app.rs");
    }

    #[test]
    fn sort_messages_by_origin_uses_msgid_and_context_tiebreakers() {
        let mut messages = vec![
            test_message("src/app.rs", "beta", Some("dialog")),
            test_message("src/app.rs", "alpha", Some("dialog")),
            test_message("src/app.rs", "alpha", None),
            test_message("src/lib.rs", "alpha", None),
        ];

        sort_messages(&mut messages, OrderBy::Origin);

        assert_eq!(
            messages
                .iter()
                .map(|message| {
                    (
                        message.origins[0].file.as_str(),
                        message.msgid.as_str(),
                        message.msgctxt.as_deref(),
                    )
                })
                .collect::<Vec<_>>(),
            vec![
                ("src/app.rs", "alpha", None),
                ("src/app.rs", "alpha", Some("dialog")),
                ("src/app.rs", "beta", Some("dialog")),
                ("src/lib.rs", "alpha", None)
            ]
        );
    }

    fn test_message(file: &str, msgid: &str, msgctxt: Option<&str>) -> CanonicalMessage {
        CanonicalMessage {
            msgid: msgid.to_owned(),
            msgctxt: msgctxt.map(str::to_owned),
            translation: CanonicalTranslation::Singular {
                value: String::new(),
            },
            comments: Vec::new(),
            origins: PoVec::from(vec![CatalogOrigin {
                file: file.to_owned(),
                scope: None,
            }]),
            placeholders: Default::default(),
            obsolete: None,
            machine: None,
        }
    }
}