datasynth-generators 2.2.0

50+ data generators covering GL, P2P, O2C, S2C, HR, manufacturing, audit, tax, treasury, and ESG
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
//! Format variations for data quality simulation.
//!
//! Simulates realistic format inconsistencies including:
//! - Date formats (ISO, US, EU, various separators)
//! - Amount formats (decimal separators, thousand separators, currency symbols)
//! - Identifier formats (padding, prefixes, case variations)
//! - Text formats (case, whitespace, encoding)

use chrono::NaiveDate;
use datasynth_core::CountryPack;
use rand::Rng;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

/// Date format variations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DateFormat {
    /// ISO 8601: 2024-01-15
    ISO,
    /// US format: 01/15/2024
    US,
    /// US with dashes: 01-15-2024
    USDash,
    /// European: 15/01/2024
    EU,
    /// European with dashes: 15-01-2024
    EUDash,
    /// European with dots: 15.01.2024
    EUDot,
    /// Long format: January 15, 2024
    Long,
    /// Short year: 01/15/24
    ShortYear,
    /// Compact: 20240115
    Compact,
    /// Unix timestamp
    Unix,
    /// Excel serial number
    ExcelSerial,
}

impl DateFormat {
    /// Returns all date formats.
    pub fn all() -> Vec<Self> {
        vec![
            DateFormat::ISO,
            DateFormat::US,
            DateFormat::USDash,
            DateFormat::EU,
            DateFormat::EUDash,
            DateFormat::EUDot,
            DateFormat::Long,
            DateFormat::ShortYear,
            DateFormat::Compact,
        ]
    }

    /// Infer the baseline `DateFormat` from a country pack's short date format
    /// string (e.g. "MM/DD/YYYY", "DD.MM.YYYY", "DD/MM/YYYY").
    /// Falls back to `DateFormat::ISO` for unrecognised patterns.
    pub fn from_locale_short(short: &str) -> Self {
        let s = short.to_uppercase();
        if s.starts_with("YYYY") {
            // ISO family (year-first)
            DateFormat::ISO
        } else if s.starts_with("MM") {
            // Month-first (US family)
            if s.contains('-') {
                DateFormat::USDash
            } else {
                DateFormat::US
            }
        } else if s.starts_with("DD") {
            // Day-first (European family)
            if s.contains('.') {
                DateFormat::EUDot
            } else if s.contains('-') {
                DateFormat::EUDash
            } else {
                DateFormat::EU
            }
        } else {
            DateFormat::ISO
        }
    }

    /// Formats a date using this format.
    pub fn format(&self, date: NaiveDate) -> String {
        match self {
            DateFormat::ISO => date.format("%Y-%m-%d").to_string(),
            DateFormat::US => date.format("%m/%d/%Y").to_string(),
            DateFormat::USDash => date.format("%m-%d-%Y").to_string(),
            DateFormat::EU => date.format("%d/%m/%Y").to_string(),
            DateFormat::EUDash => date.format("%d-%m-%Y").to_string(),
            DateFormat::EUDot => date.format("%d.%m.%Y").to_string(),
            DateFormat::Long => date.format("%B %d, %Y").to_string(),
            DateFormat::ShortYear => date.format("%m/%d/%y").to_string(),
            DateFormat::Compact => date.format("%Y%m%d").to_string(),
            DateFormat::Unix => {
                let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).expect("valid unix epoch date");
                let days = (date - epoch).num_days();
                (days * 86400).to_string()
            }
            DateFormat::ExcelSerial => {
                // Excel epoch is December 30, 1899
                let epoch = NaiveDate::from_ymd_opt(1899, 12, 30).expect("valid excel epoch date");
                let days = (date - epoch).num_days();
                days.to_string()
            }
        }
    }
}

/// Amount format variations.
#[derive(Debug, Clone, PartialEq)]
pub enum AmountFormat {
    /// Plain number: 1234.56
    Plain,
    /// With thousand separator (comma): 1,234.56
    USComma,
    /// European (dot thousand, comma decimal): 1.234,56
    EUFormat,
    /// Space thousand separator: 1 234.56
    SpaceSeparator,
    /// With currency prefix: $1,234.56
    CurrencyPrefix(String),
    /// With currency suffix: 1,234.56 USD
    CurrencySuffix(String),
    /// Accounting format (parentheses for negative): (1,234.56)
    Accounting,
    /// Scientific notation: 1.23456E+03
    Scientific,
    /// No decimal places: 1235
    NoDecimals,
    /// Four decimal places: 1234.5600
    FourDecimals,
}

impl AmountFormat {
    /// Returns common amount formats.
    pub fn common() -> Vec<Self> {
        vec![
            AmountFormat::Plain,
            AmountFormat::USComma,
            AmountFormat::EUFormat,
            AmountFormat::SpaceSeparator,
            AmountFormat::CurrencyPrefix("$".to_string()),
            AmountFormat::CurrencySuffix("USD".to_string()),
            AmountFormat::Accounting,
            AmountFormat::NoDecimals,
        ]
    }

    /// Infer the baseline `AmountFormat` from a country pack's locale settings.
    ///
    /// Uses the `decimal_separator`, `thousands_separator`, `currency_symbol`,
    /// and `default_currency` to pick the most appropriate "correct" format.
    pub fn from_locale(
        decimal_sep: &str,
        thousands_sep: &str,
        currency_symbol: &str,
        _default_currency: &str,
    ) -> Self {
        match (decimal_sep, thousands_sep) {
            (",", ".") => AmountFormat::EUFormat,
            (".", " ") => AmountFormat::SpaceSeparator,
            (".", ",") => {
                if !currency_symbol.is_empty() {
                    AmountFormat::CurrencyPrefix(currency_symbol.to_string())
                } else {
                    AmountFormat::USComma
                }
            }
            _ => AmountFormat::Plain,
        }
    }

    /// Formats a decimal using this format.
    pub fn format(&self, amount: Decimal) -> String {
        let is_negative = amount < Decimal::ZERO;
        let abs_amount = amount.abs();
        let amount_f64: f64 = abs_amount.try_into().unwrap_or(0.0);

        match self {
            AmountFormat::Plain => {
                if is_negative {
                    format!("-{amount_f64:.2}")
                } else {
                    format!("{amount_f64:.2}")
                }
            }
            AmountFormat::USComma => {
                let formatted = format_with_thousands(amount_f64, ',', '.');
                if is_negative {
                    format!("-{formatted}")
                } else {
                    formatted
                }
            }
            AmountFormat::EUFormat => {
                let formatted = format_with_thousands(amount_f64, '.', ',');
                if is_negative {
                    format!("-{formatted}")
                } else {
                    formatted
                }
            }
            AmountFormat::SpaceSeparator => {
                let formatted = format_with_thousands(amount_f64, ' ', '.');
                if is_negative {
                    format!("-{formatted}")
                } else {
                    formatted
                }
            }
            AmountFormat::CurrencyPrefix(symbol) => {
                let formatted = format_with_thousands(amount_f64, ',', '.');
                if is_negative {
                    format!("-{symbol}{formatted}")
                } else {
                    format!("{symbol}{formatted}")
                }
            }
            AmountFormat::CurrencySuffix(code) => {
                let formatted = format_with_thousands(amount_f64, ',', '.');
                if is_negative {
                    format!("-{formatted} {code}")
                } else {
                    format!("{formatted} {code}")
                }
            }
            AmountFormat::Accounting => {
                let formatted = format_with_thousands(amount_f64, ',', '.');
                if is_negative {
                    format!("({formatted})")
                } else {
                    formatted
                }
            }
            AmountFormat::Scientific => {
                if is_negative {
                    format!("-{amount_f64:.5E}")
                } else {
                    format!("{amount_f64:.5E}")
                }
            }
            AmountFormat::NoDecimals => {
                let rounded = amount_f64.round() as i64;
                if is_negative {
                    format!("-{}", rounded.abs())
                } else {
                    rounded.to_string()
                }
            }
            AmountFormat::FourDecimals => {
                if is_negative {
                    format!("-{amount_f64:.4}")
                } else {
                    format!("{amount_f64:.4}")
                }
            }
        }
    }
}

/// Formats a number with thousand separators.
fn format_with_thousands(value: f64, thousand_sep: char, decimal_sep: char) -> String {
    let integer_part = value.trunc() as i64;
    let decimal_part = ((value.fract() * 100.0).round() as i64).abs();

    let integer_str = integer_part.abs().to_string();
    let mut result = String::new();

    for (i, c) in integer_str.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(thousand_sep);
        }
        result.push(c);
    }

    let integer_formatted: String = result.chars().rev().collect();
    format!("{integer_formatted}{decimal_sep}{decimal_part:02}")
}

/// Identifier format variations.
#[derive(Debug, Clone)]
pub enum IdentifierFormat {
    /// Original case.
    Original,
    /// Uppercase.
    Upper,
    /// Lowercase.
    Lower,
    /// With prefix.
    WithPrefix(String),
    /// With suffix.
    WithSuffix(String),
    /// Zero-padded to length.
    ZeroPadded(usize),
    /// Space-padded to length.
    SpacePadded(usize),
    /// With separator.
    WithSeparator { separator: char, interval: usize },
}

impl IdentifierFormat {
    /// Formats an identifier using this format.
    pub fn format(&self, id: &str) -> String {
        match self {
            IdentifierFormat::Original => id.to_string(),
            IdentifierFormat::Upper => id.to_uppercase(),
            IdentifierFormat::Lower => id.to_lowercase(),
            IdentifierFormat::WithPrefix(prefix) => format!("{prefix}{id}"),
            IdentifierFormat::WithSuffix(suffix) => format!("{id}{suffix}"),
            IdentifierFormat::ZeroPadded(len) => {
                if id.len() >= *len {
                    id.to_string()
                } else {
                    format!("{id:0>len$}")
                }
            }
            IdentifierFormat::SpacePadded(len) => {
                if id.len() >= *len {
                    id.to_string()
                } else {
                    format!("{id:>len$}")
                }
            }
            IdentifierFormat::WithSeparator {
                separator,
                interval,
            } => {
                let mut result = String::new();
                for (i, c) in id.chars().enumerate() {
                    if i > 0 && i % interval == 0 {
                        result.push(*separator);
                    }
                    result.push(c);
                }
                result
            }
        }
    }
}

/// Text format variations.
#[derive(Debug, Clone)]
pub enum TextFormat {
    /// Original text.
    Original,
    /// Uppercase.
    Upper,
    /// Lowercase.
    Lower,
    /// Title case.
    Title,
    /// With leading whitespace.
    LeadingWhitespace(usize),
    /// With trailing whitespace.
    TrailingWhitespace(usize),
    /// With extra internal spaces.
    ExtraSpaces,
    /// Trimmed.
    Trimmed,
    /// With non-breaking spaces.
    NonBreakingSpaces,
}

impl TextFormat {
    /// Formats text using this format.
    pub fn format(&self, text: &str) -> String {
        match self {
            TextFormat::Original => text.to_string(),
            TextFormat::Upper => text.to_uppercase(),
            TextFormat::Lower => text.to_lowercase(),
            TextFormat::Title => text
                .split_whitespace()
                .map(|word| {
                    let mut chars = word.chars();
                    match chars.next() {
                        None => String::new(),
                        Some(first) => {
                            first.to_uppercase().to_string()
                                + chars.as_str().to_lowercase().as_str()
                        }
                    }
                })
                .collect::<Vec<_>>()
                .join(" "),
            TextFormat::LeadingWhitespace(n) => {
                format!("{}{}", " ".repeat(*n), text)
            }
            TextFormat::TrailingWhitespace(n) => {
                format!("{}{}", text, " ".repeat(*n))
            }
            TextFormat::ExtraSpaces => text.split_whitespace().collect::<Vec<_>>().join("  "),
            TextFormat::Trimmed => text.trim().to_string(),
            TextFormat::NonBreakingSpaces => text.replace(' ', "\u{00A0}"),
        }
    }
}

/// Configuration for format variations.
#[derive(Debug, Clone)]
pub struct FormatVariationConfig {
    /// Probability of applying date format variation.
    pub date_variation_rate: f64,
    /// Probability of applying amount format variation.
    pub amount_variation_rate: f64,
    /// Probability of applying identifier format variation.
    pub identifier_variation_rate: f64,
    /// Probability of applying text format variation.
    pub text_variation_rate: f64,
    /// Allowed date formats.
    pub allowed_date_formats: Vec<DateFormat>,
    /// Allowed amount formats.
    pub allowed_amount_formats: Vec<AmountFormat>,
}

impl Default for FormatVariationConfig {
    fn default() -> Self {
        Self {
            date_variation_rate: 0.05,
            amount_variation_rate: 0.03,
            identifier_variation_rate: 0.02,
            text_variation_rate: 0.05,
            allowed_date_formats: DateFormat::all(),
            allowed_amount_formats: AmountFormat::common(),
        }
    }
}

/// Format variation injector.
pub struct FormatVariationInjector {
    config: FormatVariationConfig,
    stats: FormatVariationStats,
    /// Optional country pack for locale-aware baseline formats.
    country_pack: Option<CountryPack>,
}

/// Statistics for format variations.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FormatVariationStats {
    pub date_variations: usize,
    pub amount_variations: usize,
    pub identifier_variations: usize,
    pub text_variations: usize,
    pub total_processed: usize,
}

impl FormatVariationInjector {
    /// Creates a new format variation injector.
    pub fn new(config: FormatVariationConfig) -> Self {
        Self {
            config,
            stats: FormatVariationStats::default(),
            country_pack: None,
        }
    }

    /// Set the country pack for locale-aware format baselines.
    ///
    /// When a country pack is set, the "correct" (non-varied) format for dates
    /// and amounts is derived from the pack's locale settings instead of
    /// defaulting to ISO/Plain.
    pub fn set_country_pack(&mut self, pack: CountryPack) {
        self.country_pack = Some(pack);
    }

    /// Returns the baseline date format derived from the country pack (if set)
    /// or `DateFormat::ISO` as the default.
    fn baseline_date_format(&self) -> DateFormat {
        match &self.country_pack {
            Some(pack) => {
                let short = &pack.locale.date_format.short;
                if short.is_empty() {
                    DateFormat::ISO
                } else {
                    DateFormat::from_locale_short(short)
                }
            }
            None => DateFormat::ISO,
        }
    }

    /// Returns the baseline amount format derived from the country pack (if set)
    /// or `AmountFormat::Plain` as the default.
    fn baseline_amount_format(&self) -> AmountFormat {
        match &self.country_pack {
            Some(pack) => {
                let locale = &pack.locale;
                let dec_sep = &locale.number_format.decimal_separator;
                let thou_sep = &locale.number_format.thousands_separator;
                let symbol = &locale.currency_symbol;
                let currency = &locale.default_currency;
                if dec_sep.is_empty() && thou_sep.is_empty() {
                    AmountFormat::Plain
                } else {
                    AmountFormat::from_locale(dec_sep, thou_sep, symbol, currency)
                }
            }
            None => AmountFormat::Plain,
        }
    }

    /// Potentially applies a date format variation.
    ///
    /// When a country pack is set, the baseline (non-varied) format is derived
    /// from the pack's locale `date_format.short` field. Otherwise ISO 8601 is
    /// used as the default.
    pub fn vary_date<R: Rng>(&mut self, date: NaiveDate, rng: &mut R) -> String {
        self.stats.total_processed += 1;

        if rng.random::<f64>() < self.config.date_variation_rate {
            self.stats.date_variations += 1;
            let format = &self.config.allowed_date_formats
                [rng.random_range(0..self.config.allowed_date_formats.len())];
            format.format(date)
        } else {
            self.baseline_date_format().format(date)
        }
    }

    /// Potentially applies an amount format variation.
    ///
    /// When a country pack is set, the baseline (non-varied) format is derived
    /// from the pack's locale number/currency settings. Otherwise plain format
    /// is used as the default.
    pub fn vary_amount<R: Rng>(&mut self, amount: Decimal, rng: &mut R) -> String {
        self.stats.total_processed += 1;

        if rng.random::<f64>() < self.config.amount_variation_rate {
            self.stats.amount_variations += 1;
            let format = &self.config.allowed_amount_formats
                [rng.random_range(0..self.config.allowed_amount_formats.len())];
            format.format(amount)
        } else {
            self.baseline_amount_format().format(amount)
        }
    }

    /// Potentially applies an identifier format variation.
    pub fn vary_identifier<R: Rng>(&mut self, id: &str, rng: &mut R) -> String {
        self.stats.total_processed += 1;

        if rng.random::<f64>() < self.config.identifier_variation_rate {
            self.stats.identifier_variations += 1;

            let variations = [
                IdentifierFormat::Upper,
                IdentifierFormat::Lower,
                IdentifierFormat::ZeroPadded(10),
                IdentifierFormat::WithPrefix(" ".to_string()),
                IdentifierFormat::WithSuffix(" ".to_string()),
            ];

            let format = &variations[rng.random_range(0..variations.len())];
            format.format(id)
        } else {
            id.to_string()
        }
    }

    /// Potentially applies a text format variation.
    pub fn vary_text<R: Rng>(&mut self, text: &str, rng: &mut R) -> String {
        self.stats.total_processed += 1;

        if rng.random::<f64>() < self.config.text_variation_rate {
            self.stats.text_variations += 1;

            let variations = [
                TextFormat::Upper,
                TextFormat::Lower,
                TextFormat::Title,
                TextFormat::LeadingWhitespace(1),
                TextFormat::TrailingWhitespace(1),
                TextFormat::ExtraSpaces,
            ];

            let format = &variations[rng.random_range(0..variations.len())];
            format.format(text)
        } else {
            text.to_string()
        }
    }

    /// Returns statistics.
    pub fn stats(&self) -> &FormatVariationStats {
        &self.stats
    }

    /// Resets statistics.
    pub fn reset_stats(&mut self) {
        self.stats = FormatVariationStats::default();
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn test_date_formats() {
        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();

        assert_eq!(DateFormat::ISO.format(date), "2024-01-15");
        assert_eq!(DateFormat::US.format(date), "01/15/2024");
        assert_eq!(DateFormat::EU.format(date), "15/01/2024");
        assert_eq!(DateFormat::Compact.format(date), "20240115");
    }

    #[test]
    fn test_amount_formats() {
        let amount = dec!(1234567.89);

        assert_eq!(AmountFormat::Plain.format(amount), "1234567.89");
        assert_eq!(AmountFormat::USComma.format(amount), "1,234,567.89");
        assert_eq!(AmountFormat::EUFormat.format(amount), "1.234.567,89");
        assert_eq!(AmountFormat::NoDecimals.format(amount), "1234568");
    }

    #[test]
    fn test_negative_amounts() {
        let amount = dec!(-1234.56);

        assert_eq!(AmountFormat::Plain.format(amount), "-1234.56");
        assert_eq!(AmountFormat::Accounting.format(amount), "(1,234.56)");
    }

    #[test]
    fn test_identifier_formats() {
        let id = "abc123";

        assert_eq!(IdentifierFormat::Upper.format(id), "ABC123");
        assert_eq!(IdentifierFormat::ZeroPadded(10).format(id), "0000abc123");
    }

    #[test]
    fn test_text_formats() {
        let text = "hello world";

        assert_eq!(TextFormat::Upper.format(text), "HELLO WORLD");
        assert_eq!(TextFormat::Title.format(text), "Hello World");
        assert_eq!(TextFormat::ExtraSpaces.format(text), "hello  world");
    }

    #[test]
    fn test_format_injector() {
        use rand::SeedableRng;
        use rand_chacha::ChaCha8Rng;

        let config = FormatVariationConfig {
            date_variation_rate: 1.0, // Always vary for testing
            ..Default::default()
        };

        let mut injector = FormatVariationInjector::new(config);
        let mut rng = ChaCha8Rng::seed_from_u64(42);

        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
        let formatted = injector.vary_date(date, &mut rng);

        // Formatted date should not be empty and stats should be updated
        assert!(!formatted.is_empty());
        assert_eq!(injector.stats().date_variations, 1);
    }

    #[test]
    fn test_date_format_from_locale_short() {
        assert_eq!(DateFormat::from_locale_short("MM/DD/YYYY"), DateFormat::US);
        assert_eq!(
            DateFormat::from_locale_short("MM-DD-YYYY"),
            DateFormat::USDash
        );
        assert_eq!(DateFormat::from_locale_short("DD/MM/YYYY"), DateFormat::EU);
        assert_eq!(
            DateFormat::from_locale_short("DD-MM-YYYY"),
            DateFormat::EUDash
        );
        assert_eq!(
            DateFormat::from_locale_short("DD.MM.YYYY"),
            DateFormat::EUDot
        );
        assert_eq!(DateFormat::from_locale_short("YYYY-MM-DD"), DateFormat::ISO);
        assert_eq!(DateFormat::from_locale_short(""), DateFormat::ISO);
    }

    #[test]
    fn test_amount_format_from_locale() {
        // German: comma decimal, dot thousands
        assert_eq!(
            AmountFormat::from_locale(",", ".", "\u{20ac}", "EUR"),
            AmountFormat::EUFormat
        );
        // US: dot decimal, comma thousands, dollar symbol
        assert_eq!(
            AmountFormat::from_locale(".", ",", "$", "USD"),
            AmountFormat::CurrencyPrefix("$".to_string())
        );
        // Space-separated thousands
        assert_eq!(
            AmountFormat::from_locale(".", " ", "", "CHF"),
            AmountFormat::SpaceSeparator
        );
        // Plain fallback
        assert_eq!(
            AmountFormat::from_locale("X", "Y", "", "XYZ"),
            AmountFormat::Plain
        );
    }

    #[test]
    fn test_injector_with_country_pack_date_baseline() {
        use datasynth_core::country::schema::{DateFormatConfig, LocaleConfig};
        use rand::SeedableRng;
        use rand_chacha::ChaCha8Rng;

        // German pack: DD.MM.YYYY
        let pack = CountryPack {
            locale: LocaleConfig {
                date_format: DateFormatConfig {
                    short: "DD.MM.YYYY".to_string(),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };

        let config = FormatVariationConfig {
            date_variation_rate: 0.0, // Never vary -> always use baseline
            ..Default::default()
        };
        let mut injector = FormatVariationInjector::new(config);
        injector.set_country_pack(pack);

        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
        let formatted = injector.vary_date(date, &mut rng);

        // Baseline should be EU dot: 15.01.2024
        assert_eq!(formatted, "15.01.2024");
    }

    #[test]
    fn test_injector_with_country_pack_amount_baseline() {
        use datasynth_core::country::schema::{LocaleConfig, NumberFormatConfig};
        use rand::SeedableRng;
        use rand_chacha::ChaCha8Rng;

        // German pack: comma decimal, dot thousands
        let pack = CountryPack {
            locale: LocaleConfig {
                number_format: NumberFormatConfig {
                    decimal_separator: ",".to_string(),
                    thousands_separator: ".".to_string(),
                    ..Default::default()
                },
                currency_symbol: "\u{20ac}".to_string(),
                default_currency: "EUR".to_string(),
                ..Default::default()
            },
            ..Default::default()
        };

        let config = FormatVariationConfig {
            amount_variation_rate: 0.0, // Never vary -> always use baseline
            ..Default::default()
        };
        let mut injector = FormatVariationInjector::new(config);
        injector.set_country_pack(pack);

        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let amount = dec!(1234.56);
        let formatted = injector.vary_amount(amount, &mut rng);

        // Baseline should be EU format: 1.234,56
        assert_eq!(formatted, "1.234,56");
    }

    #[test]
    fn test_injector_without_country_pack_uses_defaults() {
        use rand::SeedableRng;
        use rand_chacha::ChaCha8Rng;

        let config = FormatVariationConfig {
            date_variation_rate: 0.0,
            amount_variation_rate: 0.0,
            ..Default::default()
        };
        let mut injector = FormatVariationInjector::new(config);
        // No country pack set

        let mut rng = ChaCha8Rng::seed_from_u64(42);
        let date = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
        let formatted_date = injector.vary_date(date, &mut rng);
        assert_eq!(formatted_date, "2024-01-15"); // ISO default

        let amount = dec!(1234.56);
        let formatted_amount = injector.vary_amount(amount, &mut rng);
        assert_eq!(formatted_amount, "1234.56"); // Plain default
    }
}