formatjs_cli 0.1.11

Command-line interface for FormatJS - A Rust-based CLI for internationalization
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
use anyhow::{Context, Result};
use glob::glob;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Run a series of checks on translation files to validate correctness and consistency.
///
/// This command loads translation files and runs various validation checks comparing
/// target locales against a source locale to ensure translations are complete,
/// don't have extra keys, and maintain structural equivalence with the source.
///
/// # Arguments
///
/// * `translation_files` - Glob patterns for translation files (e.g., `foo/**/en.json`)
/// * `source_locale` - Source locale identifier (e.g., `en`). **Required** for checks to work.
/// * `ignore` - Glob patterns to exclude from verification
/// * `missing_keys` - Whether to check for missing keys in target locales compared to source
/// * `extra_keys` - Whether to check that target locales don't have extra keys not in source
/// * `structural_equality` - Whether to check for structural equality of messages between source and targets
///
/// # Checks
///
/// ## Missing Keys Check
/// Flattens nested objects in both source and target locales, then verifies that all keys
/// present in the source locale exist in each target locale. This guarantees no untranslated messages.
///
/// ## Extra Keys Check
/// Flattens nested objects and checks if target locales have keys that don't exist in the
/// source locale. Helps identify obsolete or mistakenly added translations.
///
/// ## Structural Equality Check
/// Parses both source and target messages as ICU MessageFormat and compares the AST structure.
/// This ensures that translations maintain the same structure (placeholders, plurals, selects)
/// as the source, guaranteeing they can be properly formatted at runtime.
///
/// # Exit Codes
///
/// * `0` - All checks passed
/// * `1` - At least one check failed
///
/// # Example
///
/// ```no_run
/// # use std::path::PathBuf;
/// # use formatjs_cli::verify::verify;
/// let files = vec![PathBuf::from("lang/*.json")];
/// verify(
///     &files,
///     Some("en"),
///     &[],
///     true,  // Check missing keys
///     true,  // Check extra keys
///     true,  // Check structural equality
/// ).unwrap();
/// ```
pub fn verify(
    translation_files: &[PathBuf],
    source_locale: Option<&str>,
    ignore: &[String],
    missing_keys: bool,
    extra_keys: bool,
    structural_equality: bool,
) -> Result<()> {
    // Ensure source locale is provided
    let source_locale = source_locale.context("--source-locale is required for verify command")?;

    // Expand glob patterns to actual file paths
    let mut expanded_files = Vec::new();
    for pattern in translation_files {
        let pattern_str = pattern
            .to_str()
            .context("Pattern path contains invalid UTF-8")?;

        // Try to expand as glob pattern
        match glob(pattern_str) {
            Ok(paths) => {
                for entry in paths {
                    match entry {
                        Ok(path) => expanded_files.push(path),
                        Err(e) => eprintln!("Warning: Failed to read glob entry: {}", e),
                    }
                }
            }
            Err(e) => {
                // If glob pattern is invalid, treat as literal path
                eprintln!("Warning: Invalid glob pattern '{}': {}", pattern_str, e);
                expanded_files.push(pattern.clone());
            }
        }
    }

    // Load all translation files
    let mut locales: HashMap<String, Value> = HashMap::new();

    for file in &expanded_files {
        // Skip ignored patterns
        if should_ignore(file, ignore) {
            continue;
        }

        // Extract locale from filename (e.g., "en.json" -> "en")
        let locale = extract_locale_from_path(file)?;

        // Read and parse JSON
        let content = std::fs::read_to_string(file)
            .with_context(|| format!("Failed to read file: {}", file.display()))?;

        let json: Value = serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse JSON in file: {}", file.display()))?;

        locales.insert(locale, json);
    }

    // Verify source locale exists
    if !locales.contains_key(source_locale) {
        anyhow::bail!(" Missing source {}.json file", source_locale);
    }

    eprintln!("Loaded {} locales", locales.len());
    eprintln!("Source locale: {}", source_locale);
    eprintln!();

    let mut exit_code = 0;

    // Run checks
    if missing_keys {
        if !check_missing_keys(&locales, source_locale) {
            exit_code = 1;
        }
    }

    if extra_keys {
        if !check_extra_keys(&locales, source_locale) {
            exit_code = 1;
        }
    }

    if structural_equality {
        if !check_structural_equality(&locales, source_locale) {
            exit_code = 1;
        }
    }

    if exit_code == 0 {
        eprintln!("✓ All checks passed!");
    } else {
        eprintln!("✗ Some checks failed");
        std::process::exit(exit_code);
    }

    Ok(())
}

/// Extract locale identifier from file path
/// e.g., "/path/to/en.json" -> "en"
fn extract_locale_from_path(path: &Path) -> Result<String> {
    let filename = path
        .file_stem()
        .context("Failed to get filename")?
        .to_str()
        .context("Filename is not valid UTF-8")?;

    Ok(filename.to_string())
}

/// Check if a file should be ignored based on ignore patterns
fn should_ignore(file: &Path, ignore_patterns: &[String]) -> bool {
    let file_str = file.to_string_lossy();
    ignore_patterns.iter().any(|pattern| {
        // Simple glob matching - just check if pattern is substring
        // TODO: Implement proper glob matching
        file_str.contains(pattern)
    })
}

/// Extract all keys from a JSON value recursively with dot notation
/// Returns nested keys like: ["a", "a.b", "a.b.c"]
fn extract_keys(value: &Value, parent_key: &str) -> Vec<String> {
    let mut keys = Vec::new();

    match value {
        Value::Object(map) => {
            for (key, val) in map {
                let full_key = if parent_key.is_empty() {
                    key.clone()
                } else {
                    format!("{}.{}", parent_key, key)
                };

                keys.push(full_key.clone());

                // Recursively extract nested keys
                if val.is_object() {
                    keys.extend(extract_keys(val, &full_key));
                }
            }
        }
        _ => {}
    }

    keys
}

/// Flatten a JSON value to leaf key-value pairs
/// Only includes string values at leaf nodes
fn flatten(value: &Value, parent_key: &str) -> HashMap<String, String> {
    let mut result = HashMap::new();

    match value {
        Value::Object(map) => {
            for (key, val) in map {
                let full_key = if parent_key.is_empty() {
                    key.clone()
                } else {
                    format!("{}.{}", parent_key, key)
                };

                match val {
                    Value::String(s) => {
                        result.insert(full_key, s.clone());
                    }
                    Value::Object(_) => {
                        result.extend(flatten(val, &full_key));
                    }
                    _ => {
                        // Ignore arrays and other types
                    }
                }
            }
        }
        _ => {}
    }

    result
}

/// Check for missing keys in target locales compared to source
fn check_missing_keys(locales: &HashMap<String, Value>, source_locale: &str) -> bool {
    let source = locales.get(source_locale).unwrap();
    let source_keys = extract_keys(source, "");
    let source_key_set: HashSet<_> = source_keys.iter().collect();

    let mut all_passed = true;

    for (locale, content) in locales {
        // Skip source locale
        if locale == source_locale {
            continue;
        }

        let target_keys = extract_keys(content, "");
        let target_key_set: HashSet<_> = target_keys.iter().collect();

        // Find keys in source that are missing in target
        let mut missing: Vec<_> = source_key_set.difference(&target_key_set).collect();

        // Sort missing keys: parent keys before nested keys (shorter keys first, then alphabetically)
        missing.sort_by(|a, b| {
            let a_len = a.len();
            let b_len = b.len();
            a_len.cmp(&b_len).then_with(|| a.cmp(b))
        });

        if !missing.is_empty() {
            all_passed = false;
            eprintln!("---------------------------------");
            eprintln!("Missing translation keys for locale {}:", locale);
            for key in missing {
                eprintln!("{}", key);
            }
            eprintln!();
        }
    }

    all_passed
}

/// Check for extra keys in target locales not present in source
fn check_extra_keys(locales: &HashMap<String, Value>, source_locale: &str) -> bool {
    let source = locales.get(source_locale).unwrap();
    let source_keys = extract_keys(source, "");
    let source_key_set: HashSet<_> = source_keys.iter().collect();

    let mut all_passed = true;

    for (locale, content) in locales {
        // Skip source locale
        if locale == source_locale {
            continue;
        }

        let target_keys = extract_keys(content, "");
        let target_key_set: HashSet<_> = target_keys.iter().collect();

        // Find keys in target that are not in source
        let extra: Vec<_> = target_key_set.difference(&source_key_set).collect();

        if !extra.is_empty() {
            all_passed = false;
            eprintln!("---------------------------------");
            eprintln!("Extra translation keys for locale {}:", locale);
            for key in extra {
                eprintln!("{}", key);
            }
            eprintln!();
        }
    }

    all_passed
}

/// Check for structural equality between source and target messages
fn check_structural_equality(locales: &HashMap<String, Value>, source_locale: &str) -> bool {
    let source = locales.get(source_locale).unwrap();
    let source_messages = flatten(source, "");

    let mut all_passed = true;

    for (locale, content) in locales {
        // Skip source locale
        if locale == source_locale {
            continue;
        }

        let target_messages = flatten(content, "");
        let mut errors = Vec::new();

        // Check each source message
        for (key, source_msg) in &source_messages {
            // Skip if key doesn't exist in target (that's covered by missing keys check)
            if let Some(target_msg) = target_messages.get(key) {
                // Parse both messages and compare structure with message ID as context
                match compare_message_structure(source_msg, target_msg, Some(key)) {
                    Ok((true, _)) => {
                        // Structures match, all good
                    }
                    Ok((false, Some(detail))) => {
                        errors.push((key.clone(), format_error_message(&detail)));
                    }
                    Ok((false, None)) => {
                        errors.push((
                            key.clone(),
                            "Messages are structurally different".to_string(),
                        ));
                    }
                    Err(e) => {
                        // Extract parse error code from error message
                        let error_msg = format!("{:#}", e); // Use alternate display to get root cause
                        // Check if the error message contains a parse error code
                        if error_msg.contains("EXPECT_ARGUMENT_CLOSING_BRACE") {
                            errors.push((key.clone(), "EXPECT_ARGUMENT_CLOSING_BRACE".to_string()));
                        } else if let Some(code) = extract_parse_error_code(&error_msg) {
                            errors.push((key.clone(), code));
                        } else {
                            errors.push((key.clone(), format_error_message(&error_msg)));
                        }
                    }
                }
            }
        }

        if !errors.is_empty() {
            all_passed = false;
            eprintln!("---------------------------------");
            eprintln!(
                "These translation keys for locale {} are structurally different from {}:",
                locale, source_locale
            );
            // Sort errors by key (numeric if possible, otherwise lexicographic)
            errors.sort_by(|a, b| {
                // Try to parse as numbers first
                match (a.0.parse::<i32>(), b.0.parse::<i32>()) {
                    (Ok(a_num), Ok(b_num)) => a_num.cmp(&b_num),
                    _ => a.0.cmp(&b.0),
                }
            });
            for (key, error) in errors {
                eprintln!("{}: {}", key, error);
            }
            eprintln!();
        }
    }

    all_passed
}

/// Extract parse error code from error message
/// Returns the error code if found (e.g., "EXPECT_ARGUMENT_CLOSING_BRACE")
fn extract_parse_error_code(msg: &str) -> Option<String> {
    // List of known parse error codes
    let error_codes = [
        "EXPECT_ARGUMENT_CLOSING_BRACE",
        "EMPTY_ARGUMENT",
        "MALFORMED_ARGUMENT",
        "EXPECT_ARGUMENT_TYPE",
        "INVALID_ARGUMENT_TYPE",
        "EXPECT_SELECT_ARGUMENT_OPTIONS",
        "EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",
        "INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",
        "EXPECT_SELECT_ARGUMENT_SELECTOR",
        "EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",
        "UNMATCHED_CLOSING_BRACE",
        "UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",
    ];

    for code in &error_codes {
        if msg.contains(code) {
            return Some(code.to_string());
        }
    }

    None
}

/// Format error message to match TypeScript CLI output
fn format_error_message(msg: &str) -> String {
    // Remove quotes around variable names
    let msg = msg.replace("'", "");

    // Normalize type names to lowercase (Number -> number, Date -> date, Time -> time)
    let msg = msg.replace("Number", "number");
    let msg = msg.replace("Date", "date");
    let msg = msg.replace("Time", "time");

    // Handle "Different number of variables" messages
    // The Rust ICU parser doesn't preserve variable order, so we need to extract and sort them
    if msg.contains("Different number of variables:") {
        if let Some((_prefix, lists)) = msg.split_once("Different number of variables:") {
            if let Some((list1, rest)) = lists.split_once("] vs [") {
                let list1_str = list1.trim_start_matches(&[' ', '['][..]);
                let list2_str = rest.trim_end_matches(&[']'][..]);

                // Parse variables
                let mut vars1: Vec<&str> = list1_str.split(", ").collect();
                let mut vars2: Vec<&str> = list2_str.split(", ").collect();

                // Sort alphabetically, but move single-letter variables to the end
                // This matches the TypeScript CLI behavior where tag variables appear last
                vars1.sort_by(|a, b| {
                    let a_single = a.len() == 1;
                    let b_single = b.len() == 1;
                    match (a_single, b_single) {
                        (true, false) => std::cmp::Ordering::Greater, // a is single, move to end
                        (false, true) => std::cmp::Ordering::Less,    // b is single, move to end
                        _ => a.cmp(b), // both single or both not, sort normally
                    }
                });
                vars2.sort();

                return format!(
                    "Different number of variables: [{}] vs [{}]",
                    vars1.join(", "),
                    vars2.join(", ")
                );
            }
        }
    }

    msg
}

/// Compare the structure of two ICU MessageFormat messages
/// Returns Ok((true, None)) if structures match, Ok((false, Some(detail))) if they don't, Err if parsing fails
fn compare_message_structure(source: &str, target: &str, message_id: Option<&str>) -> Result<(bool, Option<String>)> {
    use formatjs_icu_messageformat_parser::{Parser, ParserOptions, is_structurally_same};

    // Parse source message
    let parser_options = ParserOptions::default();
    let source_parser = Parser::new(source, parser_options.clone());
    let source_ast = source_parser
        .parse()
        .with_context(|| format!("Failed to parse source message: {}", source))?;

    // Parse target message
    let target_parser = Parser::new(target, parser_options);
    let target_ast = target_parser
        .parse()
        .with_context(|| format!("Failed to parse target message: {}", target))?;

    // Compare AST structures with message ID as context
    let context = message_id.unwrap_or("unknown");
    match is_structurally_same(&source_ast, &target_ast, context.to_string()) {
        Ok(()) => Ok((true, None)),
        Err(e) => Ok((false, Some(e.to_string()))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_extract_keys() {
        let value = json!({
            "a": "value",
            "b": {
                "c": "value2",
                "d": {
                    "e": "value3"
                }
            }
        });

        let keys = extract_keys(&value, "");
        assert!(keys.contains(&"a".to_string()));
        assert!(keys.contains(&"b".to_string()));
        assert!(keys.contains(&"b.c".to_string()));
        assert!(keys.contains(&"b.d".to_string()));
        assert!(keys.contains(&"b.d.e".to_string()));
    }

    #[test]
    fn test_extract_keys_empty_object() {
        let value = json!({});
        let keys = extract_keys(&value, "");
        assert_eq!(keys.len(), 0);
    }

    #[test]
    fn test_extract_keys_flat_object() {
        let value = json!({
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        });

        let keys = extract_keys(&value, "");
        assert_eq!(keys.len(), 3);
        assert!(keys.contains(&"key1".to_string()));
        assert!(keys.contains(&"key2".to_string()));
        assert!(keys.contains(&"key3".to_string()));
    }

    #[test]
    fn test_flatten() {
        let value = json!({
            "a": "value1",
            "b": {
                "c": "value2",
                "d": {
                    "e": "value3"
                }
            }
        });

        let flattened = flatten(&value, "");
        assert_eq!(flattened.get("a"), Some(&"value1".to_string()));
        assert_eq!(flattened.get("b.c"), Some(&"value2".to_string()));
        assert_eq!(flattened.get("b.d.e"), Some(&"value3".to_string()));
        assert_eq!(flattened.len(), 3);
    }

    #[test]
    fn test_flatten_ignores_non_string_values() {
        let value = json!({
            "string": "value",
            "number": 42,
            "array": [1, 2, 3],
            "null": null,
            "bool": true,
            "nested": {
                "valid": "nested_value",
                "invalid": 123
            }
        });

        let flattened = flatten(&value, "");
        assert_eq!(flattened.len(), 2);
        assert_eq!(flattened.get("string"), Some(&"value".to_string()));
        assert_eq!(
            flattened.get("nested.valid"),
            Some(&"nested_value".to_string())
        );
        assert!(!flattened.contains_key("number"));
        assert!(!flattened.contains_key("array"));
        assert!(!flattened.contains_key("nested.invalid"));
    }

    #[test]
    fn test_flatten_empty_object() {
        let value = json!({});
        let flattened = flatten(&value, "");
        assert_eq!(flattened.len(), 0);
    }

    #[test]
    fn test_extract_locale_from_path() {
        let path = Path::new("/path/to/en.json");
        assert_eq!(extract_locale_from_path(path).unwrap(), "en");

        let path = Path::new("fr-FR.json");
        assert_eq!(extract_locale_from_path(path).unwrap(), "fr-FR");
    }

    #[test]
    fn test_extract_locale_from_path_complex() {
        let path = Path::new("/deep/nested/path/to/locales/zh-Hans-CN.json");
        assert_eq!(extract_locale_from_path(path).unwrap(), "zh-Hans-CN");

        let path = Path::new("pt-BR.json");
        assert_eq!(extract_locale_from_path(path).unwrap(), "pt-BR");
    }

    #[test]
    fn test_should_ignore() {
        let file = Path::new("/path/to/file.json");
        let ignore_patterns = vec!["node_modules".to_string(), "test".to_string()];
        assert!(!should_ignore(file, &ignore_patterns));

        let file = Path::new("/path/node_modules/file.json");
        assert!(should_ignore(file, &ignore_patterns));

        let file = Path::new("/path/test/file.json");
        assert!(should_ignore(file, &ignore_patterns));

        let file = Path::new("/path/to/test_file.json");
        assert!(should_ignore(file, &ignore_patterns));
    }

    #[test]
    fn test_should_ignore_empty_patterns() {
        let file = Path::new("/path/to/file.json");
        let ignore_patterns: Vec<String> = vec![];
        assert!(!should_ignore(file, &ignore_patterns));
    }

    #[test]
    fn test_check_missing_keys() {
        let mut locales = HashMap::new();
        locales.insert(
            "en".to_string(),
            json!({
                "greeting": "Hello",
                "farewell": "Goodbye",
                "nested": {
                    "key": "value"
                }
            }),
        );
        locales.insert(
            "es".to_string(),
            json!({
                "greeting": "Hola",
                "farewell": "Adiós",
                "nested": {
                    "key": "valor"
                }
            }),
        );

        assert!(check_missing_keys(&locales, "en"));
    }

    #[test]
    fn test_check_missing_keys_with_missing() {
        let mut locales = HashMap::new();
        locales.insert(
            "en".to_string(),
            json!({
                "greeting": "Hello",
                "farewell": "Goodbye",
                "extra": "Extra key"
            }),
        );
        locales.insert(
            "es".to_string(),
            json!({
                "greeting": "Hola"
            }),
        );

        assert!(!check_missing_keys(&locales, "en"));
    }

    #[test]
    fn test_check_extra_keys() {
        let mut locales = HashMap::new();
        locales.insert(
            "en".to_string(),
            json!({
                "greeting": "Hello",
                "farewell": "Goodbye"
            }),
        );
        locales.insert(
            "es".to_string(),
            json!({
                "greeting": "Hola",
                "farewell": "Adiós"
            }),
        );

        assert!(check_extra_keys(&locales, "en"));
    }

    #[test]
    fn test_check_extra_keys_with_extra() {
        let mut locales = HashMap::new();
        locales.insert(
            "en".to_string(),
            json!({
                "greeting": "Hello"
            }),
        );
        locales.insert(
            "es".to_string(),
            json!({
                "greeting": "Hola",
                "extra_key": "Extra value",
                "another_extra": "Another"
            }),
        );

        assert!(!check_extra_keys(&locales, "en"));
    }

    #[test]
    fn test_compare_message_structure_identical() {
        let source = "Hello {name}!";
        let target = "Hola {name}!";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
        assert_eq!(result.1, None);
    }

    #[test]
    fn test_compare_message_structure_same_structure_different_text() {
        let source = "You have {count} items";
        let target = "Tienes {count} artículos";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_plural() {
        let source = "You have {count, plural, one {# item} other {# items}}";
        let target = "Tienes {count, plural, one {# artículo} other {# artículos}}";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_missing_variable() {
        let source = "Hello {name}!";
        let target = "Hello!";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, false);
        assert!(result.1.is_some());
        assert!(result.1.unwrap().contains("name"));
    }

    #[test]
    fn test_compare_message_structure_different_variable_name() {
        let source = "Hello {name}!";
        let target = "Hello {username}!";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, false);
        assert!(result.1.is_some());
    }

    #[test]
    fn test_compare_message_structure_type_mismatch() {
        let source = "{count, plural, one {# item} other {# items}}";
        let target = "{count} items";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, false);
        assert!(result.1.is_some());
        let error_msg = result.1.unwrap();
        assert!(error_msg.contains("count"));
        assert!(error_msg.contains("type"));
    }

    #[test]
    fn test_compare_message_structure_date_format() {
        let source = "Today is {date, date, short}";
        let target = "Hoy es {date, date, short}";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_date_type_mismatch() {
        let source = "Today is {date, date, short}";
        let target = "Today is {date}";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, false);
        assert!(result.1.is_some());
    }

    #[test]
    fn test_compare_message_structure_number_format() {
        let source = "Price: {price, number, ::currency/USD}";
        let target = "Precio: {price, number, ::currency/USD}";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_select() {
        let source = "{gender, select, male {He} female {She} other {They}}";
        let target = "{gender, select, male {Él} female {Ella} other {Ellos}}";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_multiple_variables() {
        let source = "Hello {firstName} {lastName}! You have {count} messages.";
        let target = "Hola {firstName} {lastName}! Tienes {count} mensajes.";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_multiple_variables_missing_one() {
        let source = "Hello {firstName} {lastName}! You have {count} messages.";
        let target = "Hola {firstName}! Tienes {count} mensajes.";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, false);
        assert!(result.1.is_some());
    }

    #[test]
    fn test_compare_message_structure_complex_nested() {
        // Use # instead of {count} inside plural branches
        let source = "{count, plural, one {You have # {itemType, select, photo {photo} video {video} other {item}}} other {You have # {itemType, select, photo {photos} video {videos} other {items}}}}";
        let target = "{count, plural, one {Tienes # {itemType, select, photo {foto} video {video} other {artículo}}} other {Tienes # {itemType, select, photo {fotos} video {videos} other {artículos}}}}";
        let result = compare_message_structure(source, target, None).unwrap();
        assert_eq!(result.0, true);
    }

    #[test]
    fn test_compare_message_structure_invalid_source() {
        let source = "Hello {name";
        let target = "Hola {name}";
        let result = compare_message_structure(source, target, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_compare_message_structure_invalid_target() {
        let source = "Hello {name}";
        let target = "Hola {name";
        let result = compare_message_structure(source, target, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_check_structural_equality() {
        let mut locales = HashMap::new();
        locales.insert(
            "en".to_string(),
            json!({
                "greeting": "Hello {name}!",
                "count": "You have {count, plural, one {# item} other {# items}}"
            }),
        );
        locales.insert(
            "es".to_string(),
            json!({
                "greeting": "Hola {name}!",
                "count": "Tienes {count, plural, one {# artículo} other {# artículos}}"
            }),
        );

        assert!(check_structural_equality(&locales, "en"));
    }

    #[test]
    fn test_check_structural_equality_with_errors() {
        let mut locales = HashMap::new();
        locales.insert(
            "en".to_string(),
            json!({
                "greeting": "Hello {name}!",
                "count": "You have {count, plural, one {# item} other {# items}}"
            }),
        );
        locales.insert(
            "fr".to_string(),
            json!({
                "greeting": "Bonjour {username}!",
                "count": "Vous avez {count} articles"
            }),
        );

        assert!(!check_structural_equality(&locales, "en"));
    }
}