ferrocat-po 1.3.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
use std::collections::{BTreeMap, BTreeSet};

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

use super::catalog_index::{index_catalogs, select_target_locales};
use super::message_status::{active_message_keys, classify_expected_message};
use super::mt::validate_machine_translation_metadata;
use super::{
    ApiError, CatalogCoverageOptions, CatalogLocaleCoverage, CatalogMessage, CatalogMessageKey,
    CatalogMessageStatus, EffectiveTranslationRef, NormalizedParsedCatalog, catalog_coverage,
    machine_translation_hash, validate_source_locale,
};

/// Options controlling catalog review reports.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CatalogReviewOptions<'a> {
    /// Source locale whose active identities define the expected current set.
    pub source_locale: &'a str,
    /// Optional target locale filter. Empty means all current non-source locales.
    pub locales: &'a [&'a str],
    /// Whether detail vectors should be populated in addition to counters.
    pub include_details: bool,
}

impl<'a> CatalogReviewOptions<'a> {
    /// Creates review options with the required source locale set.
    #[must_use]
    pub fn new(source_locale: &'a str) -> Self {
        Self {
            source_locale,
            ..Self::default()
        }
    }

    /// Returns options that include source, translation, and metadata detail rows.
    #[must_use]
    pub const fn with_details(mut self, include_details: bool) -> Self {
        self.include_details = include_details;
        self
    }
}

/// Read-only catalog review report comparing two normalized catalog states.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogReviewReport {
    /// Aggregate counters across the compared catalog states.
    pub summary: CatalogReviewSummary,
    /// Source identity additions and removals.
    pub source_changes: CatalogSourceChangeReport,
    /// Per-locale target review sections.
    pub locales: Vec<CatalogLocaleReview>,
}

/// Aggregate counters for a catalog review report.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogReviewSummary {
    /// Active source identities added in the current state.
    pub source_added: usize,
    /// Active source identities removed from the current state.
    pub source_removed: usize,
    /// Target locales included in the report.
    pub target_locales: usize,
    /// Target translations that changed between previous and current states.
    pub translation_changed: usize,
    /// Current active target messages with valid current machine-translation metadata.
    pub machine_translation_current: usize,
    /// Current active target messages with stale machine-translation metadata.
    pub machine_translation_stale: usize,
    /// Current active target messages without machine-translation metadata.
    pub machine_translation_absent: usize,
    /// Current active target messages with invalid machine-translation metadata.
    pub machine_translation_invalid: usize,
}

/// Source identity add/remove summary.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogSourceChangeReport {
    /// Number of active source identities added in the current state.
    pub added: usize,
    /// Number of active source identities removed from the current state.
    pub removed: usize,
    /// Optional source change details.
    pub details: Vec<CatalogSourceChange>,
}

/// One source identity change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogSourceChange {
    /// Canonical gettext identity that changed.
    pub source_key: CatalogMessageKey,
    /// Add/remove classification.
    pub kind: CatalogSourceChangeKind,
}

/// Kind of source identity change.
#[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 CatalogSourceChangeKind {
    /// Identity exists in current source but not previous source.
    Added,
    /// Identity existed in previous source but not current source.
    Removed,
}

/// Review details for one target locale.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogLocaleReview {
    /// Locale represented by this review section.
    pub locale: String,
    /// Current coverage/status rollup for this locale.
    pub coverage: CatalogLocaleCoverage,
    /// Translation changes against the previous state.
    pub translations: CatalogTranslationChangeReport,
    /// Machine-translation metadata state in the current target catalog.
    pub machine_translation: CatalogMachineTranslationReview,
}

/// Translation change summary for one locale.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogTranslationChangeReport {
    /// Number of active translations whose effective value changed.
    pub changed: usize,
    /// Optional changed translation details.
    pub details: Vec<CatalogTranslationChange>,
}

/// One target translation change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogTranslationChange {
    /// Target locale whose translation changed.
    pub locale: String,
    /// Canonical gettext identity for the changed translation.
    pub source_key: CatalogMessageKey,
    /// Previous effective translation value.
    pub previous: CatalogReviewTranslation,
    /// Current effective translation value.
    pub current: CatalogReviewTranslation,
}

/// Owned translation value used in review reports.
#[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 CatalogReviewTranslation {
    /// Singular translation value.
    Singular(String),
    /// Plural translation values keyed by plural category.
    Plural(BTreeMap<String, String>),
}

/// Machine-translation metadata summary for one locale.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogMachineTranslationReview {
    /// Active target messages whose metadata hash matches the current translation.
    pub current: usize,
    /// Active target messages whose metadata hash no longer matches the translation.
    pub stale: usize,
    /// Active target messages without machine-translation metadata.
    pub absent: usize,
    /// Active target messages with invalid metadata, when detectable.
    pub invalid: usize,
    /// Optional per-message metadata detail rows.
    pub details: Vec<CatalogMachineTranslationMessage>,
}

/// One machine-translation metadata classification.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CatalogMachineTranslationMessage {
    /// Target locale associated with the metadata row.
    pub locale: String,
    /// Canonical gettext identity for the metadata row.
    pub source_key: CatalogMessageKey,
    /// Machine-translation metadata status.
    pub status: CatalogMachineTranslationStatus,
}

/// Machine-translation metadata freshness status.
#[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 CatalogMachineTranslationStatus {
    /// Metadata hash matches the current effective translation.
    Current,
    /// Metadata hash does not match the current effective translation.
    Stale,
    /// No machine-translation metadata is present.
    Absent,
    /// Metadata is invalid in a way the parsed catalog representation can expose.
    Invalid,
}

/// Compares previous and current normalized catalog states for translator review.
///
/// Source changes are deterministic identity additions/removals by
/// `msgctxt + msgid`; semantic rename detection is intentionally out of scope.
/// Target status rollups reuse [`CatalogMessageStatus`] and therefore match
/// [`super::audit_catalogs`] and [`super::catalog_coverage`] semantics.
/// Translation change details are limited to source identities whose current
/// target status is [`CatalogMessageStatus::Translated`]; missing, empty,
/// fuzzy, and obsolete current entries are surfaced by the coverage counters.
///
/// # Errors
///
/// Returns [`ApiError::InvalidArguments`] when either catalog state is missing
/// required locales, contains duplicate locales, or a requested target locale is
/// not available in the current catalog state.
pub fn catalog_review(
    previous_catalogs: &[&NormalizedParsedCatalog],
    current_catalogs: &[&NormalizedParsedCatalog],
    options: &CatalogReviewOptions<'_>,
) -> Result<CatalogReviewReport, ApiError> {
    validate_source_locale(options.source_locale)?;
    let previous_index = index_catalogs(previous_catalogs, "catalog_review previous")?;
    let current_index = index_catalogs(current_catalogs, "catalog_review current")?;
    let previous_source = previous_index
        .get(options.source_locale)
        .copied()
        .ok_or_else(|| missing_source_error("previous", options.source_locale))?;
    let current_source = current_index
        .get(options.source_locale)
        .copied()
        .ok_or_else(|| missing_source_error("current", options.source_locale))?;
    let previous_source_keys = active_message_keys(previous_source);
    let current_source_keys = active_message_keys(current_source);
    let target_locales = select_target_locales(
        &current_index,
        options.source_locale,
        options.locales,
        "catalog_review",
    )?;
    let source_changes = source_change_report(
        &previous_source_keys,
        &current_source_keys,
        options.include_details,
    );
    let coverage_options = CatalogCoverageOptions {
        source_locale: options.source_locale,
        locales: options.locales,
        include_details: options.include_details,
    };
    let coverage = catalog_coverage(current_catalogs, &coverage_options)?;
    let mut locales = Vec::with_capacity(target_locales.len());

    for locale in target_locales {
        let current_target = current_index
            .get(locale.as_str())
            .expect("selected target locale must exist");
        let previous_target = previous_index.get(locale.as_str()).copied();
        let locale_coverage = coverage
            .locales
            .iter()
            .find(|entry| entry.locale == locale)
            .expect("coverage locale must exist")
            .clone();
        let translations = translation_change_report(
            &locale,
            previous_target,
            current_target,
            &current_source_keys,
            options.include_details,
        );
        let machine_translation =
            machine_translation_review(&locale, current_target, options.include_details);
        locales.push(CatalogLocaleReview {
            locale,
            coverage: locale_coverage,
            translations,
            machine_translation,
        });
    }

    let summary = review_summary(&source_changes, &locales);
    Ok(CatalogReviewReport {
        summary,
        source_changes,
        locales,
    })
}

fn missing_source_error(state: &str, source_locale: &str) -> ApiError {
    ApiError::InvalidArguments(format!(
        "catalog_review {state} catalogs did not receive source locale {source_locale:?}"
    ))
}

fn source_change_report(
    previous_keys: &BTreeSet<CatalogMessageKey>,
    current_keys: &BTreeSet<CatalogMessageKey>,
    include_details: bool,
) -> CatalogSourceChangeReport {
    let added_keys = current_keys.difference(previous_keys);
    let removed_keys = previous_keys.difference(current_keys);
    let mut report = CatalogSourceChangeReport {
        added: added_keys.clone().count(),
        removed: removed_keys.clone().count(),
        details: Vec::new(),
    };

    if include_details {
        report
            .details
            .extend(added_keys.map(|source_key| CatalogSourceChange {
                source_key: source_key.clone(),
                kind: CatalogSourceChangeKind::Added,
            }));
        report
            .details
            .extend(removed_keys.map(|source_key| CatalogSourceChange {
                source_key: source_key.clone(),
                kind: CatalogSourceChangeKind::Removed,
            }));
    }

    report
}

fn translation_change_report(
    locale: &str,
    previous_target: Option<&NormalizedParsedCatalog>,
    current_target: &NormalizedParsedCatalog,
    current_source_keys: &BTreeSet<CatalogMessageKey>,
    include_details: bool,
) -> CatalogTranslationChangeReport {
    let Some(previous_target) = previous_target else {
        return CatalogTranslationChangeReport::default();
    };
    let mut report = CatalogTranslationChangeReport::default();

    for source_key in current_source_keys {
        if classify_expected_message(current_target, source_key) != CatalogMessageStatus::Translated
        {
            continue;
        }
        let Some(previous_message) = previous_target
            .get(source_key)
            .filter(|message| !message.obsolete)
        else {
            continue;
        };
        let current_message = current_target
            .get(source_key)
            .filter(|message| !message.obsolete)
            .expect("translated classification must have an active current message");
        let previous = previous_message.effective_translation();
        let current = current_message.effective_translation();
        if previous == current {
            continue;
        }
        report.changed += 1;
        if include_details {
            report.details.push(CatalogTranslationChange {
                locale: locale.to_owned(),
                source_key: source_key.clone(),
                previous: owned_translation(previous),
                current: owned_translation(current),
            });
        }
    }

    report
}

fn machine_translation_review(
    locale: &str,
    current_target: &NormalizedParsedCatalog,
    include_details: bool,
) -> CatalogMachineTranslationReview {
    let mut report = CatalogMachineTranslationReview::default();

    for (source_key, message) in current_target.iter() {
        if message.obsolete {
            continue;
        }
        let status = machine_translation_status(message);
        increment_machine_translation_status(&mut report, status);
        if include_details {
            report.details.push(CatalogMachineTranslationMessage {
                locale: locale.to_owned(),
                source_key: source_key.clone(),
                status,
            });
        }
    }

    report
}

fn machine_translation_status(message: &CatalogMessage) -> CatalogMachineTranslationStatus {
    let Some(metadata) = message.machine_translation.as_ref() else {
        return CatalogMachineTranslationStatus::Absent;
    };
    if validate_machine_translation_metadata(metadata).is_err() {
        return CatalogMachineTranslationStatus::Invalid;
    }
    if metadata.hash == machine_translation_hash(message.effective_translation()) {
        CatalogMachineTranslationStatus::Current
    } else {
        CatalogMachineTranslationStatus::Stale
    }
}

fn increment_machine_translation_status(
    report: &mut CatalogMachineTranslationReview,
    status: CatalogMachineTranslationStatus,
) {
    match status {
        CatalogMachineTranslationStatus::Current => report.current += 1,
        CatalogMachineTranslationStatus::Stale => report.stale += 1,
        CatalogMachineTranslationStatus::Absent => report.absent += 1,
        CatalogMachineTranslationStatus::Invalid => report.invalid += 1,
    }
}

fn review_summary(
    source_changes: &CatalogSourceChangeReport,
    locales: &[CatalogLocaleReview],
) -> CatalogReviewSummary {
    let mut summary = CatalogReviewSummary {
        source_added: source_changes.added,
        source_removed: source_changes.removed,
        target_locales: locales.len(),
        ..CatalogReviewSummary::default()
    };
    for locale in locales {
        summary.translation_changed += locale.translations.changed;
        summary.machine_translation_current += locale.machine_translation.current;
        summary.machine_translation_stale += locale.machine_translation.stale;
        summary.machine_translation_absent += locale.machine_translation.absent;
        summary.machine_translation_invalid += locale.machine_translation.invalid;
    }
    summary
}

fn owned_translation(value: EffectiveTranslationRef<'_>) -> CatalogReviewTranslation {
    match value {
        EffectiveTranslationRef::Singular(value) => {
            CatalogReviewTranslation::Singular(value.to_owned())
        }
        EffectiveTranslationRef::Plural(values) => CatalogReviewTranslation::Plural(values.clone()),
    }
}

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

    use super::{
        CatalogMachineTranslationStatus, CatalogReviewOptions, CatalogReviewTranslation,
        CatalogSourceChangeKind, catalog_review,
    };
    use crate::api::{
        ApiError, CatalogMessage, CatalogMessageKey, CatalogMode, CatalogSemantics,
        EffectiveTranslationRef, MachineTranslationMetadata, ParseCatalogOptions, ParsedCatalog,
        TranslationShape, machine_translation_hash, parse_catalog,
    };

    fn catalog(content: &str, locale: &str) -> crate::api::NormalizedParsedCatalog {
        catalog_with_mode(content, Some(locale), CatalogMode::IcuPo)
    }

    fn catalog_with_locale(
        content: &str,
        locale: Option<&str>,
    ) -> crate::api::NormalizedParsedCatalog {
        catalog_with_mode(content, locale, CatalogMode::IcuPo)
    }

    fn gettext_catalog(content: &str, locale: &str) -> crate::api::NormalizedParsedCatalog {
        catalog_with_mode(content, Some(locale), CatalogMode::GettextPo)
    }

    fn catalog_with_mode(
        content: &str,
        locale: Option<&str>,
        mode: CatalogMode,
    ) -> crate::api::NormalizedParsedCatalog {
        parse_catalog(ParseCatalogOptions {
            locale,
            mode,
            ..ParseCatalogOptions::new(content, "en")
        })
        .expect("parse catalog")
        .into_normalized_view()
        .expect("normalize catalog")
    }

    fn catalog_with_messages(
        locale: &str,
        messages: Vec<CatalogMessage>,
    ) -> crate::api::NormalizedParsedCatalog {
        ParsedCatalog {
            locale: Some(locale.to_owned()),
            semantics: CatalogSemantics::IcuNative,
            headers: BTreeMap::new(),
            messages,
            diagnostics: Vec::new(),
        }
        .into_normalized_view()
        .expect("normalize catalog")
    }

    fn error_debug(error: ApiError) -> String {
        format!("{error:?}")
    }

    #[test]
    fn catalog_review_reports_source_and_target_changes() {
        let previous_source = catalog(
            "msgid \"Hello\"\nmsgstr \"Hello\"\n\nmsgid \"Removed\"\nmsgstr \"Removed\"\n",
            "en",
        );
        let current_source = catalog(
            "msgid \"Hello\"\nmsgstr \"Hello\"\n\nmsgid \"Added\"\nmsgstr \"Added\"\n",
            "en",
        );
        let previous_target = catalog(
            "msgid \"Hello\"\nmsgstr \"Hallo\"\n\nmsgid \"Removed\"\nmsgstr \"Entfernt\"\n",
            "de",
        );
        let current_target = catalog(
            "msgid \"Hello\"\nmsgstr \"Hallo neu\"\n\nmsgid \"Added\"\nmsgstr \"\"\n\nmsgid \"Extra\"\nmsgstr \"Extra\"\n",
            "de",
        );

        let report = catalog_review(
            &[&previous_source, &previous_target],
            &[&current_source, &current_target],
            &CatalogReviewOptions::new("en").with_details(true),
        )
        .expect("review");
        let locale = &report.locales[0];

        assert_eq!(report.summary.source_added, 1);
        assert_eq!(report.summary.source_removed, 1);
        assert_eq!(report.summary.translation_changed, 1);
        assert!(report.source_changes.details.iter().any(|change| {
            change.source_key == CatalogMessageKey::new("Added", None)
                && change.kind == CatalogSourceChangeKind::Added
        }));
        assert_eq!(locale.coverage.empty, 1);
        assert_eq!(locale.coverage.extra, 1);
        assert_eq!(
            locale.translations.details[0].current,
            CatalogReviewTranslation::Singular("Hallo neu".to_owned())
        );
    }

    #[test]
    fn catalog_review_reports_machine_translation_freshness() {
        let hash = machine_translation_hash(EffectiveTranslationRef::Singular("Hallo"));
        let source = catalog(
            "msgid \"Hello\"\nmsgstr \"Hello\"\n\nmsgid \"Stale\"\nmsgstr \"Stale\"\n\nmsgid \"Absent\"\nmsgstr \"Absent\"\n",
            "en",
        );
        let target = catalog(
            &format!(
                concat!(
                    "#@ ferrocat-mt model=openai/gpt-5.5-high hash={}\n",
                    "msgid \"Hello\"\nmsgstr \"Hallo\"\n\n",
                    "#@ ferrocat-mt model=openai/gpt-5.5-high hash=old\n",
                    "msgid \"Stale\"\nmsgstr \"Alt\"\n\n",
                    "msgid \"Absent\"\nmsgstr \"Ohne\"\n",
                ),
                hash
            ),
            "de",
        );

        let report = catalog_review(
            &[&source, &target],
            &[&source, &target],
            &CatalogReviewOptions::new("en").with_details(true),
        )
        .expect("review");
        let machine_translation = &report.locales[0].machine_translation;

        assert_eq!(machine_translation.current, 1);
        assert_eq!(machine_translation.stale, 1);
        assert_eq!(machine_translation.absent, 1);
        assert!(machine_translation.details.iter().any(|detail| {
            detail.source_key == CatalogMessageKey::new("Stale", None)
                && detail.status == CatalogMachineTranslationStatus::Stale
        }));
    }

    #[test]
    fn catalog_review_reports_invalid_machine_translation_metadata() {
        let source = catalog("msgid \"Hello\"\nmsgstr \"Hello\"\n", "en");
        let target = catalog_with_messages(
            "de",
            vec![CatalogMessage {
                msgid: "Hello".to_owned(),
                msgctxt: None,
                translation: TranslationShape::Singular {
                    value: "Hallo".to_owned(),
                },
                comments: Vec::new(),
                origin: Vec::new(),
                obsolete: false,
                machine_translation: Some(MachineTranslationMetadata {
                    model: String::new(),
                    modified: None,
                    confidence: None,
                    hash: machine_translation_hash(EffectiveTranslationRef::Singular("Hallo")),
                }),
                extra: None,
            }],
        );

        let report = catalog_review(
            &[&source, &target],
            &[&source, &target],
            &CatalogReviewOptions::new("en").with_details(true),
        )
        .expect("review");
        let machine_translation = &report.locales[0].machine_translation;

        assert_eq!(machine_translation.invalid, 1);
        assert_eq!(report.summary.machine_translation_invalid, 1);
        assert!(machine_translation.details.iter().any(|detail| {
            detail.source_key == CatalogMessageKey::new("Hello", None)
                && detail.status == CatalogMachineTranslationStatus::Invalid
        }));
    }

    #[test]
    fn catalog_review_can_return_summary_only() {
        let source = catalog("msgid \"Hello\"\nmsgstr \"Hello\"\n", "en");
        let target = catalog("msgid \"Hello\"\nmsgstr \"Hallo\"\n", "de");

        let report = catalog_review(
            &[&source, &target],
            &[&source, &target],
            &CatalogReviewOptions::new("en"),
        )
        .expect("review");

        assert!(report.source_changes.details.is_empty());
        assert!(report.locales[0].translations.details.is_empty());
        assert!(report.locales[0].machine_translation.details.is_empty());
        assert!(report.locales[0].coverage.details.is_empty());
        assert_eq!(report.locales[0].coverage.translated, 1);
    }

    #[test]
    fn catalog_review_rejects_invalid_locale_inputs() {
        let source = catalog("msgid \"Hello\"\nmsgstr \"Hello\"\n", "en");
        let duplicate_source = catalog("msgid \"Bye\"\nmsgstr \"Bye\"\n", "en");
        let missing_locale = catalog_with_locale("msgid \"Hello\"\nmsgstr \"Hallo\"\n", None);
        let target = catalog("msgid \"Hello\"\nmsgstr \"Hallo\"\n", "de");
        let requested = ["fr"];

        let missing_previous_source = catalog_review(
            &[&target],
            &[&source, &target],
            &CatalogReviewOptions::new("en"),
        )
        .expect_err("missing previous source should fail");
        assert!(error_debug(missing_previous_source).contains("previous catalogs"));

        let missing_current_source = catalog_review(
            &[&source, &target],
            &[&target],
            &CatalogReviewOptions::new("en"),
        )
        .expect_err("missing current source should fail");
        assert!(error_debug(missing_current_source).contains("current catalogs"));

        let undeclared_locale = catalog_review(
            &[&missing_locale],
            &[&source, &target],
            &CatalogReviewOptions::new("en"),
        )
        .expect_err("missing declared locale should fail");
        assert!(error_debug(undeclared_locale).contains("declare a locale"));

        let duplicate_locale = catalog_review(
            &[&source, &duplicate_source],
            &[&source, &target],
            &CatalogReviewOptions::new("en"),
        )
        .expect_err("duplicate locale should fail");
        assert!(error_debug(duplicate_locale).contains("duplicate catalog locale"));

        let missing_requested = catalog_review(
            &[&source, &target],
            &[&source, &target],
            &CatalogReviewOptions {
                locales: &requested,
                ..CatalogReviewOptions::new("en")
            },
        )
        .expect_err("missing requested locale should fail");
        assert!(error_debug(missing_requested).contains("requested locale"));
    }

    #[test]
    fn catalog_review_filters_requested_locales_and_handles_new_target_locale() {
        let source = catalog("msgid \"Hello\"\nmsgstr \"Hello\"\n", "en");
        let de = catalog("msgid \"Hello\"\nmsgstr \"Hallo\"\n", "de");
        let fr = catalog("msgid \"Hello\"\nmsgstr \"Bonjour\"\n", "fr");
        let requested = ["en", "de", "de", "fr"];

        let report = catalog_review(
            &[&source],
            &[&source, &de, &fr],
            &CatalogReviewOptions {
                locales: &requested,
                ..CatalogReviewOptions::new("en")
            },
        )
        .expect("review");

        assert_eq!(report.summary.target_locales, 2);
        assert_eq!(report.locales[0].locale, "de");
        assert_eq!(report.locales[1].locale, "fr");
        assert_eq!(report.summary.translation_changed, 0);
        assert_eq!(report.locales[0].translations.changed, 0);
    }

    #[test]
    fn catalog_review_ignores_new_messages_when_tracking_translation_changes() {
        let previous_source = catalog("msgid \"Hello\"\nmsgstr \"Hello\"\n", "en");
        let current_source = catalog(
            "msgid \"Hello\"\nmsgstr \"Hello\"\n\nmsgid \"Added\"\nmsgstr \"Added\"\n",
            "en",
        );
        let previous_target = catalog("msgid \"Hello\"\nmsgstr \"Hallo\"\n", "de");
        let current_target = catalog(
            "msgid \"Hello\"\nmsgstr \"Hallo\"\n\nmsgid \"Added\"\nmsgstr \"Neu\"\n",
            "de",
        );

        let report = catalog_review(
            &[&previous_source, &previous_target],
            &[&current_source, &current_target],
            &CatalogReviewOptions::new("en").with_details(true),
        )
        .expect("review");

        assert_eq!(report.locales[0].translations.changed, 0);
        assert!(report.locales[0].translations.details.is_empty());
    }

    #[test]
    fn catalog_review_reports_plural_translation_changes() {
        let previous_source = gettext_catalog(
            concat!(
                "msgid \"book\"\n",
                "msgid_plural \"books\"\n",
                "msgstr[0] \"book\"\n",
                "msgstr[1] \"books\"\n",
            ),
            "en",
        );
        let current_source = gettext_catalog(
            concat!(
                "msgid \"book\"\n",
                "msgid_plural \"books\"\n",
                "msgstr[0] \"book\"\n",
                "msgstr[1] \"books\"\n",
            ),
            "en",
        );
        let previous_target = gettext_catalog(
            concat!(
                "msgid \"book\"\n",
                "msgid_plural \"books\"\n",
                "msgstr[0] \"Buch\"\n",
                "msgstr[1] \"Buecher\"\n",
            ),
            "de",
        );
        let current_target = gettext_catalog(
            concat!(
                "msgid \"book\"\n",
                "msgid_plural \"books\"\n",
                "msgstr[0] \"Buch\"\n",
                "msgstr[1] \"Buecher neu\"\n",
            ),
            "de",
        );

        let report = catalog_review(
            &[&previous_source, &previous_target],
            &[&current_source, &current_target],
            &CatalogReviewOptions::new("en").with_details(true),
        )
        .expect("review");
        let detail = &report.locales[0].translations.details[0];

        assert_eq!(report.locales[0].translations.changed, 1);
        assert!(matches!(
            detail.current,
            CatalogReviewTranslation::Plural(_)
        ));
    }

    #[test]
    fn catalog_review_skips_obsolete_machine_translation_entries() {
        let source = catalog("msgid \"Hello\"\nmsgstr \"Hello\"\n", "en");
        let target = catalog(
            "msgid \"Hello\"\nmsgstr \"Hallo\"\n\n#~ msgid \"Old\"\n#~ msgstr \"Alt\"\n",
            "de",
        );

        let report = catalog_review(
            &[&source, &target],
            &[&source, &target],
            &CatalogReviewOptions::new("en").with_details(true),
        )
        .expect("review");
        let machine_translation = &report.locales[0].machine_translation;

        assert_eq!(machine_translation.absent, 1);
        assert_eq!(machine_translation.details.len(), 1);
        assert_eq!(
            machine_translation.details[0].source_key,
            CatalogMessageKey::new("Hello", None)
        );
    }
}