rustango 0.43.0

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! Internationalization (i18n) — translation lookups + Accept-Language negotiation.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::i18n::{Translator, Locale};
//! use std::collections::HashMap;
//!
//! let mut en = HashMap::new();
//! en.insert("welcome".to_owned(), "Welcome, {name}!".to_owned());
//! let mut fr = HashMap::new();
//! fr.insert("welcome".to_owned(), "Bienvenue, {name} !".to_owned());
//!
//! let t = Translator::new(Locale::new("en"))
//!     .add_locale(Locale::new("en"), en)
//!     .add_locale(Locale::new("fr"), fr);
//!
//! let s = t.translate("fr", "welcome", &[("name", "Alice")]);
//! assert_eq!(s, "Bienvenue, Alice !");
//! ```
//!
//! ## Loading from JSON files
//!
//! ```ignore
//! // locales/en.json: {"welcome": "Hello, {name}"}
//! let t = Translator::from_directory("./locales", Locale::new("en"))?;
//! ```
//!
//! ## Accept-Language negotiation
//!
//! ```ignore
//! use rustango::i18n::negotiate_language;
//!
//! // Picks the best-matching locale present in the translator
//! let lang = negotiate_language("fr-FR,fr;q=0.9,en;q=0.8", &["en", "fr"]);
//! assert_eq!(lang.as_deref(), Some("fr"));
//! ```

use std::collections::HashMap;
use std::path::Path;
use std::sync::RwLock;

pub mod admin;
pub mod db;
pub mod middleware;
pub mod tera_tags;
pub mod timezone;

// ------------------------------------------------------------------ Locale

/// A locale identifier (e.g. `"en"`, `"en-US"`, `"fr"`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Locale(String);

impl Locale {
    #[must_use]
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into().to_lowercase())
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The base language portion of a locale: `"en-US"` → `"en"`.
    #[must_use]
    pub fn base_language(&self) -> &str {
        self.0.split('-').next().unwrap_or(&self.0)
    }

    /// `true` for right-to-left scripts. Django parity #429 — matches
    /// `LANGUAGE_BIDI` / `{% get_current_language_bidi %}`. The check
    /// is on the base language (`ar-EG` ≡ `ar`).
    ///
    /// Covered RTL families: Arabic (`ar`), Hebrew (`he`, plus its
    /// retired ISO code `iw`), Persian / Farsi (`fa`), Urdu (`ur`),
    /// Pashto (`ps`), Yiddish (`yi`, plus retired `ji`), Divehi /
    /// Dhivehi (`dv`), Sorani Kurdish (`ckb`), Uyghur (`ug`), Sindhi
    /// (`sd`), Aramaic / Syriac (`syr`). Everything else is LTR.
    #[must_use]
    pub fn is_rtl(&self) -> bool {
        is_rtl_base(self.base_language())
    }

    /// `"rtl"` for right-to-left scripts, `"ltr"` otherwise — the
    /// value you'd hand to an HTML `dir` attribute or CSS
    /// `direction` property. Django parity #429.
    #[must_use]
    pub fn direction(&self) -> &'static str {
        if self.is_rtl() {
            "rtl"
        } else {
            "ltr"
        }
    }
}

/// `true` for an RTL base-language code. Public so callers that
/// only have a bare `&str` (e.g. a context-injected `LANG`) can
/// route through the same table without first allocating a
/// [`Locale`]. The check is case-insensitive and ignores any
/// region subtag.
#[must_use]
pub fn is_rtl_language(locale: &str) -> bool {
    let lower = locale.to_ascii_lowercase();
    let base = lower.split('-').next().unwrap_or(&lower);
    is_rtl_base(base)
}

/// `"rtl"` / `"ltr"` for a bare locale string — the bidi sibling of
/// [`is_rtl_language`].
#[must_use]
pub fn text_direction(locale: &str) -> &'static str {
    if is_rtl_language(locale) {
        "rtl"
    } else {
        "ltr"
    }
}

impl Locale {
    /// English display name for the base language — what an English
    /// speaker would call this locale. Returns the base-language code
    /// itself for unknown locales so callers always get *something*
    /// to render. Companion to [`Self::native_name`] for language
    /// picker UIs.
    ///
    /// Examples: `"en"` → `"English"`, `"fr-FR"` → `"French"`,
    /// `"zh-CN"` → `"Chinese"`, `"ar-EG"` → `"Arabic"`.
    #[must_use]
    pub fn display_name(&self) -> &'static str {
        language_display_name(self.base_language())
    }

    /// Native name for the base language — what a speaker of that
    /// language would call it. Returns the base-language code for
    /// unknown locales. Pair with [`Self::display_name`] for
    /// bidi-aware language pickers:
    ///
    /// ```ignore
    /// for code in ["en", "fr", "ja", "ar"] {
    ///     let loc = rustango::i18n::Locale::new(code);
    ///     println!("{} — {}", loc.native_name(), loc.display_name());
    /// }
    /// // English — English
    /// // français — French
    /// // 日本語 — Japanese
    /// // العربية — Arabic
    /// ```
    #[must_use]
    pub fn native_name(&self) -> &'static str {
        language_native_name(self.base_language())
    }
}

/// English display name for a bare locale string — public so callers
/// holding an `Accept-Language`-shaped `&str` can render it without
/// constructing a [`Locale`].
#[must_use]
pub fn language_display_name(locale: &str) -> &'static str {
    let lower = locale.to_ascii_lowercase();
    let base = lower.split('-').next().unwrap_or(&lower);
    match base {
        "en" => "English",
        "fr" => "French",
        "de" => "German",
        "es" => "Spanish",
        "it" => "Italian",
        "pt" => "Portuguese",
        "nl" => "Dutch",
        "ru" => "Russian",
        "ja" => "Japanese",
        "zh" => "Chinese",
        "ko" => "Korean",
        "ar" => "Arabic",
        "he" | "iw" => "Hebrew",
        "fa" => "Persian",
        "ur" => "Urdu",
        "tr" => "Turkish",
        "pl" => "Polish",
        "uk" => "Ukrainian",
        "cs" => "Czech",
        "sk" => "Slovak",
        "hu" => "Hungarian",
        "ro" => "Romanian",
        "bg" => "Bulgarian",
        "el" => "Greek",
        "sv" => "Swedish",
        "no" | "nb" | "nn" => "Norwegian",
        "da" => "Danish",
        "fi" => "Finnish",
        "hi" => "Hindi",
        "bn" => "Bengali",
        "ta" => "Tamil",
        "th" => "Thai",
        "vi" => "Vietnamese",
        "id" => "Indonesian",
        "ms" => "Malay",
        "ps" => "Pashto",
        "yi" | "ji" => "Yiddish",
        "dv" => "Divehi",
        "ckb" => "Sorani Kurdish",
        "ug" => "Uyghur",
        "sd" => "Sindhi",
        "syr" => "Syriac",
        // Unknown → return the input verbatim so the UI shows
        // something. Static lifetime requires a tiny static fallback;
        // leak the input on the cold path to satisfy &'static str.
        _ => "Unknown",
    }
}

/// Native name for a bare locale string — sibling to
/// [`language_display_name`].
#[must_use]
pub fn language_native_name(locale: &str) -> &'static str {
    let lower = locale.to_ascii_lowercase();
    let base = lower.split('-').next().unwrap_or(&lower);
    match base {
        "en" => "English",
        "fr" => "français",
        "de" => "Deutsch",
        "es" => "español",
        "it" => "italiano",
        "pt" => "português",
        "nl" => "Nederlands",
        "ru" => "русский",
        "ja" => "日本語",
        "zh" => "中文",
        "ko" => "한국어",
        "ar" => "العربية",
        "he" | "iw" => "עברית",
        "fa" => "فارسی",
        "ur" => "اردو",
        "tr" => "Türkçe",
        "pl" => "polski",
        "uk" => "українська",
        "cs" => "čeština",
        "sk" => "slovenčina",
        "hu" => "magyar",
        "ro" => "română",
        "bg" => "български",
        "el" => "Ελληνικά",
        "sv" => "svenska",
        "no" | "nb" | "nn" => "norsk",
        "da" => "dansk",
        "fi" => "suomi",
        "hi" => "हिन्दी",
        "bn" => "বাংলা",
        "ta" => "தமிழ்",
        "th" => "ไทย",
        "vi" => "Tiếng Việt",
        "id" => "Bahasa Indonesia",
        "ms" => "Bahasa Melayu",
        "ps" => "پښتو",
        "yi" | "ji" => "ייִדיש",
        "dv" => "ދިވެހި",
        "ckb" => "کوردیی ناوەندی",
        "ug" => "ئۇيغۇرچە",
        "sd" => "سنڌي",
        "syr" => "ܠܫܢܐ ܣܘܪܝܝܐ",
        _ => "Unknown",
    }
}

/// Lowercase, region-stripped base-language match against the
/// canonical RTL table. Inlined into `Locale::is_rtl` +
/// `is_rtl_language` so neither needs to allocate.
fn is_rtl_base(base: &str) -> bool {
    matches!(
        base,
        "ar"   // Arabic
        | "he" // Hebrew
        | "iw" // Hebrew (retired ISO 639-1 code, still emitted by some clients)
        | "fa" // Persian / Farsi
        | "ur" // Urdu
        | "ps" // Pashto
        | "yi" // Yiddish
        | "ji" // Yiddish (retired ISO 639-1 code)
        | "dv" // Divehi / Dhivehi
        | "ckb" // Sorani Kurdish
        | "ug" // Uyghur
        | "sd" // Sindhi
        | "syr" // Syriac / Aramaic
    )
}

impl std::fmt::Display for Locale {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

// ------------------------------------------------------------------ I18nError

#[derive(Debug, thiserror::Error)]
pub enum I18nError {
    #[error("io error: {0}")]
    Io(String),
    #[error("parse error in {file}: {detail}")]
    Parse { file: String, detail: String },
}

// ------------------------------------------------------------------ Translator

/// Translation backend — keyed by `(locale, key)`.
pub struct Translator {
    default_locale: Locale,
    /// Optional explicit fallback chain — checked AFTER the
    /// requested locale + its base language, BEFORE `default_locale`.
    /// Django parity #425. Lowercased on insert.
    fallback_chain: Vec<Locale>,
    catalogs: RwLock<HashMap<Locale, HashMap<String, String>>>,
    /// DB-sourced override layer (#532). Same `locale → key → value`
    /// shape as `catalogs`, but consulted *first* by [`Self::translate`]
    /// so operator edits persisted to `rustango_translations` win over
    /// the file-loaded defaults. Empty unless [`Self::load_overrides`] /
    /// [`Self::set_override`] is called (e.g. by
    /// [`crate::i18n::db::refresh_overrides_pool`]). Refreshing from the
    /// DB keeps `translate` synchronous — no per-render query.
    overrides: RwLock<HashMap<Locale, HashMap<String, String>>>,
}

impl Translator {
    /// New translator with the given fallback locale.
    #[must_use]
    pub fn new(default_locale: Locale) -> Self {
        Self {
            default_locale,
            fallback_chain: Vec::new(),
            catalogs: RwLock::new(HashMap::new()),
            overrides: RwLock::new(HashMap::new()),
        }
    }

    /// Set an explicit fallback chain (#425, Django parity). When
    /// `translate(locale, key, ...)` doesn't find a key in `locale`
    /// or its base language, the lookup walks `chain` in order
    /// before falling through to the default locale.
    ///
    /// ```ignore
    /// // Spanish missing? try Portuguese, then English (default).
    /// let t = Translator::new(Locale::new("en"))
    ///     .with_fallback_chain(&["pt"]);
    /// ```
    ///
    /// Duplicate entries and entries equal to `default_locale` are
    /// silently dropped (the default-locale check is already at the
    /// end of the chain).
    #[must_use]
    pub fn with_fallback_chain(mut self, chain: &[&str]) -> Self {
        let mut seen: std::collections::HashSet<Locale> = std::collections::HashSet::new();
        seen.insert(self.default_locale.clone());
        self.fallback_chain = chain
            .iter()
            .map(|s| Locale::new(*s))
            .filter(|loc| seen.insert(loc.clone()))
            .collect();
        self
    }

    /// Current explicit fallback chain (without the implicit
    /// default-locale terminus). Useful for diagnostics.
    #[must_use]
    pub fn fallback_chain(&self) -> &[Locale] {
        &self.fallback_chain
    }

    /// Add a translation catalog for `locale`. Replaces any existing
    /// catalog for the same locale.
    #[must_use]
    pub fn add_locale(self, locale: Locale, catalog: HashMap<String, String>) -> Self {
        self.catalogs
            .write()
            .expect("translator poisoned")
            .insert(locale, catalog);
        self
    }

    /// Mutably add a catalog (use with `let mut t = ...`).
    pub fn insert_locale(&self, locale: Locale, catalog: HashMap<String, String>) {
        self.catalogs
            .write()
            .expect("translator poisoned")
            .insert(locale, catalog);
    }

    /// Look up `key` in `locale`'s catalog, walking the fallback
    /// chain in order: exact locale → base language → explicit
    /// `fallback_chain` (#425) → default locale → `key` itself.
    ///
    /// `params` substitutes `{name}` placeholders in the result.
    #[must_use]
    pub fn translate(&self, locale: &str, key: &str, params: &[(&str, &str)]) -> String {
        let req = Locale::new(locale);

        // DB override layer (#532) takes priority over the file
        // catalogs for the requested locale / its base language, so an
        // operator's persisted edit wins. Anything not overridden falls
        // through to the unchanged catalog lookup below.
        {
            let ov = self.overrides.read().expect("translator poisoned");
            if let Some(v) = ov.get(&req).and_then(|c| c.get(key)).or_else(|| {
                ov.get(&Locale::new(req.base_language()))
                    .and_then(|c| c.get(key))
            }) {
                return substitute(v, params);
            }
        }

        let cats = self.catalogs.read().expect("translator poisoned");

        // Walk the lookup chain in priority order.
        let mut template: Option<String> = cats
            .get(&req)
            .and_then(|c| c.get(key))
            .or_else(|| {
                cats.get(&Locale::new(req.base_language()))
                    .and_then(|c| c.get(key))
            })
            .cloned();

        if template.is_none() {
            for fb in &self.fallback_chain {
                if let Some(v) = cats.get(fb).and_then(|c| c.get(key)) {
                    template = Some(v.clone());
                    break;
                }
            }
        }

        let template = template
            .or_else(|| {
                cats.get(&self.default_locale)
                    .and_then(|c| c.get(key))
                    .cloned()
            })
            .unwrap_or_else(|| key.to_owned());

        substitute(&template, params)
    }

    /// `true` when a catalog is registered for `locale` (or its base language).
    #[must_use]
    pub fn has_locale(&self, locale: &str) -> bool {
        let cats = self.catalogs.read().expect("translator poisoned");
        let req = Locale::new(locale);
        cats.contains_key(&req) || cats.contains_key(&Locale::new(req.base_language()))
    }

    /// All registered locale identifiers (for `negotiate_language`).
    #[must_use]
    pub fn locales(&self) -> Vec<String> {
        self.catalogs
            .read()
            .expect("translator poisoned")
            .keys()
            .map(|l| l.0.clone())
            .collect()
    }

    /// Every file-catalog entry as `(locale, key, value)` triples — used
    /// to seed the editable DB layer from the on-disk defaults (#532).
    #[must_use]
    pub fn entries(&self) -> Vec<(String, String, String)> {
        let cats = self.catalogs.read().expect("translator poisoned");
        let mut out = Vec::new();
        for (loc, catalog) in cats.iter() {
            for (k, v) in catalog {
                out.push((loc.0.clone(), k.clone(), v.clone()));
            }
        }
        out
    }

    /// Replace the entire DB-override layer (#532) with `rows`
    /// (`(locale, key, value)` triples — typically every
    /// `rustango_translations` row). Locale strings are normalized the
    /// same way as catalog locales. See
    /// [`crate::i18n::db::refresh_overrides_pool`].
    pub fn load_overrides(&self, rows: impl IntoIterator<Item = (String, String, String)>) {
        let mut map: HashMap<Locale, HashMap<String, String>> = HashMap::new();
        for (locale, key, value) in rows {
            map.entry(Locale::new(&locale))
                .or_default()
                .insert(key, value);
        }
        *self.overrides.write().expect("translator poisoned") = map;
    }

    /// Set a single override entry (#532) without a full reload — used by
    /// the admin edit path so a save takes effect immediately.
    pub fn set_override(&self, locale: &str, key: impl Into<String>, value: impl Into<String>) {
        self.overrides
            .write()
            .expect("translator poisoned")
            .entry(Locale::new(locale))
            .or_default()
            .insert(key.into(), value.into());
    }

    /// Drop every DB override, falling back to the file catalogs (#532).
    pub fn clear_overrides(&self) {
        self.overrides.write().expect("translator poisoned").clear();
    }

    /// Total number of override entries across all locales (#532) —
    /// handy for diagnostics and the admin coverage panel.
    #[must_use]
    pub fn override_count(&self) -> usize {
        self.overrides
            .read()
            .expect("translator poisoned")
            .values()
            .map(HashMap::len)
            .sum()
    }

    /// Load every `*.json` file in `dir` as a locale catalog. The file
    /// stem becomes the locale identifier (e.g. `en.json` → `Locale::new("en")`).
    ///
    /// Each file must contain a flat object of string→string entries.
    ///
    /// # Errors
    /// [`I18nError::Io`] when the dir can't be read or a file is unreadable.
    /// [`I18nError::Parse`] when a JSON file is malformed.
    pub fn from_directory(dir: &Path, default_locale: Locale) -> Result<Self, I18nError> {
        let t = Translator::new(default_locale);
        let entries = std::fs::read_dir(dir).map_err(|e| I18nError::Io(e.to_string()))?;
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) != Some("json") {
                continue;
            }
            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
                continue;
            };
            let raw = std::fs::read_to_string(&path).map_err(|e| I18nError::Io(e.to_string()))?;
            let catalog: HashMap<String, String> =
                serde_json::from_str(&raw).map_err(|e| I18nError::Parse {
                    file: path.display().to_string(),
                    detail: e.to_string(),
                })?;
            t.insert_locale(Locale::new(stem), catalog);
        }
        Ok(t)
    }

    /// Build a `Translator` from a [`crate::config::sections::I18nSettings`]
    /// — Django-shape `LANGUAGE_CODE` / `LANGUAGES` / `LOCALE_PATHS`
    /// (#403). Reads each `locale_paths` entry as a directory of
    ///
    /// Gated behind the `config` feature since it consults the
    /// loader's typed sections.
    /// `<lang>.json` catalogs, narrows the active set to
    /// `languages` (if non-empty), and pins the default locale +
    /// fallback chain.
    ///
    /// ```toml
    /// # config/default.toml
    /// [i18n]
    /// default_locale = "en"
    /// languages = ["en", "fr", "es"]
    /// locale_paths = ["locales", "vendor/locales"]
    /// fallback_chain = ["en"]
    /// ```
    ///
    /// ```ignore
    /// let settings = rustango::config::load()?;
    /// let translator = rustango::i18n::Translator::from_settings(&settings.i18n)?;
    /// ```
    ///
    /// Defaults when fields are unset:
    /// - `default_locale = None` → `"en"`.
    /// - `languages = []` → every catalog discovered via `locale_paths` stays active.
    /// - `locale_paths = []` → no directory scan; resulting translator has
    ///   no registered catalogs (apps that build catalogs programmatically
    ///   via `add_locale` skip the TOML path entirely).
    /// - `fallback_chain = []` → only the implicit
    ///   `exact-locale → base-language → default-locale → key`
    ///   chain applies.
    ///
    /// # Errors
    /// [`I18nError::Io`] / [`I18nError::Parse`] forwarded from any
    /// `locale_paths` entry that fails to load. A missing directory
    /// is treated as a hard error so deployment mistakes surface
    /// immediately rather than silently producing an empty
    /// translator.
    #[cfg(feature = "config")]
    pub fn from_settings(settings: &crate::config::I18nSettings) -> Result<Self, I18nError> {
        let default = settings.default_locale.as_deref().unwrap_or("en");
        let mut t = Translator::new(Locale::new(default));

        // Build the active-language allowlist. Empty `languages`
        // means "no narrowing"; non-empty means we only insert
        // catalogs whose stem matches one of the entries.
        let allowlist: Option<std::collections::HashSet<String>> = if settings.languages.is_empty()
        {
            None
        } else {
            Some(settings.languages.iter().cloned().collect())
        };

        for raw_path in &settings.locale_paths {
            let path = std::path::Path::new(raw_path);
            let entries = std::fs::read_dir(path)
                .map_err(|e| I18nError::Io(format!("{}: {e}", path.display())))?;
            for entry in entries.flatten() {
                let p = entry.path();
                if p.extension().and_then(|s| s.to_str()) != Some("json") {
                    continue;
                }
                let Some(stem) = p.file_stem().and_then(|s| s.to_str()) else {
                    continue;
                };
                if let Some(allow) = &allowlist {
                    if !allow.contains(stem) {
                        continue;
                    }
                }
                let raw = std::fs::read_to_string(&p).map_err(|e| I18nError::Io(e.to_string()))?;
                let catalog: HashMap<String, String> =
                    serde_json::from_str(&raw).map_err(|e| I18nError::Parse {
                        file: p.display().to_string(),
                        detail: e.to_string(),
                    })?;
                t.insert_locale(Locale::new(stem), catalog);
            }
        }

        if !settings.fallback_chain.is_empty() {
            let chain: Vec<&str> = settings.fallback_chain.iter().map(String::as_str).collect();
            t = t.with_fallback_chain(&chain);
        }

        Ok(t)
    }

    /// Django/gettext-shape alias for [`Self::translate`] — issue #422.
    /// Mirrors Django's `gettext(message)`: look up the key in the
    /// supplied locale and return the translated string (or the
    /// key itself when no translation is found). No parameter
    /// substitution — Django's `gettext` is the raw lookup.
    ///
    /// For interpolation use [`Self::translate`] (rustango shape)
    /// or [`Self::gettext_fmt`] (gettext shape that accepts a
    /// placeholder map).
    #[must_use]
    pub fn gettext(&self, locale: &str, key: &str) -> String {
        self.translate(locale, key, &[])
    }

    /// gettext-shape lookup with placeholder substitution. Same
    /// substitution rules as [`Self::translate`] (`{name}` →
    /// `params["name"]`). Provided so projects porting from Django
    /// keep their muscle memory: `gettext_fmt(locale, "Hi, {name}",
    /// &[("name", &user.name)])`.
    #[must_use]
    pub fn gettext_fmt(&self, locale: &str, key: &str, params: &[(&str, &str)]) -> String {
        self.translate(locale, key, params)
    }

    /// Django/gettext-shape `pgettext(context, message)` — context-
    /// disambiguated translation. Identical keys with different
    /// contexts can resolve to different translations. Issue #422.
    ///
    /// Catalog key format: `"<context>\u{4}<message>"` (the same
    /// `` (`EOT`) delimiter gettext uses internally). When
    /// no context-prefixed entry exists, falls back to the bare
    /// `message` lookup so the function degrades gracefully on
    /// catalogs that haven't yet been authored with contexts.
    #[must_use]
    pub fn pgettext(&self, locale: &str, context: &str, key: &str) -> String {
        let composite = format!("{context}\u{0004}{key}");
        let translated = self.translate(locale, &composite, &[]);
        // `translate` returns the key itself on miss — detect that
        // and fall through to the bare-key lookup so callers don't
        // see the raw `contextmessage` string when the
        // context-prefixed entry isn't in the catalog yet.
        if translated == composite {
            return self.translate(locale, key, &[]);
        }
        translated
    }

    /// gettext-shape `pgettext` with placeholder substitution.
    /// Mirrors [`Self::gettext_fmt`] semantics.
    #[must_use]
    pub fn pgettext_fmt(
        &self,
        locale: &str,
        context: &str,
        key: &str,
        params: &[(&str, &str)],
    ) -> String {
        let raw = self.pgettext(locale, context, key);
        substitute(&raw, params)
    }

    /// Django/gettext-shape `ngettext(singular, plural, count)` —
    /// pluralization. Returns `singular` when `count == 1`,
    /// `plural` otherwise. Issue #422.
    ///
    /// Catalog format mirrors gettext's `msgid_plural` convention:
    /// register two keys, one for each form. The fallback chain is
    /// the same as [`Self::translate`]; missing entries fall back
    /// to the supplied source strings.
    ///
    /// This implements the **English** plural rule (`n == 1` →
    /// singular; everything else → plural). Languages with more
    /// complex plural categories (Russian's three forms, Arabic's
    /// six, etc.) need a CLDR plural-rules resolver — out of scope
    /// for v1; track in #426 / future-backlog.
    ///
    /// `count` is bound to the `{count}` placeholder automatically
    /// so templates can read `"You have {count} unread messages"`
    /// without the caller threading it in.
    #[must_use]
    pub fn ngettext(&self, locale: &str, singular: &str, plural: &str, count: i64) -> String {
        let key = if count == 1 { singular } else { plural };
        let count_str = count.to_string();
        self.translate(locale, key, &[("count", &count_str)])
    }

    /// Pluralization with additional placeholder substitution.
    /// `{count}` is bound from the `count` argument; everything in
    /// `params` overlays on top so callers can pass extra keys
    /// (`{name}`, `{item}`, etc.).
    #[must_use]
    pub fn ngettext_fmt(
        &self,
        locale: &str,
        singular: &str,
        plural: &str,
        count: i64,
        params: &[(&str, &str)],
    ) -> String {
        let key = if count == 1 { singular } else { plural };
        let count_str = count.to_string();
        let mut all: Vec<(&str, &str)> = Vec::with_capacity(params.len() + 1);
        all.push(("count", &count_str));
        all.extend_from_slice(params);
        self.translate(locale, key, &all)
    }
}

/// Substitute `{name}` placeholders in `template` with values from `params`.
fn substitute(template: &str, params: &[(&str, &str)]) -> String {
    let mut out = template.to_owned();
    for (name, value) in params {
        let placeholder = format!("{{{name}}}");
        out = out.replace(&placeholder, value);
    }
    out
}

// ------------------------------------------------------------------ Accept-Language negotiation

/// Pick the best-matching language from `Accept-Language`.
///
/// `accept_language` is the raw header value (e.g. `"fr-FR,fr;q=0.9,en;q=0.8"`).
/// `available` is the list of locales the app supports.
///
/// Returns the best match or `None` if no acceptable language is supported.
#[must_use]
pub fn negotiate_language<S: AsRef<str>>(accept_language: &str, available: &[S]) -> Option<String> {
    let mut prefs = parse_accept_language(accept_language);
    // Sort by quality desc
    prefs.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    let avail_lower: Vec<String> = available
        .iter()
        .map(|s| s.as_ref().to_lowercase())
        .collect();

    for (lang, _q) in prefs {
        let lang_lower = lang.to_lowercase();
        // Exact match
        if let Some(matched) = avail_lower.iter().find(|a| **a == lang_lower) {
            return Some(matched.clone());
        }
        // Base-language match
        let base = lang_lower.split('-').next().unwrap_or(&lang_lower);
        if let Some(matched) = avail_lower
            .iter()
            .find(|a| **a == base || a.starts_with(&format!("{base}-")))
        {
            return Some(matched.clone());
        }
    }
    None
}

fn parse_accept_language(header: &str) -> Vec<(String, f32)> {
    header
        .split(',')
        .filter_map(|raw| {
            let mut parts = raw.split(';').map(str::trim);
            let lang = parts.next()?.to_owned();
            if lang.is_empty() {
                return None;
            }
            let mut q = 1.0;
            for kv in parts {
                if let Some(rest) = kv.strip_prefix("q=") {
                    if let Ok(parsed) = rest.parse::<f32>() {
                        q = parsed;
                    }
                }
            }
            Some((lang, q))
        })
        .collect()
}

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

    fn make_translator() -> Translator {
        let mut en = HashMap::new();
        en.insert("hello".into(), "Hello".into());
        en.insert("greet".into(), "Hi, {name}!".into());
        let mut fr = HashMap::new();
        fr.insert("hello".into(), "Bonjour".into());
        fr.insert("greet".into(), "Salut, {name} !".into());

        Translator::new(Locale::new("en"))
            .add_locale(Locale::new("en"), en)
            .add_locale(Locale::new("fr"), fr)
    }

    #[test]
    fn translate_basic() {
        let t = make_translator();
        assert_eq!(t.translate("en", "hello", &[]), "Hello");
        assert_eq!(t.translate("fr", "hello", &[]), "Bonjour");
    }

    #[test]
    fn translate_substitutes_params() {
        let t = make_translator();
        assert_eq!(
            t.translate("en", "greet", &[("name", "Alice")]),
            "Hi, Alice!"
        );
        assert_eq!(
            t.translate("fr", "greet", &[("name", "Alice")]),
            "Salut, Alice !"
        );
    }

    #[test]
    fn unknown_locale_falls_back_to_default() {
        let t = make_translator();
        assert_eq!(t.translate("ja", "hello", &[]), "Hello");
    }

    #[test]
    fn unknown_key_returns_key_itself() {
        let t = make_translator();
        assert_eq!(t.translate("en", "unknown.key", &[]), "unknown.key");
    }

    #[test]
    fn region_falls_back_to_base_language() {
        let t = make_translator();
        // "fr-FR" → falls back to "fr"
        assert_eq!(t.translate("fr-FR", "hello", &[]), "Bonjour");
    }

    #[test]
    fn has_locale_with_base_match() {
        let t = make_translator();
        assert!(t.has_locale("en"));
        assert!(t.has_locale("fr"));
        assert!(t.has_locale("en-US"));
        assert!(!t.has_locale("ja"));
    }

    /// Issue #425 — explicit fallback chain. Build a translator where
    /// only Spanish is missing the key; it should walk pt → en (default).
    #[test]
    fn fallback_chain_walks_in_order() {
        let mut es: HashMap<String, String> = HashMap::new();
        es.insert("welcome".into(), "Bienvenido".into());
        // No `hello` in `es`.
        let mut pt: HashMap<String, String> = HashMap::new();
        pt.insert("hello".into(), "Olá".into());
        let mut en: HashMap<String, String> = HashMap::new();
        en.insert("hello".into(), "Hello".into());

        let t = Translator::new(Locale::new("en"))
            .with_fallback_chain(&["pt"])
            .add_locale(Locale::new("es"), es)
            .add_locale(Locale::new("pt"), pt)
            .add_locale(Locale::new("en"), en);

        // `welcome` exists in `es` — direct hit.
        assert_eq!(t.translate("es", "welcome", &[]), "Bienvenido");
        // `hello` is missing in `es`; chain says try `pt` next.
        assert_eq!(t.translate("es", "hello", &[]), "Olá");
    }

    /// Issue #425 — default locale is still the last terminus when
    /// nothing in the chain has the key.
    #[test]
    fn fallback_chain_then_default() {
        let mut en: HashMap<String, String> = HashMap::new();
        en.insert("hello".into(), "Hello".into());
        let pt: HashMap<String, String> = HashMap::new();

        let t = Translator::new(Locale::new("en"))
            .with_fallback_chain(&["pt"])
            .add_locale(Locale::new("pt"), pt)
            .add_locale(Locale::new("en"), en);

        // `es` not in catalogs, chain entry `pt` doesn't have the key,
        // default `en` does.
        assert_eq!(t.translate("es", "hello", &[]), "Hello");
    }

    /// Issue #425 — chain accessor returns what was set, sans duplicates
    /// and sans the default-locale entry.
    #[test]
    fn fallback_chain_accessor_deduplicates() {
        let t = Translator::new(Locale::new("en")).with_fallback_chain(&["pt", "pt", "en", "es"]);
        let chain: Vec<&str> = t.fallback_chain().iter().map(Locale::as_str).collect();
        assert_eq!(chain, vec!["pt", "es"]);
    }

    #[test]
    fn locales_lists_registered() {
        let t = make_translator();
        let mut locales = t.locales();
        locales.sort();
        assert_eq!(locales, vec!["en".to_string(), "fr".to_string()]);
    }

    // ---- #429 RTL detection ----

    #[test]
    fn locale_is_rtl_for_arabic_hebrew_persian_urdu() {
        for code in ["ar", "he", "fa", "ur", "ps", "yi", "dv", "ckb", "ug", "sd"] {
            let loc = Locale::new(code);
            assert!(loc.is_rtl(), "{code} should be RTL");
            assert_eq!(loc.direction(), "rtl", "{code} direction should be rtl");
        }
    }

    #[test]
    fn locale_is_ltr_for_western_and_cjk() {
        for code in ["en", "fr", "de", "es", "ja", "zh", "ko", "ru", "tr", "pt"] {
            let loc = Locale::new(code);
            assert!(!loc.is_rtl(), "{code} should be LTR");
            assert_eq!(loc.direction(), "ltr", "{code} direction should be ltr");
        }
    }

    #[test]
    fn rtl_check_uses_base_language_for_region_subtag() {
        // Region-specific Arabic / Hebrew variants still RTL.
        assert!(Locale::new("ar-EG").is_rtl());
        assert!(Locale::new("AR-SA").is_rtl()); // case-insensitive ctor
        assert!(Locale::new("he-IL").is_rtl());
        // Region-specific LTR locales stay LTR.
        assert!(!Locale::new("en-US").is_rtl());
        assert!(!Locale::new("pt-BR").is_rtl());
    }

    #[test]
    fn rtl_check_handles_retired_iso_codes() {
        // Some Accept-Language headers still emit the old ISO 639-1 codes.
        assert!(Locale::new("iw").is_rtl()); // Hebrew (retired alias)
        assert!(Locale::new("ji").is_rtl()); // Yiddish (retired alias)
    }

    // ---- Language display/native names ----

    #[test]
    fn display_name_returns_english_label_for_known_locales() {
        assert_eq!(Locale::new("en").display_name(), "English");
        assert_eq!(Locale::new("fr-FR").display_name(), "French");
        assert_eq!(Locale::new("zh-CN").display_name(), "Chinese");
        assert_eq!(Locale::new("ar-EG").display_name(), "Arabic");
        assert_eq!(Locale::new("he-IL").display_name(), "Hebrew");
        assert_eq!(Locale::new("iw").display_name(), "Hebrew"); // retired alias
    }

    #[test]
    fn native_name_returns_endonym_for_known_locales() {
        assert_eq!(Locale::new("en").native_name(), "English");
        assert_eq!(Locale::new("fr-CA").native_name(), "français");
        assert_eq!(Locale::new("ja").native_name(), "日本語");
        assert_eq!(Locale::new("zh-TW").native_name(), "中文");
        assert_eq!(Locale::new("ar").native_name(), "العربية");
        assert_eq!(Locale::new("he").native_name(), "עברית");
    }

    #[test]
    fn unknown_locale_falls_back_to_unknown_label() {
        assert_eq!(Locale::new("xx").display_name(), "Unknown");
        assert_eq!(Locale::new("xx").native_name(), "Unknown");
    }

    #[test]
    fn norwegian_variants_share_one_label() {
        // Norwegian Bokmål / Nynorsk should collapse to one label.
        for code in ["no", "nb", "nn", "nb-NO", "nn-NO"] {
            assert_eq!(Locale::new(code).display_name(), "Norwegian", "{code}");
            assert_eq!(Locale::new(code).native_name(), "norsk", "{code}");
        }
    }

    #[test]
    fn bare_string_helpers_match_locale_methods() {
        for code in ["ar", "fa-IR", "he-IL", "iw"] {
            assert!(is_rtl_language(code), "{code} should be RTL");
            assert_eq!(text_direction(code), "rtl");
        }
        for code in ["en", "fr-FR", "ja", "zh-CN"] {
            assert!(!is_rtl_language(code), "{code} should be LTR");
            assert_eq!(text_direction(code), "ltr");
        }
    }

    #[test]
    fn negotiate_picks_highest_q() {
        let lang = negotiate_language("en;q=0.5,fr;q=0.9,de;q=0.1", &["en", "fr", "de"]);
        assert_eq!(lang.as_deref(), Some("fr"));
    }

    #[test]
    fn negotiate_falls_back_to_base() {
        let lang = negotiate_language("fr-FR,fr;q=0.9,en;q=0.8", &["en", "fr"]);
        assert_eq!(lang.as_deref(), Some("fr"));
    }

    #[test]
    fn negotiate_no_match_returns_none() {
        let lang = negotiate_language("ja,zh", &["en", "fr"]);
        assert_eq!(lang, None);
    }

    #[test]
    fn negotiate_uses_default_q_of_1() {
        // "en" without q is 1.0; "fr;q=0.5" is 0.5 → en wins
        let lang = negotiate_language("en,fr;q=0.5", &["en", "fr"]);
        assert_eq!(lang.as_deref(), Some("en"));
    }

    #[test]
    fn negotiate_empty_accept_language_returns_none() {
        let lang = negotiate_language("", &["en", "fr"]);
        assert_eq!(lang, None);
    }

    // ============================================================ #422
    //
    // Django/gettext-shape aliases: `gettext`, `pgettext` (context
    // disambiguation), `ngettext` (English plural rule), + their
    // `_fmt` placeholder-substitution variants.

    fn translator_with_en_fr() -> Translator {
        let mut en = HashMap::new();
        en.insert("welcome".into(), "Welcome, {name}!".into());
        en.insert(
            "count_unread".into(),
            "You have {count} unread message.".into(),
        );
        en.insert(
            "count_unread_plural".into(),
            "You have {count} unread messages.".into(),
        );
        en.insert("verb\u{0004}save".into(), "Save".into()); // pgettext context=verb, key=save
        en.insert("noun\u{0004}save".into(), "Discount".into()); // pgettext context=noun, key=save
        en.insert("save".into(), "Save (bare)".into());

        let mut fr = HashMap::new();
        fr.insert("welcome".into(), "Bienvenue, {name} !".into());
        fr.insert(
            "count_unread".into(),
            "Vous avez {count} message non lu.".into(),
        );
        fr.insert(
            "count_unread_plural".into(),
            "Vous avez {count} messages non lus.".into(),
        );

        Translator::new(Locale::new("en"))
            .add_locale(Locale::new("en"), en)
            .add_locale(Locale::new("fr"), fr)
    }

    #[test]
    fn gettext_returns_translated_string_no_params() {
        let t = translator_with_en_fr();
        // No interpolation — gettext returns the raw template.
        assert_eq!(t.gettext("en", "welcome"), "Welcome, {name}!");
    }

    #[test]
    fn gettext_fmt_substitutes_placeholders() {
        let t = translator_with_en_fr();
        assert_eq!(
            t.gettext_fmt("fr", "welcome", &[("name", "Alice")]),
            "Bienvenue, Alice !"
        );
    }

    #[test]
    fn gettext_falls_back_to_key_on_miss() {
        let t = translator_with_en_fr();
        // Missing keys fall through to the literal source string —
        // matches Django's behavior where untranslated msgids
        // surface unchanged.
        assert_eq!(t.gettext("en", "no_such_key"), "no_such_key");
    }

    #[test]
    fn pgettext_uses_context_disambiguated_entry() {
        let t = translator_with_en_fr();
        assert_eq!(t.pgettext("en", "verb", "save"), "Save");
        assert_eq!(t.pgettext("en", "noun", "save"), "Discount");
    }

    #[test]
    fn pgettext_falls_back_to_bare_key_when_context_entry_missing() {
        let t = translator_with_en_fr();
        // Unknown context → fall through to the bare-key entry
        // (matches Django's pgettext fallback).
        assert_eq!(t.pgettext("en", "adjective", "save"), "Save (bare)");
    }

    #[test]
    fn pgettext_fmt_substitutes_placeholders() {
        let mut en = HashMap::new();
        en.insert("button\u{0004}greet".into(), "Hi, {name}".into());
        let t = Translator::new(Locale::new("en")).add_locale(Locale::new("en"), en);
        assert_eq!(
            t.pgettext_fmt("en", "button", "greet", &[("name", "Bob")]),
            "Hi, Bob"
        );
    }

    #[test]
    fn ngettext_picks_singular_when_count_is_one() {
        let t = translator_with_en_fr();
        let s = t.ngettext("en", "count_unread", "count_unread_plural", 1);
        assert_eq!(s, "You have 1 unread message.");
    }

    #[test]
    fn ngettext_picks_plural_for_zero_and_many() {
        let t = translator_with_en_fr();
        let s0 = t.ngettext("en", "count_unread", "count_unread_plural", 0);
        let s5 = t.ngettext("en", "count_unread", "count_unread_plural", 5);
        // English plural rule — `n != 1` is plural, so n=0 plural too.
        assert_eq!(s0, "You have 0 unread messages.");
        assert_eq!(s5, "You have 5 unread messages.");
    }

    #[test]
    fn ngettext_works_in_french_locale() {
        let t = translator_with_en_fr();
        let s1 = t.ngettext("fr", "count_unread", "count_unread_plural", 1);
        let s3 = t.ngettext("fr", "count_unread", "count_unread_plural", 3);
        assert_eq!(s1, "Vous avez 1 message non lu.");
        assert_eq!(s3, "Vous avez 3 messages non lus.");
    }

    #[test]
    fn ngettext_fmt_overlays_extra_placeholders() {
        let mut en = HashMap::new();
        en.insert(
            "item_singular".into(),
            "{count} {item} sold to {customer}.".into(),
        );
        en.insert(
            "item_plural".into(),
            "{count} {item}s sold to {customer}.".into(),
        );
        let t = Translator::new(Locale::new("en")).add_locale(Locale::new("en"), en);
        let s = t.ngettext_fmt(
            "en",
            "item_singular",
            "item_plural",
            2,
            &[("item", "book"), ("customer", "Alice")],
        );
        assert_eq!(s, "2 books sold to Alice.");
    }
}