garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 国际化模块,提供异常消息多语言切换(中英文)。
//!
//! - `GarrisonLocale`:支持的语言枚举(默认 `En`,英文)
//! - thread_local 栈式 scope:`set_locale()` 返回 RAII guard,drop 时自动 pop
//! - FTL 词条经 `include_str!` 编译期内嵌,懒加载注册进 sdforge i18n 宿主注册表(`register_translation`),查询走其 `translate_for` 链
//! - `translate_error(&GarrisonError) -> String`:依据当前 locale 经 sdforge i18n 解析
//!
//! ## 使用示例
//!
//! ```ignore
//! use garrison::i18n::{set_locale, GarrisonLocale};
//! use garrison::error::GarrisonError;
//!
//! // 默认中文
//! let err = GarrisonError::NotLogin("请先登录".to_string());
//! assert_eq!(err.to_string(), "未登录: 请先登录");
//!
//! // 切换英文
//! let _guard = set_locale(GarrisonLocale::En);
//! assert_eq!(err.to_string(), "Not logged in: 请先登录");
//!
//! // guard drop 后自动恢复中文
//! ```
use crate::error::GarrisonError;
use std::cell::RefCell;
use std::sync::OnceLock;

/// 构造本地化错误文案:按 `key` 查 FTL 翻译,缺 key 或格式化失败回退 `$fallback`,`$fallback` 为空串时返回 `key` 本身(既有调用点传 `""` 时输出与旧行为一致)。
///
/// i18n 基础层无条件编译,本宏始终委托 [`translate_detail`],无需 feature 门控。
///
/// # 示例
///
/// ```ignore
/// let err = GarrisonError::Network(loc!(
/// "wechat-response-missing-openid",
/// "wechat response missing openid field".to_string()
/// ));
/// ```
#[macro_export]
macro_rules! loc {
    ($key:expr, $fallback:expr $(, ($arg_k:expr, $arg_v:expr))*) => {{
        let translated = $crate::i18n::translate_detail($key, &[$(($arg_k, $arg_v)),*]);
        if translated == $key {
            // 缺 key:应用调用方 fallback;空串保持返回 key(视为未提供)
            let fallback = $fallback.to_string();
            if fallback.is_empty() {
                translated
            } else {
                fallback
            }
        } else {
            translated
        }
    }};
}

/// 支持的语言枚举(仅中文与英文):`#[default] En` 为系统语言探测失败的回退值;未显式 [`set_locale`] 时 [`current_locale()`] 首次调用探测系统语言并缓存。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GarrisonLocale {
    /// 中文。
    Zh,
    /// 英文(默认语言,亦为探测失败回退)。
    #[default]
    En,
}

impl GarrisonLocale {
    /// 返回对应的 BCP-47 语言标签(同时用作 sdforge i18n 注册桶键)。
    fn as_language_tag(self) -> &'static str {
        match self {
            GarrisonLocale::Zh => "zh-CN",
            GarrisonLocale::En => "en",
        }
    }
}

// 系统语言自动检测(GARRISON_LANG → LC_ALL → LC_MESSAGES → LANG → sys-locale)

/// 系统语言检测结果缓存(进程级):locale 栈为空时由 [`current_locale()`] 首次调用填充,所有线程"无显式 locale"状态共用;[`set_locale`] 覆盖栈内值,guard 全 pop 后回到该缓存值。
static DETECTED_LOCALE: OnceLock<GarrisonLocale> = OnceLock::new();

/// 探测系统语言(检测链命中即返回):`GARRISON_LANG` → `LC_ALL`/`LC_MESSAGES`/`LANG`(显式读取保证 Windows/边缘环境确定性)→ `sys_locale::get_locale()` → 回退 [`GarrisonLocale::En`]。
///
/// 仅映射 `zh*`/`en*`;`C`/`POSIX` 与第三语言跳过并继续走链,链尾必为 `En`。
pub fn detect_locale() -> GarrisonLocale {
    detect_from(
        &|key| std::env::var(key).ok(),
        sys_locale::get_locale().as_deref(),
    )
}

/// 检测链纯函数:env 查找与系统 locale 均注入,不读进程环境,便于测试。
fn detect_from(getenv: &dyn Fn(&str) -> Option<String>, sys: Option<&str>) -> GarrisonLocale {
    detect_from_env(getenv)
        .or_else(|| sys.and_then(normalize_lang))
        .unwrap_or(GarrisonLocale::En)
}

/// 环境变量检测链:`GARRISON_LANG` → `LC_ALL` → `LC_MESSAGES` → `LANG`。
///
/// 全链未命中(无变量、空值、`C`/`POSIX`、不支持的第三语言)返回 `None`,
/// 交由 [`detect_from`] 继续走 sys-locale / `En` 回退。
fn detect_from_env(getenv: &dyn Fn(&str) -> Option<String>) -> Option<GarrisonLocale> {
    const CHAIN: [&str; 4] = ["GARRISON_LANG", "LC_ALL", "LC_MESSAGES", "LANG"];
    CHAIN.iter().find_map(|key| {
        getenv(key)
            .filter(|raw| !raw.trim().is_empty())
            .and_then(|raw| normalize_lang(&raw))
    })
}

/// 归一化语言标签:去 `@modifier`/`.codeset`(`zh_CN.UTF-8` → `zh-CN`),`zh*`/`en*` 映射两枚举;`C`/`POSIX` 与第三语言返回 `None`,交由检测链继续回退。
fn normalize_lang(raw: &str) -> Option<GarrisonLocale> {
    let tag = raw
        .split('@')
        .next()
        .unwrap_or_default()
        .split('.')
        .next()
        .unwrap_or_default()
        .replace('_', "-");
    if matches!(tag.as_str(), "C" | "POSIX") {
        return None;
    }
    let lang = tag
        .split('-')
        .next()
        .unwrap_or_default()
        .to_ascii_lowercase();
    match lang.as_str() {
        "zh" => Some(GarrisonLocale::Zh),
        "en" => Some(GarrisonLocale::En),
        _ => None,
    }
}

// thread_local 栈式 scope(支持嵌套 set_locale 调用)

thread_local! {
    static CURRENT_LOCALE_STACK: RefCell<Vec<GarrisonLocale>> = const { RefCell::new(Vec::new()) };
}

/// 获取当前 locale(线程本地):[`set_locale`] scope 内返回栈顶显式值,否则返回缓存的系统检测值(首次经 [`detect_locale`] 探测,失败回退 `En`)。
pub fn current_locale() -> GarrisonLocale {
    CURRENT_LOCALE_STACK.with(|stack| match stack.borrow().last() {
        Some(locale) => *locale,
        None => *DETECTED_LOCALE.get_or_init(detect_locale),
    })
}

/// 设置当前线程 locale 并返回 RAII guard(drop 自动 pop,支持嵌套);显式值优先于 [`detect_locale`] 检测值,栈 pop 回空后回到缓存的检测值。
///
/// # 示例
///
/// ```ignore
/// let _guard = set_locale(GarrisonLocale::En);
/// // 此范围内 current_locale() == En
/// ```
pub fn set_locale(locale: GarrisonLocale) -> LocaleGuard {
    CURRENT_LOCALE_STACK.with(|stack| stack.borrow_mut().push(locale));
    LocaleGuard { _priv: () }
}

/// RAII guard(由 [`set_locale`] 返回,不应手动构造):drop 时 pop locale 栈恢复上一个 locale。
pub struct LocaleGuard {
    _priv: (),
}

impl Drop for LocaleGuard {
    fn drop(&mut self) {
        CURRENT_LOCALE_STACK.with(|stack| {
            stack.borrow_mut().pop();
        });
    }
}

// sdforge i18n 宿主注册(FTL 真源 include_str! 编译期内嵌,懒加载注册一次)

/// FTL 词条注册标记(进程级一次)。
static I18N_REGISTERED: OnceLock<()> = OnceLock::new();

/// 结算一条 FTL 条目:去前导空行、剥非空行公共缩进(fluent 多行语义)、
/// 还原 fluent 转义括号 `{"{"}`/`{"}"}` 为字面 `{`/`}`、去尾部空行。
fn flush_ftl_entry(
    key: &mut Option<String>,
    lines: &mut Vec<String>,
    out: &mut Vec<(String, String)>,
) {
    if let Some(key) = key.take() {
        // `key =` 空值条目:首物理行为空占位,移除后其余行全部是续行;
        // `key = 内容` 条目:lines[0] 是 `=` 行本身,永不剥缩进
        let had_inline = lines.first().is_some_and(|l| !l.is_empty());
        if !had_inline && lines.first().is_some_and(|l| l.is_empty()) {
            lines.remove(0);
        }
        while lines.last().is_some_and(|l| l.is_empty()) {
            lines.pop();
        }
        // fluent 规则:公共缩进以首个非空续行为基准,仅剥「确实以该前缀开头」的续行;
        // `=` 行(had_inline 时 lines[0])与不成前缀的行原样保留
        let cont_start = usize::from(had_inline);
        let common = lines
            .iter()
            .skip(cont_start)
            .filter(|l| !l.trim().is_empty())
            .map(|l| l.len() - l.trim_start().len())
            .min()
            .unwrap_or(0);
        let prefix = " ".repeat(common);
        let value = lines
            .iter()
            .enumerate()
            .map(|(i, l)| {
                let stripped = if i >= cont_start && common > 0 && l.starts_with(prefix.as_str()) {
                    &l[common..]
                } else {
                    l
                };
                stripped.replace("{\"{\"}", "{").replace("{\"}\"}", "}")
            })
            .collect::<Vec<_>>()
            .join("\n");
        out.push((key, value));
        lines.clear();
    }
}

/// 归一 FTL 源:占位符跨行断开(`{$` 行尾折行)时丢弃占位符内部的换行——
/// fluent 词法允许 placeable 内部换行(换行归属表达式空白,不进入渲染值)。
/// 花括号计数在 `{"{"}` 转义序列上配对平衡,不影响该规则。
fn normalize_ftl_placeholders(ftl: &str) -> String {
    if !ftl.contains("{$") {
        return ftl.to_string();
    }
    let mut out = String::with_capacity(ftl.len());
    let mut in_placeholder = false;
    for ch in ftl.chars() {
        match ch {
            '{' => {
                in_placeholder = true;
                out.push(ch);
            },
            '}' => {
                in_placeholder = false;
                out.push(ch);
            },
            '\n' if in_placeholder => {},
            _ => out.push(ch),
        }
    }
    out
}

/// 解析 FTL 文本为 (key, value) 条目(fluent 语义):`key = value` 起条(首行内容可为空),
/// 其后的缩进续行与空行并入 value 直至下一个条目/注释;`#` 注释行跳过。
/// 与 locales/*.ftl 真源一一对应(纯文本消息,无 selector/term 语法)。
fn parse_ftl_entries(ftl: &str) -> Vec<(String, String)> {
    let ftl = &normalize_ftl_placeholders(ftl);
    let mut out: Vec<(String, String)> = Vec::new();
    let mut cur_key: Option<String> = None;
    let mut cur_lines: Vec<String> = Vec::new();
    for line in ftl.lines() {
        if cur_key.is_some() && (line.starts_with([' ', '\t']) || line.trim().is_empty()) {
            // 当前条目的续行或段内空行
            cur_lines.push(line.to_string());
            continue;
        }
        // 到达新条目/注释/顶层空行:结算当前条目
        flush_ftl_entry(&mut cur_key, &mut cur_lines, &mut out);
        if line.trim().is_empty() || line.trim_start().starts_with('#') {
            continue;
        }
        if let Some((k, v)) = line.split_once('=') {
            cur_key = Some(k.trim().to_string());
            cur_lines.push(v.trim().to_string());
        }
    }
    flush_ftl_entry(&mut cur_key, &mut cur_lines, &mut out);
    out
}

/// 将两份 FTL 真源注册进 sdforge i18n 宿主注册表(懒加载,进程级一次)。
fn ensure_registered() {
    I18N_REGISTERED.get_or_init(|| {
        for (tag, ftl) in [
            ("zh-CN", include_str!("../locales/zh.ftl")),
            ("en", include_str!("../locales/en.ftl")),
        ] {
            for (key, value) in parse_ftl_entries(ftl) {
                sdforge::i18n::register_translation(tag, &key, &value);
            }
        }
    });
}

/// 按 (locale tag, key, args) 解析;命中返回渲染文本,未命中返回 `None`。
///
/// 渲染结果仍含 `{$name}` 形态占位符视为未命中:与旧 fluent 引擎的格式错误语义对齐
/// (缺变量 ⇒ 格式失败 ⇒ 调用方回退),避免把残缺模板直接透给用户。
fn lookup(tag: &str, key: &str, args: &[(&str, &str)]) -> Option<String> {
    ensure_registered();
    let sd_args: Vec<(&str, String)> = args.iter().map(|(k, v)| (*k, (*v).to_string())).collect();
    let rendered = sdforge::i18n::translate_for(tag, key, &sd_args);
    if rendered == key || rendered.contains("{$") || rendered.contains("{ $") {
        None
    } else {
        Some(rendered)
    }
}

// 错误翻译:依据当前 locale 经 sdforge i18n 解析

/// 将 `GarrisonError` 翻译为当前 locale 的本地化字符串:按 `current_locale()` 经 sdforge i18n 查 key 与 args;当前语言缺失时回退 en 词条,en 亦缺失时回退硬编码英文(与 `locales/en.ftl` 模板一致)。
pub fn translate_error(err: &GarrisonError) -> String {
    let tag = current_locale().as_language_tag();
    let (key, args) = error_to_key_args(err);
    let args_ref: Vec<(&str, &str)> = args.iter().map(|(k, v)| (*k, v.as_str())).collect();
    match lookup(tag, key, &args_ref) {
        Some(value) => value,
        None => {
            if tag != "en" {
                if let Some(value) = lookup("en", key, &args_ref) {
                    return value;
                }
            }
            // 翻译缺失回退到硬编码英文
            fallback_display(err)
        },
    }
}

/// 按 key + args 翻译为当前 locale 的本地化字符串;不依赖 `GarrisonError`,供 `loc!` 宏与社交登录 / Keycloak 等模块按需翻译异常 detail。
/// 未找到 key 或格式化出错返回 `key` 本身([`loc!`] 在此基础上应用调用方 fallback,空时保持 key)。
pub fn translate_detail(key: &str, args: &[(&str, &str)]) -> String {
    let tag = current_locale().as_language_tag();
    match lookup(tag, key, args) {
        Some(value) => value,
        None => {
            if tag != "en" {
                // 当前语言缺词条时回退 en 束(与 sdforge i18n 的 zh→en 回退链一致)
                lookup("en", key, args).unwrap_or_else(|| key.to_string())
            } else {
                key.to_string()
            }
        },
    }
}

/// 解析结构化错误 detail `key::arg0::arg1`:拆出 FTL message key 与位置参数(键 `arg0`/`arg1`,因 Fluent 变量标识符不能以数字开头);非结构化串返回 `None`,交由调用方回退 variant 默认 key。
fn parse_keyed_detail(s: &str) -> Option<(&'static str, Vec<(&'static str, String)>)> {
    // 仅当包含 `::` 分隔符才视为结构化 key,避免把普通中文/英文串误判为 key
    if !s.contains("::") {
        return None;
    }
    let mut parts = s.splitn(3, "::");
    let key = parts.next()?;
    // key 必须以字母开头且为合法 kebab-case(允许数字段:argon2 / l1 / jwt-ec-sec1 等;
    // 中文串与含空格/大写的普通句子仍不满足形态,不会被误判为 key)
    if key.is_empty() || !key.chars().next().unwrap().is_ascii_alphabetic() {
        return None;
    }
    if key
        .chars()
        .any(|c| !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'))
    {
        return None;
    }
    let static_key = intern_string(key);
    let a0 = parts.next();
    let a1 = parts.next();
    match (a0, a1) {
        (None, None) | (None, Some(_)) => Some((static_key, vec![])),
        (Some(x), None) => Some((static_key, vec![("arg0", x.to_string())])),
        (Some(x), Some(y)) => Some((
            static_key,
            vec![("arg0", x.to_string()), ("arg1", y.to_string())],
        )),
    }
}

/// 全局字符串缓存:相同 key 只 `Box::leak` 一次,后续复用已缓存的 `&'static str`。
fn intern_string(s: &str) -> &'static str {
    use std::collections::HashMap;
    use std::sync::Mutex;
    static CACHE: Mutex<Option<HashMap<String, &'static str>>> = Mutex::new(None);
    let mut guard = CACHE.lock().unwrap();
    let map = guard.get_or_insert_with(HashMap::new);
    if let Some(&cached) = map.get(s) {
        return cached;
    }
    let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
    map.insert(s.to_string(), leaked);
    leaked
}

/// 单个 `String` 错误字段 → (key, args):优先结构化 `key::arg`,否则 variant 默认 key + `detail` 参数(兼容未迁移的硬编码中文串)。
fn string_detail(
    variant_key: &'static str,
    s: &str,
) -> (&'static str, Vec<(&'static str, String)>) {
    match parse_keyed_detail(s) {
        Some((k, args)) => (k, args),
        None => (variant_key, vec![("detail", s.to_string())]),
    }
}

/// 错误到 FTL message key + args 的映射。
fn error_to_key_args(err: &GarrisonError) -> (&'static str, Vec<(&'static str, String)>) {
    match err {
        GarrisonError::NotLogin(s) => string_detail("not-login", s),
        GarrisonError::NotPermission(s) => string_detail("not-permission", s),
        GarrisonError::NotRole(s) => string_detail("not-role", s),
        GarrisonError::InvalidToken(s) => string_detail("invalid-token", s),
        GarrisonError::TokenRevoked(s) => string_detail("token-revoked", s),
        GarrisonError::ExpiredToken(s) => string_detail("expired-token", s),
        GarrisonError::Dao(s) => string_detail("dao", s),
        GarrisonError::Config(s) => string_detail("config", s),
        GarrisonError::Internal(s) => string_detail("internal", s),
        GarrisonError::Session(s) => string_detail("session", s),
        GarrisonError::Annotation(s) => string_detail("annotation", s),
        GarrisonError::Context(s) => string_detail("context", s),
        GarrisonError::OAuth2(s) => string_detail("oauth2", s),
        GarrisonError::Network(s) => string_detail("network", s),
        GarrisonError::InvalidResponse(s) => string_detail("invalid-response", s),
        GarrisonError::InvalidParam(s) => string_detail("invalid-param", s),
        GarrisonError::NotImplemented(s) => string_detail("not-implemented", s),
        GarrisonError::FirewallBlocked(s) => string_detail("firewall-blocked", s),
        GarrisonError::DisableService { service, until } => (
            "disable-service",
            vec![
                ("service", service.clone()),
                ("until", format!("{:?}", until)),
            ],
        ),
        GarrisonError::NotSafe { reason } => ("not-safe", vec![("reason", reason.clone())]),
        GarrisonError::InvalidStateTransition { from, to } => (
            "invalid-state-transition",
            vec![("from", from.clone()), ("to", to.clone())],
        ),
        GarrisonError::SmsRateLimitExceeded { window } => {
            ("sms-rate-limit-exceeded", vec![("window", window.clone())])
        },
        GarrisonError::SmsVerifyMaxAttempts => ("sms-verify-max-attempts", vec![]),
        GarrisonError::SmsCodeNotFound => ("sms-code-not-found", vec![]),
        GarrisonError::SmsChannelRecycled => ("sms-channel-recycled", vec![]),
        GarrisonError::RateLimited { .. } => ("rate-limited", vec![]),
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailRateLimitExceeded { window } => (
            "email-rate-limit-exceeded",
            vec![("window", window.clone())],
        ),
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailVerifyMaxAttempts => ("email-verify-max-attempts", vec![]),
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailCodeNotFound => ("email-code-not-found", vec![]),
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailChannelRecycled => ("email-channel-recycled", vec![]),
        #[cfg(feature = "credit-metering")]
        GarrisonError::CreditInsufficient {
            tenant_id,
            requested,
            remaining,
        } => (
            "credit-insufficient",
            vec![
                ("tenant_id", tenant_id.to_string()),
                ("requested", requested.to_string()),
                ("remaining", remaining.to_string()),
            ],
        ),
        GarrisonError::Exception(ex) => (
            "exception",
            vec![
                ("code", ex.code.to_string()),
                ("detail", ex.message.clone()),
            ],
        ),
    }
}

/// 翻译失败时的硬编码英文回退(文案与 `locales/en.ftl` 英文模板一致)。
fn fallback_display(err: &GarrisonError) -> String {
    match err {
        GarrisonError::NotLogin(s) => format!("Not logged in: {}", s),
        GarrisonError::NotPermission(s) => format!("Permission denied: {}", s),
        GarrisonError::NotRole(s) => format!("Role denied: {}", s),
        GarrisonError::InvalidToken(s) => format!("Invalid token: {}", s),
        GarrisonError::TokenRevoked(s) => format!("Token revoked: {}", s),
        GarrisonError::ExpiredToken(s) => format!("Token expired: {}", s),
        GarrisonError::Dao(s) => format!("DAO error: {}", s),
        GarrisonError::Config(s) => format!("Configuration error: {}", s),
        GarrisonError::Internal(s) => format!("Internal error: {}", s),
        GarrisonError::Session(s) => format!("Session error: {}", s),
        GarrisonError::Annotation(s) => format!("Annotation error: {}", s),
        GarrisonError::Context(s) => format!("Context error: {}", s),
        GarrisonError::OAuth2(s) => format!("OAuth2 error: {}", s),
        GarrisonError::Network(s) => format!("Network error: {}", s),
        GarrisonError::InvalidResponse(s) => format!("Invalid upstream response: {}", s),
        GarrisonError::InvalidParam(s) => format!("Invalid parameter: {}", s),
        GarrisonError::NotImplemented(s) => format!("Not implemented: {}", s),
        GarrisonError::FirewallBlocked(s) => format!("Firewall blocked: {}", s),
        GarrisonError::DisableService { service, until } => {
            format!("Account disabled: service={}, until={:?}", service, until)
        },
        GarrisonError::NotSafe { reason } => {
            format!("Second factor authentication required: {}", reason)
        },
        GarrisonError::InvalidStateTransition { from, to } => {
            format!("Invalid state transition: {} -> {}", from, to)
        },
        GarrisonError::SmsRateLimitExceeded { window } => {
            format!("SMS rate limit exceeded: {} window", window)
        },
        GarrisonError::SmsVerifyMaxAttempts => "SMS verification max attempts exceeded".to_string(),
        GarrisonError::SmsCodeNotFound => "SMS verification code not found".to_string(),
        GarrisonError::SmsChannelRecycled => "SMS channel recycled".to_string(),
        GarrisonError::RateLimited { .. } => "Rate limited".to_string(),
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailRateLimitExceeded { window } => {
            format!("Email rate limit exceeded: {} window", window)
        },
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailVerifyMaxAttempts => {
            "Email verification max attempts exceeded".to_string()
        },
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailCodeNotFound => "Email verification code not found".to_string(),
        #[cfg(feature = "email-verification")]
        GarrisonError::EmailChannelRecycled => "Email channel recycled".to_string(),
        #[cfg(feature = "credit-metering")]
        GarrisonError::CreditInsufficient {
            tenant_id,
            requested,
            remaining,
        } => {
            format!(
                "Credit insufficient: tenant={}, requested={}, remaining={}",
                tenant_id, requested, remaining
            )
        },
        GarrisonError::Exception(ex) => format!("Business exception[{}]: {}", ex.code, ex.message),
    }
}

// ICU4X 增强层(feature = "i18n-icu",ICU4X 经 trait-kit "i18n" feature 统一供给)

/// locale 感知格式化增强模块(仅 `i18n-icu` feature 编译):复数规则、日期/数字本地化,
/// 底层统一走 trait-kit `I18nFormatter`(ICU4X 单一来源),不影响现有翻译逻辑。
#[cfg(feature = "i18n-icu")]
pub mod icu_enhanced {
    use crate::i18n::{current_locale, GarrisonLocale};
    use chrono::{Datelike, Timelike};

    /// 当前 locale 的 trait-kit 格式化器(zh-CN/en 恒可构造)。
    fn formatter() -> trait_kit::i18n::I18nFormatter {
        let tag = match current_locale() {
            GarrisonLocale::Zh => "zh-CN",
            GarrisonLocale::En => "en",
        };
        trait_kit::i18n::I18nFormatter::new(tag)
            .expect("trait-kit I18nFormatter 对 zh-CN/en 恒可构造;若失败请报告 bug")
    }

    /// `PluralCategory` 的 Debug 形态 → 小写类别名(trait-kit 未重导出该类型,经字符串映射解耦)。
    fn plural_to_str(debug: &str) -> &'static str {
        match debug {
            "Zero" => "zero",
            "One" => "one",
            "Two" => "two",
            "Few" => "few",
            "Many" => "many",
            _ => "other",
        }
    }

    /// 当前 locale 下 `count` 的复数类别名(Cardinal,小写:zero/one/two/few/many/other),用于选择正确复数形式。
    pub fn plural_category(count: usize) -> &'static str {
        match formatter().plural_category(count as u64) {
            Ok(cat) => plural_to_str(&format!("{cat:?}")),
            Err(_) => "other",
        }
    }

    /// 格式化 `chrono::DateTime` 为当前 locale 的本地化字符串:日期经 trait-kit ICU4X
    /// (如 "2026年1月1日" / "Jan 1, 2026"),时间部分与 locale 无关,附固定 24 小时制 `HH:MM:SS`。
    pub fn format_datetime_locale(dt: &chrono::DateTime<chrono::Utc>) -> String {
        let date = formatter()
            .format_date(dt.year(), dt.month() as u8, dt.day() as u8)
            .expect("trait-kit format_date 对合法日历日期不应失败");
        format!(
            "{date} {:02}:{:02}:{:02}",
            dt.hour(),
            dt.minute(),
            dt.second()
        )
    }

    /// 格式化整数为当前 locale 的本地化字符串(千分位/数字系统,如 en "1,000,000",经 trait-kit ICU4X)。
    pub fn format_number_locale(n: i64) -> String {
        formatter()
            .format_number(n as f64)
            .expect("trait-kit format_number 不应失败")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::GarrisonError;
    use crate::exception::GarrisonException;

    // GarrisonLocale 枚举测试

    /// 枚举默认值应为英文;`En` 同时是系统语言探测失败的最终回退。
    #[test]
    fn default_locale_is_en() {
        let locale = GarrisonLocale::default();
        assert_eq!(locale, GarrisonLocale::En);
    }

    #[test]
    fn as_language_tag_returns_correct_tag() {
        assert_eq!(GarrisonLocale::Zh.as_language_tag(), "zh-CN");
        assert_eq!(GarrisonLocale::En.as_language_tag(), "en");
    }

    // current_locale / set_locale 测试

    /// 仅断言 current_locale() 与 detect_locale() 同源(进程 env 因机器而异,映射细节由纯函数测试覆盖)。
    #[test]
    fn current_locale_defaults_to_detected_locale_when_not_set() {
        assert_eq!(current_locale(), detect_locale());
    }

    #[test]
    fn set_locale_changes_current_and_restores_on_drop() {
        let original = current_locale();
        {
            let _guard = set_locale(GarrisonLocale::En);
            assert_eq!(current_locale(), GarrisonLocale::En);
        }
        assert_eq!(current_locale(), original);
    }

    #[test]
    fn set_locale_supports_nesting() {
        let original = current_locale();
        {
            let _g1 = set_locale(GarrisonLocale::En);
            assert_eq!(current_locale(), GarrisonLocale::En);
            {
                let _g2 = set_locale(GarrisonLocale::Zh);
                assert_eq!(current_locale(), GarrisonLocale::Zh);
            }
            assert_eq!(current_locale(), GarrisonLocale::En);
        }
        assert_eq!(current_locale(), original);
    }

    #[test]
    fn set_locale_overrides_detection_and_pop_restores_detected() {
        let detected = current_locale(); // 首次调用触发探测并缓存
        {
            let _guard = set_locale(GarrisonLocale::En);
            assert_eq!(current_locale(), GarrisonLocale::En);
        }
        assert_eq!(current_locale(), detected);
        {
            let _guard = set_locale(GarrisonLocale::Zh);
            assert_eq!(current_locale(), GarrisonLocale::Zh);
        }
        assert_eq!(current_locale(), detected);
    }

    // 系统语言检测链测试(env 注入纯函数,不依赖进程环境)

    /// 构造注入式 env 查找闭包(按值持有,无生命周期绑定)。
    fn env_of<const N: usize>(
        vars: [(&'static str, &'static str); N],
    ) -> impl Fn(&str) -> Option<String> {
        move |key| {
            vars.iter()
                .find(|(k, _)| *k == key)
                .map(|(_, v)| v.to_string())
        }
    }

    #[test]
    fn detect_chain_zh_cn_utf8_yields_zh() {
        let getenv = env_of([("LANG", "zh_CN.UTF-8")]);
        assert_eq!(detect_from(&getenv, None), GarrisonLocale::Zh);
    }

    #[test]
    fn detect_chain_fr_fr_falls_back_to_en() {
        let getenv = env_of([("LANG", "fr_FR.UTF-8")]);
        assert_eq!(detect_from(&getenv, None), GarrisonLocale::En);
    }

    #[test]
    fn detect_chain_c_and_posix_fall_back_to_en() {
        let c = env_of([("LANG", "C")]);
        assert_eq!(detect_from(&c, None), GarrisonLocale::En);
        let posix = env_of([("LC_ALL", "POSIX")]);
        assert_eq!(detect_from(&posix, None), GarrisonLocale::En);
        let c_utf8 = env_of([("LANG", "C.UTF-8")]);
        assert_eq!(detect_from(&c_utf8, None), GarrisonLocale::En);
    }

    #[test]
    fn detect_chain_garrison_lang_takes_precedence() {
        let en_overrides_zh = env_of([("GARRISON_LANG", "en_US"), ("LC_ALL", "zh_CN.UTF-8")]);
        assert_eq!(detect_from(&en_overrides_zh, None), GarrisonLocale::En);
        let zh_overrides_en = env_of([("GARRISON_LANG", "zh_CN"), ("LC_ALL", "en_US.UTF-8")]);
        assert_eq!(detect_from(&zh_overrides_en, None), GarrisonLocale::Zh);
    }

    #[test]
    fn detect_chain_lc_all_precedes_lang() {
        let getenv = env_of([("LC_ALL", "zh_CN.UTF-8"), ("LANG", "en_US.UTF-8")]);
        assert_eq!(detect_from(&getenv, None), GarrisonLocale::Zh);
    }

    #[test]
    fn detect_chain_empty_value_skipped() {
        let getenv = env_of([("GARRISON_LANG", "  "), ("LANG", "zh_CN")]);
        assert_eq!(detect_from(&getenv, None), GarrisonLocale::Zh);
    }

    #[test]
    fn detect_chain_empty_falls_back_to_en() {
        let none: fn(&str) -> Option<String> = |_key| None;
        assert_eq!(detect_from(&none, None), GarrisonLocale::En);
    }

    #[test]
    fn detect_chain_sys_locale_fallback() {
        let none: fn(&str) -> Option<String> = |_key| None;
        assert_eq!(detect_from(&none, Some("zh-Hans-CN")), GarrisonLocale::Zh);
        assert_eq!(detect_from(&none, Some("en-US")), GarrisonLocale::En);
        assert_eq!(detect_from(&none, Some("fr-FR")), GarrisonLocale::En);
        // env 链命中时 sys-locale 不参与
        let getenv = env_of([("LANG", "en_US.UTF-8")]);
        assert_eq!(detect_from(&getenv, Some("zh-CN")), GarrisonLocale::En);
    }

    #[test]
    fn detect_chain_normalizes_variants() {
        let none: fn(&str) -> Option<String> = |_key| None;
        for raw in ["zh", "zh_TW", "zh-Hant", "ZH-CN", "zh_SG@pinyin"] {
            assert_eq!(
                detect_from(&none, Some(raw)),
                GarrisonLocale::Zh,
                "raw={raw}"
            );
        }
        for raw in ["en", "en_GB.UTF-8", "EN-us"] {
            assert_eq!(
                detect_from(&none, Some(raw)),
                GarrisonLocale::En,
                "raw={raw}"
            );
        }
    }

    // translate_error 测试

    #[test]
    fn translate_error_zh_returns_chinese_message() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::NotLogin("请先登录".to_string());
        let translated = translate_error(&err);
        assert_eq!(translated, "未登录: 请先登录");
    }

    #[test]
    fn translate_error_en_returns_english_message() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::NotLogin("please login first".to_string());
        let translated = translate_error(&err);
        assert_eq!(translated, "Not logged in: please login first");
    }

    #[test]
    fn translate_error_zh_all_variants_match_hardcoded() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let cases = vec![
            (GarrisonError::NotLogin("a".into()), "未登录: a"),
            (GarrisonError::NotPermission("a".into()), "无权限: a"),
            (GarrisonError::NotRole("a".into()), "无角色: a"),
            (GarrisonError::InvalidToken("a".into()), "Token 无效: a"),
            (GarrisonError::ExpiredToken("a".into()), "Token 已过期: a"),
            (GarrisonError::Dao("a".into()), "DAO 错误: a"),
            (GarrisonError::Config("a".into()), "配置错误: a"),
            (GarrisonError::Internal("a".into()), "内部错误: a"),
            (GarrisonError::Session("a".into()), "会话错误: a"),
            (GarrisonError::Annotation("a".into()), "注解错误: a"),
            (GarrisonError::Context("a".into()), "上下文错误: a"),
            (GarrisonError::OAuth2("a".into()), "OAuth2 错误: a"),
            (GarrisonError::Network("a".into()), "网络错误: a"),
            (GarrisonError::InvalidParam("a".into()), "参数无效: a"),
            (GarrisonError::NotImplemented("a".into()), "未实现: a"),
        ];
        for (err, expected) in cases {
            assert_eq!(translate_error(&err), expected, "mismatch for {:?}", err);
        }
    }

    #[test]
    fn translate_error_en_all_variants_english() {
        let _guard = set_locale(GarrisonLocale::En);
        let cases = vec![
            (GarrisonError::NotLogin("a".into()), "Not logged in: a"),
            (
                GarrisonError::NotPermission("a".into()),
                "Permission denied: a",
            ),
            (GarrisonError::NotRole("a".into()), "Role denied: a"),
            (GarrisonError::InvalidToken("a".into()), "Invalid token: a"),
            (GarrisonError::ExpiredToken("a".into()), "Token expired: a"),
            (GarrisonError::Dao("a".into()), "DAO error: a"),
            (GarrisonError::Config("a".into()), "Configuration error: a"),
            (GarrisonError::Internal("a".into()), "Internal error: a"),
            (GarrisonError::Session("a".into()), "Session error: a"),
            (GarrisonError::Annotation("a".into()), "Annotation error: a"),
            (GarrisonError::Context("a".into()), "Context error: a"),
            (GarrisonError::OAuth2("a".into()), "OAuth2 error: a"),
            (GarrisonError::Network("a".into()), "Network error: a"),
            (
                GarrisonError::InvalidParam("a".into()),
                "Invalid parameter: a",
            ),
            (
                GarrisonError::NotImplemented("a".into()),
                "Not implemented: a",
            ),
        ];
        for (err, expected) in cases {
            assert_eq!(translate_error(&err), expected, "mismatch for {:?}", err);
        }
    }

    #[test]
    fn translate_error_zh_exception_variant() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::Exception(Box::new(GarrisonException::new(-1, "请先登录")));
        assert_eq!(translate_error(&err), "业务异常[-1]: 请先登录");
    }

    #[test]
    fn translate_error_en_exception_variant() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::Exception(Box::new(GarrisonException::new(-1, "please login")));
        assert_eq!(
            translate_error(&err),
            "Business exception[-1]: please login"
        );
    }

    #[test]
    fn locale_switch_is_isolated_per_scope() {
        let original = current_locale();
        {
            let _g = set_locale(GarrisonLocale::En);
            let err = GarrisonError::Dao("err".to_string());
            assert_eq!(translate_error(&err), "DAO error: err");
        }
        // 范围外恢复原 locale
        let err = GarrisonError::Dao("err".to_string());
        if original == GarrisonLocale::En {
            assert_eq!(translate_error(&err), "DAO error: err");
        } else {
            assert_eq!(translate_error(&err), "DAO 错误: err");
        }
    }

    #[test]
    fn fallback_display_matches_hardcoded_english() {
        let err = GarrisonError::NotLogin("test".to_string());
        assert_eq!(fallback_display(&err), "Not logged in: test");
    }

    #[test]
    fn fallback_display_all_variants() {
        let cases: Vec<(GarrisonError, &str)> = vec![
            (GarrisonError::NotLogin("x".into()), "Not logged in: x"),
            (
                GarrisonError::NotPermission("x".into()),
                "Permission denied: x",
            ),
            (GarrisonError::NotRole("x".into()), "Role denied: x"),
            (GarrisonError::InvalidToken("x".into()), "Invalid token: x"),
            (GarrisonError::ExpiredToken("x".into()), "Token expired: x"),
            (GarrisonError::Dao("x".into()), "DAO error: x"),
            (GarrisonError::Config("x".into()), "Configuration error: x"),
            (GarrisonError::Internal("x".into()), "Internal error: x"),
            (GarrisonError::Session("x".into()), "Session error: x"),
            (GarrisonError::Annotation("x".into()), "Annotation error: x"),
            (GarrisonError::Context("x".into()), "Context error: x"),
            (GarrisonError::OAuth2("x".into()), "OAuth2 error: x"),
            (GarrisonError::Network("x".into()), "Network error: x"),
            (
                GarrisonError::InvalidParam("x".into()),
                "Invalid parameter: x",
            ),
            (
                GarrisonError::NotImplemented("x".into()),
                "Not implemented: x",
            ),
            (
                GarrisonError::Exception(Box::new(GarrisonException::new(-1, "msg"))),
                "Business exception[-1]: msg",
            ),
        ];
        for (err, expected) in cases {
            assert_eq!(fallback_display(&err), expected, "mismatch for {:?}", err);
        }
    }

    #[test]
    fn ensure_registered_is_idempotent_and_populates_registry() {
        ensure_registered();
        ensure_registered();
        // 注册表已含 zh 词条:zh 查询命中(未注册则 lookup 返回 None)
        assert!(
            lookup("zh-CN", "not-login", &[("detail", "x")]).is_some(),
            "zh 注册后 lookup 应命中"
        );
    }

    // translate_detail 测试(loc! 宏底层调用)

    #[test]
    fn translate_detail_zh_returns_translated_message() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = translate_detail("not-login", &[("detail", "请先登录")]);
        assert_eq!(msg, "未登录: 请先登录");
    }

    #[test]
    fn translate_detail_en_returns_translated_message() {
        let _guard = set_locale(GarrisonLocale::En);
        let msg = translate_detail("not-login", &[("detail", "please login")]);
        assert_eq!(msg, "Not logged in: please login");
    }

    #[test]
    fn translate_detail_missing_key_returns_key() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = translate_detail("nonexistent-key-xyz", &[]);
        assert_eq!(msg, "nonexistent-key-xyz");
    }

    // loc! 宏 fallback 语义测试

    #[test]
    fn loc_macro_uses_fallback_when_key_missing() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = loc!("nonexistent-key-xyz", "human readable fallback");
        assert_eq!(msg, "human readable fallback");
    }

    #[test]
    fn loc_macro_uses_string_fallback_when_key_missing() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = loc!("nonexistent-key-xyz", "owned fallback".to_string());
        assert_eq!(msg, "owned fallback");
    }

    #[test]
    fn loc_macro_empty_fallback_keeps_key() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = loc!("nonexistent-key-xyz", "");
        assert_eq!(msg, "nonexistent-key-xyz");
    }

    #[test]
    fn loc_macro_translated_key_ignores_fallback() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = loc!("sms-verify-max-attempts", "unused fallback");
        assert_eq!(msg, "SMS 验证码尝试次数超限");
    }

    #[test]
    fn translate_detail_no_args_translates_successfully() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = translate_detail("sms-verify-max-attempts", &[]);
        assert_eq!(msg, "SMS 验证码尝试次数超限");
    }

    #[test]
    fn translate_detail_multiple_args_zh() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = translate_detail(
            "disable-service",
            &[
                ("service", "default"),
                ("until", "Some(2026-01-01T00:00:00Z)"),
            ],
        );
        assert!(msg.contains("service=default"));
        assert!(msg.contains("账号已被封禁"));
    }

    #[test]
    fn translate_detail_multiple_args_en() {
        let _guard = set_locale(GarrisonLocale::En);
        let msg = translate_detail(
            "invalid-state-transition",
            &[("from", "Active"), ("to", "Closed")],
        );
        assert_eq!(msg, "Invalid state transition: Active -> Closed");
    }

    // translate_error 测试

    #[test]
    fn translate_error_zh_token_revoked() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::TokenRevoked("reuse detected".to_string());
        let translated = translate_error(&err);
        assert_eq!(translated, "Token 已吊销: reuse detected");
    }

    #[test]
    fn translate_error_en_token_revoked() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::TokenRevoked("reuse detected".to_string());
        let translated = translate_error(&err);
        assert_eq!(translated, "Token revoked: reuse detected");
    }

    #[test]
    fn translate_error_zh_firewall_blocked() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::FirewallBlocked("black_path: /admin".to_string());
        let translated = translate_error(&err);
        assert_eq!(translated, "防火墙拦截: black_path: /admin");
    }

    #[test]
    fn translate_error_en_firewall_blocked() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::FirewallBlocked("black_path: /admin".to_string());
        let translated = translate_error(&err);
        assert_eq!(translated, "Firewall blocked: black_path: /admin");
    }

    #[test]
    fn translate_error_zh_disable_service() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let until = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let err = GarrisonError::DisableService {
            service: "default".to_string(),
            until: Some(until),
        };
        let translated = translate_error(&err);
        assert!(translated.contains("service=default"));
        assert!(translated.contains("账号已被封禁"));
    }

    #[test]
    fn translate_error_en_disable_service() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::DisableService {
            service: "oidc".to_string(),
            until: None,
        };
        let translated = translate_error(&err);
        assert!(translated.contains("service=oidc"));
        assert!(translated.contains("Account disabled"));
    }

    #[test]
    fn translate_error_zh_not_safe() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::NotSafe {
            reason: "MFA_TOTP_REQUIRED".to_string(),
        };
        assert_eq!(translate_error(&err), "未完成二次认证:MFA_TOTP_REQUIRED");
    }

    #[test]
    fn translate_error_en_not_safe() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::NotSafe {
            reason: "WEBAUTHN_REQUIRED".to_string(),
        };
        assert_eq!(
            translate_error(&err),
            "Second factor authentication required: WEBAUTHN_REQUIRED"
        );
    }

    #[test]
    fn translate_error_zh_invalid_state_transition() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::InvalidStateTransition {
            from: "Active".to_string(),
            to: "Closed".to_string(),
        };
        assert_eq!(translate_error(&err), "非法状态转换:Active -> Closed");
    }

    #[test]
    fn translate_error_en_invalid_state_transition() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::InvalidStateTransition {
            from: "Pending".to_string(),
            to: "Active".to_string(),
        };
        assert_eq!(
            translate_error(&err),
            "Invalid state transition: Pending -> Active"
        );
    }

    #[test]
    fn translate_error_zh_sms_rate_limit_exceeded() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::SmsRateLimitExceeded {
            window: "hourly".to_string(),
        };
        assert_eq!(translate_error(&err), "SMS 限速超出: hourly 窗口");
    }

    #[test]
    fn translate_error_en_sms_rate_limit_exceeded() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::SmsRateLimitExceeded {
            window: "daily".to_string(),
        };
        assert_eq!(
            translate_error(&err),
            "SMS rate limit exceeded: daily window"
        );
    }

    #[test]
    fn translate_error_zh_sms_verify_max_attempts() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::SmsVerifyMaxAttempts;
        assert_eq!(translate_error(&err), "SMS 验证码尝试次数超限");
    }

    #[test]
    fn translate_error_en_sms_verify_max_attempts() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::SmsVerifyMaxAttempts;
        assert_eq!(
            translate_error(&err),
            "SMS verification max attempts exceeded"
        );
    }

    #[test]
    fn translate_error_zh_sms_code_not_found() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::SmsCodeNotFound;
        assert_eq!(translate_error(&err), "SMS 验证码不存在");
    }

    #[test]
    fn translate_error_en_sms_code_not_found() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::SmsCodeNotFound;
        assert_eq!(translate_error(&err), "SMS verification code not found");
    }

    #[test]
    fn translate_error_zh_sms_channel_recycled() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::SmsChannelRecycled;
        assert_eq!(translate_error(&err), "SMS 通道已回收");
    }

    #[test]
    fn translate_error_en_sms_channel_recycled() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::SmsChannelRecycled;
        assert_eq!(translate_error(&err), "SMS channel recycled");
    }

    // fallback_display 补充测试

    #[test]
    fn fallback_display_new_variants() {
        let until = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let cases: Vec<(GarrisonError, String)> = vec![
            (
                GarrisonError::TokenRevoked("x".into()),
                "Token revoked: x".to_string(),
            ),
            (
                GarrisonError::FirewallBlocked("x".into()),
                "Firewall blocked: x".to_string(),
            ),
            (
                GarrisonError::DisableService {
                    service: "default".into(),
                    until: Some(until),
                },
                format!("Account disabled: service=default, until={:?}", Some(until)),
            ),
            (
                GarrisonError::DisableService {
                    service: "oidc".into(),
                    until: None,
                },
                "Account disabled: service=oidc, until=None".to_string(),
            ),
            (
                GarrisonError::NotSafe { reason: "r".into() },
                "Second factor authentication required: r".to_string(),
            ),
            (
                GarrisonError::InvalidStateTransition {
                    from: "A".into(),
                    to: "B".into(),
                },
                "Invalid state transition: A -> B".to_string(),
            ),
            (
                GarrisonError::SmsRateLimitExceeded { window: "w".into() },
                "SMS rate limit exceeded: w window".to_string(),
            ),
            (
                GarrisonError::SmsVerifyMaxAttempts,
                "SMS verification max attempts exceeded".to_string(),
            ),
            (
                GarrisonError::SmsCodeNotFound,
                "SMS verification code not found".to_string(),
            ),
            (
                GarrisonError::SmsChannelRecycled,
                "SMS channel recycled".to_string(),
            ),
        ];
        for (err, expected) in cases {
            assert_eq!(fallback_display(&err), expected, "mismatch for {:?}", err);
        }
    }

    #[test]
    fn error_to_key_args_all_variants() {
        let until = chrono::Utc::now();
        #[cfg_attr(
            not(any(feature = "email-verification", feature = "credit-metering")),
            allow(unused_mut)
        )]
        let mut cases: Vec<GarrisonError> = vec![
            GarrisonError::NotLogin("a".into()),
            GarrisonError::NotPermission("a".into()),
            GarrisonError::NotRole("a".into()),
            GarrisonError::InvalidToken("a".into()),
            GarrisonError::TokenRevoked("a".into()),
            GarrisonError::ExpiredToken("a".into()),
            GarrisonError::Dao("a".into()),
            GarrisonError::Config("a".into()),
            GarrisonError::Internal("a".into()),
            GarrisonError::Session("a".into()),
            GarrisonError::Annotation("a".into()),
            GarrisonError::Context("a".into()),
            GarrisonError::OAuth2("a".into()),
            GarrisonError::Network("a".into()),
            GarrisonError::InvalidResponse("a".into()),
            GarrisonError::InvalidParam("a".into()),
            GarrisonError::NotImplemented("a".into()),
            GarrisonError::FirewallBlocked("a".into()),
            GarrisonError::DisableService {
                service: "s".into(),
                until: Some(until),
            },
            GarrisonError::NotSafe { reason: "r".into() },
            GarrisonError::InvalidStateTransition {
                from: "f".into(),
                to: "t".into(),
            },
            GarrisonError::SmsRateLimitExceeded { window: "w".into() },
            GarrisonError::SmsVerifyMaxAttempts,
            GarrisonError::SmsCodeNotFound,
            GarrisonError::SmsChannelRecycled,
            GarrisonError::RateLimited {
                retry_after_secs: 30,
            },
            GarrisonError::Exception(Box::new(GarrisonException::new(-1, "msg"))),
        ];
        #[cfg(feature = "email-verification")]
        cases.extend([
            GarrisonError::EmailRateLimitExceeded { window: "w".into() },
            GarrisonError::EmailVerifyMaxAttempts,
            GarrisonError::EmailCodeNotFound,
            GarrisonError::EmailChannelRecycled,
        ]);
        #[cfg(feature = "credit-metering")]
        cases.push(GarrisonError::CreditInsufficient {
            tenant_id: 1,
            requested: 2,
            remaining: 3,
        });

        for err in cases {
            // 仅验证不 panic 且返回非空 key
            let (key, _args) = error_to_key_args(&err);
            assert!(!key.is_empty(), "key 不应为空: {:?}", err);
        }
    }

    /// 限流 / 邮箱 / Credit 变体的 FTL 键命中且参数透传(key 未被误用为展示文案)。
    #[test]
    #[cfg_attr(
        not(any(feature = "email-verification", feature = "credit-metering")),
        allow(unused_mut)
    )]
    fn error_to_key_args_feature_variants_hit_ftl_keys() {
        let _guard = set_locale(GarrisonLocale::En);
        let mut cases: Vec<(GarrisonError, &str)> = vec![(
            GarrisonError::RateLimited {
                retry_after_secs: 30,
            },
            "rate-limited",
        )];
        #[cfg(feature = "email-verification")]
        cases.extend([
            (
                GarrisonError::EmailRateLimitExceeded {
                    window: "hourly".into(),
                },
                "email-rate-limit-exceeded",
            ),
            (
                GarrisonError::EmailVerifyMaxAttempts,
                "email-verify-max-attempts",
            ),
            (GarrisonError::EmailCodeNotFound, "email-code-not-found"),
            (
                GarrisonError::EmailChannelRecycled,
                "email-channel-recycled",
            ),
        ]);
        #[cfg(feature = "credit-metering")]
        cases.push((
            GarrisonError::CreditInsufficient {
                tenant_id: 1,
                requested: 2,
                remaining: 3,
            },
            "credit-insufficient",
        ));

        for (err, expected_key) in &cases {
            let (key, _args) = error_to_key_args(err);
            assert_eq!(key, *expected_key, "FTL 键失配: {err:?}");
            let translated = translate_error(err);
            assert_ne!(
                translated, *expected_key,
                "应命中 FTL 翻译而非回退 key 本身: {err:?}"
            );
            assert!(!translated.is_empty());
        }
    }

    /// 限流 / 邮箱 / Credit 变体的硬编码英文回退文案(bundle 缺失时的最后防线)。
    #[test]
    fn fallback_display_rate_limited_and_feature_variants() {
        assert_eq!(
            fallback_display(&GarrisonError::RateLimited {
                retry_after_secs: 30
            }),
            "Rate limited"
        );
        #[cfg(feature = "email-verification")]
        {
            assert_eq!(
                fallback_display(&GarrisonError::EmailRateLimitExceeded {
                    window: "hourly".into()
                }),
                "Email rate limit exceeded: hourly window"
            );
            assert_eq!(
                fallback_display(&GarrisonError::EmailVerifyMaxAttempts),
                "Email verification max attempts exceeded"
            );
            assert_eq!(
                fallback_display(&GarrisonError::EmailCodeNotFound),
                "Email verification code not found"
            );
            assert_eq!(
                fallback_display(&GarrisonError::EmailChannelRecycled),
                "Email channel recycled"
            );
        }
        #[cfg(feature = "credit-metering")]
        assert_eq!(
            fallback_display(&GarrisonError::CreditInsufficient {
                tenant_id: 1,
                requested: 2,
                remaining: 3
            }),
            "Credit insufficient: tenant=1, requested=2, remaining=3"
        );
    }

    // InvalidResponse 变体 i18n 测试(上游响应解析失败专用错误类型)

    #[test]
    fn translate_error_zh_invalid_response() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let err = GarrisonError::InvalidResponse("JSON 解析失败".to_string());
        assert_eq!(translate_error(&err), "上游响应无效: JSON 解析失败");
    }

    #[test]
    fn translate_error_en_invalid_response() {
        let _guard = set_locale(GarrisonLocale::En);
        let err = GarrisonError::InvalidResponse("missing access_token field".to_string());
        assert_eq!(
            translate_error(&err),
            "Invalid upstream response: missing access_token field"
        );
    }

    #[test]
    fn fallback_display_invalid_response() {
        let err = GarrisonError::InvalidResponse("parse error".into());
        assert_eq!(
            fallback_display(&err),
            "Invalid upstream response: parse error"
        );
    }

    #[test]
    fn lookup_en_returns_registered_entry() {
        ensure_registered();
        assert!(
            lookup("en", "not-login", &[("detail", "x")]).is_some(),
            "en 注册后 lookup 应命中"
        );
    }

    // translate_detail 测试

    #[test]
    fn translate_detail_known_key_returns_translation() {
        let _guard = set_locale(GarrisonLocale::En);
        let result = translate_detail("not-login", &[("detail", "test")]);
        assert!(result.contains("test"), "应包含参数值: {}", result);
    }

    #[test]
    fn translate_detail_unknown_key_returns_key() {
        let _guard = set_locale(GarrisonLocale::En);
        let result = translate_detail("nonexistent-key-xyz", &[]);
        assert_eq!(result, "nonexistent-key-xyz");
    }

    #[test]
    fn translate_detail_known_key_no_args() {
        let _guard = set_locale(GarrisonLocale::Zh);
        let result = translate_detail("sms-verify-max-attempts", &[]);
        assert!(!result.is_empty());
        assert_ne!(result, "sms-verify-max-attempts", "应返回翻译而非 key 本身");
    }

    // ICU4X 增强层测试(feature = "i18n-icu")

    #[cfg(feature = "i18n-icu")]
    #[test]
    fn icu_plural_category_en_one() {
        let _guard = set_locale(GarrisonLocale::En);
        let cat = icu_enhanced::plural_category(1);
        assert_eq!(cat, "one");
    }

    #[cfg(feature = "i18n-icu")]
    #[test]
    fn icu_plural_category_en_other() {
        let _guard = set_locale(GarrisonLocale::En);
        let cat = icu_enhanced::plural_category(2);
        assert_eq!(cat, "other");
    }

    #[cfg(feature = "i18n-icu")]
    #[test]
    fn icu_format_number_en() {
        let _guard = set_locale(GarrisonLocale::En);
        let formatted = icu_enhanced::format_number_locale(1_000_000);
        assert!(formatted.contains("1"), "应包含数字 1: {}", formatted);
    }

    #[cfg(feature = "i18n-icu")]
    #[test]
    fn icu_format_datetime_en() {
        let _guard = set_locale(GarrisonLocale::En);
        let dt = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let formatted = icu_enhanced::format_datetime_locale(&dt);
        assert!(!formatted.is_empty(), "日期格式化不应为空");
        assert!(formatted.contains("2026"), "应包含年份: {}", formatted);
    }
    /// 含数字的键(argon2 / l1 / jwt-ec-sec1 等)必须可解析:解析器若拒绝数字,
    /// FTL 词条永不生效、用户只能看到原始 key(回归锚定 22 个不可达键的修复)。
    #[test]
    fn parse_keyed_detail_accepts_digit_keys() {
        let (key, args) = parse_keyed_detail("config-password-hash-argon2-param-invalid::t_cost")
            .expect("含数字键应被解析");
        assert_eq!(key, "config-password-hash-argon2-param-invalid");
        assert_eq!(args, [("arg0", "t_cost".to_string())]);
        assert!(
            parse_keyed_detail("cache-l1-init::").is_some(),
            "纯数字段也应可解析"
        );
    }

    /// 守卫本意不变:中文串与含空格/大写的普通句子不得被误判为 key。
    #[test]
    fn parse_keyed_detail_still_rejects_prose() {
        assert!(parse_keyed_detail("这是一句中文::包含分隔符").is_none());
        assert!(parse_keyed_detail("not a key::with spaces").is_none());
        assert!(parse_keyed_detail("MixedCase::value").is_none());
    }

    /// 端到端:含数字键经 translate_detail 渲染 FTL 文案而非回退原始 key。
    #[test]
    fn translate_detail_renders_digit_key_from_catalog() {
        let rendered = translate_detail(
            "config-password-hash-argon2-param-invalid",
            &[("arg0", "t_cost")],
        );
        assert!(rendered.contains("t_cost"), "应渲染参数: {rendered}");
        assert!(
            !rendered.contains("config-password-hash"),
            "不得回退原始 key: {rendered}"
        );
    }
}