inklog 0.3.0-rc.1

Enterprise-grade Rust logging infrastructure
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! # 数据掩码模块
//!
//! 提供敏感数据(PII)的自动检测和脱敏功能,保护日志中的隐私信息。
//!
//! ## 概述
//!
//! `DataMasker` 结构体提供日志消息和 JSON 结构中敏感数据的检测和脱敏功能。
//! 它结合模式匹配和字段名检测来识别敏感信息。
//!
//! ## 功能特性
//!
//! - **基于模式的脱敏**:通过正则表达式模式检测敏感数据(邮箱、电话等)
//! - **字段名检测**:通过字段名识别敏感字段(password、api_key 等)
//! - **嵌套结构支持**:递归处理嵌套的 JSON 对象和数组
//! - **自定义规则**:支持多个脱敏规则,可配置模式
//!
//! ## 敏感字段检测
//!
//! 以下字段名模式会自动检测为敏感字段:
//! - **认证信息**:`password`, `token`, `secret`, `credential`, `auth`
//! - **API 密钥**:`api_key`, `api_secret`, `access_key`, `secret_key`
//! - **加密密钥**:`encryption_key`, `decryption_key`, `private_key`
//! - **OAuth**:`oauth`, `oauth_token`, `bearer_token`, `jwt`
//! - **AWS 凭据**:`aws_secret`, `aws_key`, `aws_credentials`
//! - **支付信息**:`credit_card`, `card_number`, `cvv`, `ssn`
//!
//! ## 基于模式的检测
//!
//! 除了字段名,以下模式也会被检测:
//! - **邮箱地址**(部分脱敏:`***@***.***`)
//! - **电话号码**(显示后4位:`138****5678`)
//! - **身份证号**(部分脱敏)
//! - **银行卡号**(部分脱敏)
//! - **JWT 令牌**
//! - **AWS 访问密钥**
//! - **通用 API 密钥**
//!
//! ## 使用示例
//!
//! ```rust
//! use inklog::masking::DataMasker;
//!
//! let masker = DataMasker::new();
//!
//! // 脱敏日志消息
//! let message = "User login: email=test@example.com";
//! let masked = masker.mask(message);
//! // 邮箱脱敏格式: **@**.***
//! assert!(masked.contains("**@**.***"));
//! assert!(!masked.contains("test@example.com"));
//!
//! // 检查字段名是否为敏感字段
//! assert!(DataMasker::is_sensitive_field("password"));
//! assert!(DataMasker::is_sensitive_field("api_key"));
//! assert!(!DataMasker::is_sensitive_field("username"));
//! ```
//!
//! ## 性能考虑
//!
//! - 预编译正则表达式以提高性能
//! - 批量处理时使用缓存
//! - 支持禁用特定检测规则以减少开销

use regex::Regex;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

use crate::error::InklogError;

/// Word-boundary regex patterns for sensitive field detection.
/// Uses \b (word boundary) to avoid false positives like "cakey" matching "key".
static SENSITIVE_FIELD_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    vec![
        // Authentication patterns
        Regex::new(r"(?i)\b(password|passwd|pwd)\b").unwrap(),
        // token/bearer/auth: preceded by a non-word separator (space, -, _, etc.) or at start
        // This excludes cases like "cakey" where 'token' is inside a word.
        // Covers: "token" (start), "api_token" (underscore), "bearer_token", "auth_token"
        // The (?:[^a-zA-Z0-9_])? makes the preceding char optional (for start-of-string case)
        Regex::new(r"(?i)(?:[^a-zA-Z0-9_])?(token|bearer|auth)\b").unwrap(),
        Regex::new(r"(?i)\b(secret|credential)\b").unwrap(),
        // Key patterns
        Regex::new(r"(?i)\b(api[_-]?key|apikey|api[_-]?secret)\b").unwrap(),
        Regex::new(r"(?i)\b(access[_-]?key|access[_-]?key[_-]?id)\b").unwrap(),
        Regex::new(r"(?i)\b(secret[_-]?key|private[_-]?key|public[_-]?key)\b").unwrap(),
        Regex::new(r"(?i)\b(encryption[_-]?key|decryption[_-]?key|master[_-]?key)\b").unwrap(),
        Regex::new(r"(?i)\b(session[_-]?key|session[_-]?id|session[_-]?token)\b").unwrap(),
        // OAuth patterns
        Regex::new(r"(?i)\b(oauth|oauth[_-]?token|oauth[_-]?secret)\b").unwrap(),
        Regex::new(r"(?i)\b(jwt(_[a-zA-Z0-9]+)?|bearer[_-]?token)\b").unwrap(),
        // AWS patterns
        Regex::new(r"(?i)\b(aws[_-]?secret|aws[_-]?key|aws[_-]?token|aws[_-]?credentials)\b").unwrap(),
        // Database patterns
        Regex::new(r"(?i)\b(database[_-]?url|db[_-]?password|db[_-]?user|connection[_-]?string)\b").unwrap(),
        // Payment patterns
        Regex::new(r"(?i)\b(credit[_-]?card|card[_-]?number|cvv|ssn|social[_-]?security)\b").unwrap(),
        // Client patterns
        Regex::new(r"(?i)\b(client[_-]?secret|client[_-]?id)\b").unwrap(),
        // Other sensitive patterns
        Regex::new(r"(?i)\b(refresh[_-]?token|pin|pin[_-]?code|two[_-]?factor|totp|backup[_-]?code|recovery[_-]?code)\b").unwrap(),
    ]
});

/// Data masking utility for sensitive information protection.
///
/// The `DataMasker` struct provides functionality to detect and mask sensitive
/// data in log messages and JSON structures. It uses a combination of pattern
/// matching and field name detection to identify sensitive information.
///
/// # Features
/// - **Pattern-based masking**: Detects sensitive data by regex patterns (emails, phones, etc.)
/// - **Field name detection**: Identifies sensitive fields by name (password, api_key, etc.)
/// - **Nested structure support**: Recursively processes nested JSON objects and arrays
/// - **Customizable rules**: Supports multiple mask rules with configurable patterns
///
/// # Sensitive Field Detection
///
/// The following field name patterns are automatically detected as sensitive:
/// - Authentication: `password`, `token`, `secret`, `credential`, `auth`
/// - API Keys: `api_key`, `api_secret`, `access_key`, `secret_key`
/// - Encryption: `encryption_key`, `decryption_key`, `private_key`
/// - OAuth: `oauth`, `oauth_token`, `bearer_token`, `jwt`
/// - AWS: `aws_secret`, `aws_key`, `aws_credentials`
/// - Payment: `credit_card`, `card_number`, `cvv`, `ssn`
///
/// # Pattern-based Detection
///
/// In addition to field names, the following patterns are detected:
/// - Email addresses (partial masking: `***@***.***`)
/// - Phone numbers (last 4 digits shown: `138****5678`)
/// - ID card numbers (partial masking)
/// - Bank card numbers (partial masking)
/// - JWT tokens
/// - AWS access keys
/// - Generic API keys
///
/// # Example
///
/// ```ignore
/// use inklog::masking::DataMasker;
///
/// let masker = DataMasker::new();
///
/// // Mask by pattern
/// let mut email = serde_json::json!("user@example.com");
/// masker.mask_value(&mut email);
/// assert_eq!(email, serde_json::json!("***@***.***"));
///
/// // Detect sensitive fields
/// assert!(DataMasker::is_sensitive_field("password"));
/// assert!(DataMasker::is_sensitive_field("api_key"));
/// assert!(!DataMasker::is_sensitive_field("message"));
/// ```
///
/// # Thread Safety
///
/// `DataMasker` is immutable and can be safely shared between threads.
#[derive(Debug, Clone, Default)]
pub struct DataMasker {
    /// Regex-based rules (includes all rules when `fast-masking` is off).
    rules: Vec<MaskRule>,
    /// Aho-Corasick fast path for literal-pattern rules.
    #[cfg(feature = "fast-masking")]
    ac_masker: Option<super::masking_ac::AcMasker>,
}

/// Type alias for the custom apply function used in masking rules.
type ApplyFn = Arc<dyn Fn(&Regex, &str, &str) -> String + Send + Sync>;

/// A masking rule that defines how to detect and replace sensitive data patterns.
///
/// # Fields
/// - `name`: Unique identifier for the rule
/// - `pattern`: Compiled regex pattern for detection
/// - `replacement`: Replacement string (supports capture group references like `${1}`)
/// - `priority`: Execution order (lower values execute first)
/// - `enabled`: Whether this rule is active
/// - `apply_fn`: Custom application function for complex masking logic
#[derive(Clone)]
pub struct MaskRule {
    name: String,
    pattern: Regex,
    replacement: String,
    priority: i32,
    enabled: bool,
    apply_fn: ApplyFn,
    /// When true, the pattern is a literal string (eligible for AC acceleration).
    is_literal: bool,
}

impl std::fmt::Debug for MaskRule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MaskRule")
            .field("name", &self.name)
            .field("pattern", &self.pattern.as_str())
            .field("replacement", &self.replacement)
            .field("priority", &self.priority)
            .field("enabled", &self.enabled)
            .field("apply_fn", &"<fn>")
            .field("is_literal", &self.is_literal)
            .finish()
    }
}

impl DataMasker {
    pub fn new() -> Self {
        let mut rules = vec![
            MaskRule::new_email_rule(),
            MaskRule::new_phone_rule(),
            MaskRule::new_id_card_rule(),
            MaskRule::new_bank_card_rule(),
            MaskRule::new_api_key_rule(),
            MaskRule::new_aws_key_rule(),
            MaskRule::new_jwt_rule(),
            MaskRule::new_generic_secret_rule(),
            // High-priority
            MaskRule::new_international_phone_rule(),
            MaskRule::new_credit_card_rule(),
            MaskRule::new_ipv4_rule(),
            MaskRule::new_ipv6_rule(),
            MaskRule::new_mac_address_rule(),
            // Medium-priority
            MaskRule::new_passport_rule(),
            MaskRule::new_ssn_rule(),
            MaskRule::new_db_connection_rule(),
            // Low-priority
            MaskRule::new_github_token_rule(),
            MaskRule::new_slack_token_rule(),
            MaskRule::new_stripe_key_rule(),
            MaskRule::new_google_api_key_rule(),
            MaskRule::new_private_key_rule(),
        ];
        rules.sort_by_key(|r| r.priority());
        Self {
            rules,
            #[cfg(feature = "fast-masking")]
            ac_masker: None,
        }
    }

    /// 检查字段名是否为敏感字段(大小写不敏感,使用词边界正则避免误判)
    ///
    /// 例如:
    /// - `"cakey"` 不会匹配 `"key"`(避免误判)
    /// - `"polygon"` 不会匹配 `"gon"`(避免误判)
    /// - `"password"` 会匹配(正确检测)
    pub fn is_sensitive_field(field_name: &str) -> bool {
        SENSITIVE_FIELD_PATTERNS
            .iter()
            .any(|pattern| pattern.is_match(field_name))
    }

    pub fn mask(&self, text: &str) -> String {
        #[cfg(feature = "fast-masking")]
        let mut result = {
            if let Some(ref ac) = self.ac_masker {
                ac.mask_fast(text)
            } else {
                text.to_string()
            }
        };
        #[cfg(not(feature = "fast-masking"))]
        let mut result = text.to_string();

        for rule in &self.rules {
            if rule.is_enabled() {
                result = rule.apply(&result);
            }
        }
        result
    }

    pub fn mask_value(&self, value: &mut Value) {
        match value {
            Value::String(s) => {
                *s = self.mask(s);
            }
            Value::Array(arr) => {
                for item in arr {
                    self.mask_value(item);
                }
            }
            Value::Object(map) => {
                for (k, v) in map.iter_mut() {
                    if Self::is_sensitive_field(k) {
                        *v = Value::String("***MASKED***".to_string());
                    } else {
                        self.mask_value(v);
                    }
                }
            }
            _ => {}
        }
    }

    pub fn mask_hashmap(&self, map: &mut HashMap<String, Value>) {
        for (k, v) in map.iter_mut() {
            if Self::is_sensitive_field(k) {
                *v = Value::String("***MASKED***".to_string());
            } else {
                self.mask_value(v);
            }
        }
    }

    /// Consumes the `DataMasker` and returns the inner rules vector.
    pub fn into_rules(self) -> Vec<MaskRule> {
        self.rules
    }

    /// Creates a new [`DataMaskerBuilder`] for assembling a custom masker.
    pub fn builder() -> DataMaskerBuilder {
        DataMaskerBuilder::new()
    }
}

/// Builder for assembling a [`DataMasker`] with custom rule configurations.
///
/// # Example
///
/// ```rust
/// use inklog::DataMasker;
///
/// let masker = DataMasker::builder()
///     .disable_builtin("email")
///     .build();
/// ```
pub struct DataMaskerBuilder {
    extra_rules: Vec<MaskRule>,
    disabled_builtins: Vec<String>,
    use_builtins: bool,
    custom_registry: Option<super::masking_registry::MaskRuleRegistry>,
}

impl DataMaskerBuilder {
    fn new() -> Self {
        Self {
            extra_rules: Vec::new(),
            disabled_builtins: Vec::new(),
            use_builtins: true,
            custom_registry: None,
        }
    }

    /// Add a custom rule to the masker.
    pub fn add_rule(mut self, rule: MaskRule) -> Self {
        self.extra_rules.push(rule);
        self
    }

    /// Use a custom [`MaskRuleRegistry`] as the rule source instead of builtins.
    ///
    /// When set, the registry's rules replace the default built-in rules.
    /// `add_rule()` and `disable_builtin()` still apply on top.
    pub fn with_registry(mut self, registry: super::masking_registry::MaskRuleRegistry) -> Self {
        self.custom_registry = Some(registry);
        self.use_builtins = false;
        self
    }

    /// Disable a built-in rule by name.
    pub fn disable_builtin(mut self, name: &str) -> Self {
        self.disabled_builtins.push(name.to_string());
        self
    }

    /// Build the [`DataMasker`] with all configured rules sorted by priority.
    ///
    /// When the `fast-masking` feature is enabled, literal-pattern rules are
    /// extracted into an [`AcMasker`](super::masking_ac::AcMasker) for single-pass
    /// acceleration; remaining regex rules stay in the sequential path.
    pub fn build(self) -> DataMasker {
        let mut rules = if let Some(registry) = self.custom_registry {
            registry.active_rules().into_iter().cloned().collect()
        } else if self.use_builtins {
            DataMasker::new().into_rules()
        } else {
            Vec::new()
        };

        // Remove disabled builtins
        for name in &self.disabled_builtins {
            rules.retain(|r| r.name() != name.as_str());
        }

        // Add extra rules
        rules.extend(self.extra_rules);

        // Sort by priority
        rules.sort_by_key(|r| r.priority());

        #[cfg(feature = "fast-masking")]
        {
            // Partition: literal rules → AC, regex rules → sequential
            let (literal_rules, regex_rules): (Vec<_>, Vec<_>) = rules
                .into_iter()
                .partition(|r| r.is_literal() && r.is_enabled());

            let ac_masker = if !literal_rules.is_empty() {
                let patterns: Vec<String> = literal_rules
                    .iter()
                    .map(|r| r.pattern.as_str().to_string())
                    .collect();
                let replacements: Vec<String> = literal_rules
                    .iter()
                    .map(|r| r.replacement.clone())
                    .collect();
                super::masking_ac::AcMasker::new(patterns, replacements)
            } else {
                None
            };

            DataMasker {
                rules: regex_rules,
                ac_masker,
            }
        }

        #[cfg(not(feature = "fast-masking"))]
        DataMasker { rules }
    }
}

use std::sync::LazyLock;

/// Pre-compiled regex patterns for better performance
static EMAIL_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+").expect("Invalid email regex"));

static PHONE_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b1[3-9]\d{9}\b").expect("Invalid phone regex"));

static ID_CARD_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b(\d{6})(\d{8})(\d{3}[\dX])\b").expect("Invalid ID card regex"));

static BANK_CARD_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d{4})(\d{5,11})(\d{4})").expect("Invalid bank card regex"));

/// API Key 模式 - 匹配常见的 API key 格式
static API_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(api[_-]?key[^\s:=]*\s*[=:]\s*[a-zA-Z0-9_-]{20,})")
        .expect("Invalid API key regex")
});

/// AWS Access Key 模式 - 匹配 AKIA 开头的 AWS 密钥
static AWS_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}").expect("Invalid AWS key regex")
});

/// JWT Token 模式 - 匹配 JWT 格式
static JWT_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*")
        .expect("Invalid JWT regex")
});

/// 通用密钥/密码模式 - 匹配 key=value 或 "key": "value" 中的敏感值
static GENERIC_SECRET_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)([^\s:=]*(?:token|secret|key|password|passwd|pwd|credential)s?[^\s:=]*\s*[=:]\s*)([a-zA-Z0-9_\-\+]{16,})")
        .expect("Invalid generic secret regex")
});

// === High-priority rules (compliance) ===

/// International phone (E.164 format)
static INTERNATIONAL_PHONE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\+(\d{1,3})[\s.-]?(\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?)(\d{2,4})")
        .expect("Invalid international phone regex")
});

/// Credit card (major card networks)
static CREDIT_CARD_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|35[0-9]{14})\b")
        .expect("Invalid credit card regex")
});

/// IPv4 address
static IPV4_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b")
        .expect("Invalid IPv4 regex")
});

/// IPv6 address
static IPV6_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{1,4}\b").expect("Invalid IPv6 regex")
});

/// MAC address
static MAC_ADDRESS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b").expect("Invalid MAC address regex")
});

// === Medium-priority rules (regional identity) ===

/// Passport number (Chinese international passport format)
static PASSPORT_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b[EeGg][A-Za-z0-9]{8}\b").expect("Invalid passport regex"));

/// US Social Security Number
static SSN_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b\d{3}-\d{2}-\d{4}\b").expect("Invalid SSN regex"));

/// Database connection string (password in URI)
static DB_CONNECTION_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)((?:postgres|mysql|mongodb|redis|amqp)://[^:\s]+:)([^@]+)(@\S+)")
        .expect("Invalid DB connection regex")
});

// === Low-priority rules (third-party tokens) ===

/// GitHub personal access token
static GITHUB_TOKEN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(?:ghp|github_pat)_[A-Za-z0-9_]{36,}\b").expect("Invalid GitHub token regex")
});

/// Slack token
static SLACK_TOKEN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"xox[bpas]-[0-9]{10,13}-[0-9a-zA-Z-]+").expect("Invalid Slack token regex")
});

/// Stripe API key
static STRIPE_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?:sk|pk)_(?:live|test)_[0-9a-zA-Z]{24,}").expect("Invalid Stripe key regex")
});

/// Google API key
static GOOGLE_API_KEY_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"AIza[0-9A-Za-z_-]{35}").expect("Invalid Google API key regex"));

/// Private key PEM block
static PRIVATE_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"-----BEGIN[A-Z ]*PRIVATE KEY-----[\s\S]*?-----END[A-Z ]*PRIVATE KEY-----")
        .expect("Invalid private key regex")
});

impl MaskRule {
    fn new_email_rule() -> Self {
        Self::build_from_regex("email", EMAIL_REGEX.clone(), "**@**.***", 100, None)
    }

    fn new_phone_rule() -> Self {
        Self::build_from_regex("phone", PHONE_REGEX.clone(), "***-****-****", 100, None)
    }

    fn new_id_card_rule() -> Self {
        Self::build_from_regex(
            "id_card",
            ID_CARD_REGEX.clone(),
            "MASK_ID_CARD",
            100,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex.replace(text, "******$3").to_string()
            })),
        )
    }

    fn new_bank_card_rule() -> Self {
        Self::build_from_regex(
            "bank_card",
            BANK_CARD_REGEX.clone(),
            "MASK_BANK_CARD",
            100,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let matched = caps.get(0).unwrap().as_str();
                        if matched.len() >= 12 {
                            let last_four = &matched[matched.len() - 4..];
                            format!("****-****-****-{}", last_four)
                        } else {
                            matched.to_string()
                        }
                    })
                    .to_string()
            })),
        )
    }

    fn new_api_key_rule() -> Self {
        Self::build_from_regex(
            "api_key",
            API_KEY_REGEX.clone(),
            "${1}***REDACTED***",
            100,
            None,
        )
    }

    fn new_aws_key_rule() -> Self {
        Self::build_from_regex(
            "aws_key",
            AWS_KEY_REGEX.clone(),
            "***REDACTED***",
            100,
            None,
        )
    }

    fn new_jwt_rule() -> Self {
        Self::build_from_regex("jwt", JWT_REGEX.clone(), "***REDACTED_JWT***", 100, None)
    }

    fn new_generic_secret_rule() -> Self {
        Self::build_from_regex(
            "generic_secret",
            GENERIC_SECRET_REGEX.clone(),
            "${1}***REDACTED***",
            100,
            None,
        )
    }

    // === Internal helper for pre-compiled rules ===

    /// Build a rule from a pre-compiled Regex, avoiding re-compilation.
    fn build_from_regex(
        name: &str,
        regex: Regex,
        replacement: &str,
        priority: i32,
        apply_fn: Option<ApplyFn>,
    ) -> Self {
        MaskRule {
            name: name.to_string(),
            pattern: regex,
            replacement: replacement.to_string(),
            priority,
            enabled: true,
            apply_fn: apply_fn.unwrap_or_else(|| {
                Arc::new(|regex: &Regex, text: &str, replacement: &str| {
                    regex.replace(text, replacement).to_string()
                })
            }),
            is_literal: false,
        }
    }

    // === High-priority rules ===

    fn new_international_phone_rule() -> Self {
        Self::build_from_regex(
            "international_phone",
            INTERNATIONAL_PHONE_REGEX.clone(),
            "+${1}-***-***-${3}",
            10,
            None,
        )
    }

    fn new_credit_card_rule() -> Self {
        Self::build_from_regex(
            "credit_card",
            CREDIT_CARD_REGEX.clone(),
            "***REDACTED_CC***",
            15,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let number = caps.get(0).unwrap().as_str();
                        let digits: Vec<u32> =
                            number.chars().filter_map(|c| c.to_digit(10)).collect();
                        let mut sum = 0u32;
                        let mut alternate = false;
                        for &d in digits.iter().rev() {
                            if alternate {
                                let doubled = d * 2;
                                sum += if doubled > 9 { doubled - 9 } else { doubled };
                            } else {
                                sum += d;
                            }
                            alternate = !alternate;
                        }
                        if !sum.is_multiple_of(10) {
                            return number.to_string();
                        }
                        let last4 = &number[number.len() - 4..];
                        if number.starts_with('3') {
                            format!("****-******-{}", last4)
                        } else {
                            format!("****-****-****-{}", last4)
                        }
                    })
                    .to_string()
            })),
        )
    }

    fn new_ipv4_rule() -> Self {
        Self::build_from_regex(
            "ipv4",
            IPV4_REGEX.clone(),
            "***.***.***.XXX",
            20,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let ip = caps.get(0).unwrap().as_str();
                        if let Some(pos) = ip.rfind('.') {
                            format!("***.***.***.{}", &ip[pos + 1..])
                        } else {
                            "***.***.***.***".to_string()
                        }
                    })
                    .to_string()
            })),
        )
    }

    fn new_ipv6_rule() -> Self {
        Self::build_from_regex(
            "ipv6",
            IPV6_REGEX.clone(),
            "****:****:****:XXXX",
            21,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let ip = caps.get(0).unwrap().as_str();
                        if let Some(pos) = ip.rfind(':') {
                            let last_group = &ip[pos + 1..];
                            let prefix_count = ip.matches(':').count();
                            let mut result = "****".to_string();
                            for _ in 1..prefix_count {
                                result.push_str(":****");
                            }
                            result.push(':');
                            result.push_str(last_group);
                            result
                        } else {
                            ip.to_string()
                        }
                    })
                    .to_string()
            })),
        )
    }

    fn new_mac_address_rule() -> Self {
        Self::build_from_regex(
            "mac_address",
            MAC_ADDRESS_REGEX.clone(),
            "XX:**:**:**:**:XX",
            19,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let mac = caps.get(0).unwrap().as_str();
                        let sep = if mac.contains(':') { ':' } else { '-' };
                        let parts: Vec<&str> = mac.split(sep).collect();
                        if parts.len() == 6 {
                            format!(
                                "{}{}{}{}{}{}{}{}{}{}{}",
                                parts[0], sep, "**", sep, "**", sep, "**", sep, "**", sep, parts[5]
                            )
                        } else {
                            mac.to_string()
                        }
                    })
                    .to_string()
            })),
        )
    }

    // === Medium-priority rules ===

    fn new_passport_rule() -> Self {
        Self::build_from_regex(
            "passport",
            PASSPORT_REGEX.clone(),
            "******XX",
            30,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let passport = caps.get(0).unwrap().as_str();
                        let first = &passport[..1];
                        let last2 = &passport[passport.len() - 2..];
                        format!("{}******{}", first, last2)
                    })
                    .to_string()
            })),
        )
    }

    fn new_ssn_rule() -> Self {
        Self::build_from_regex(
            "ssn",
            SSN_REGEX.clone(),
            "***-**-XXXX",
            35,
            Some(Arc::new(|regex: &Regex, text: &str, _replacement: &str| {
                regex
                    .replace_all(text, |caps: &regex::Captures| {
                        let ssn = caps.get(0).unwrap().as_str();
                        let last4 = &ssn[ssn.len() - 4..];
                        format!("***-**-{}", last4)
                    })
                    .to_string()
            })),
        )
    }

    fn new_db_connection_rule() -> Self {
        Self::build_from_regex(
            "db_connection",
            DB_CONNECTION_REGEX.clone(),
            "${1}***${3}",
            40,
            None,
        )
    }

    // === Low-priority rules ===

    fn new_github_token_rule() -> Self {
        Self::build_from_regex(
            "github_token",
            GITHUB_TOKEN_REGEX.clone(),
            "***REDACTED_GITHUB***",
            50,
            None,
        )
    }

    fn new_slack_token_rule() -> Self {
        Self::build_from_regex(
            "slack_token",
            SLACK_TOKEN_REGEX.clone(),
            "***REDACTED_SLACK***",
            51,
            None,
        )
    }

    fn new_stripe_key_rule() -> Self {
        Self::build_from_regex(
            "stripe_key",
            STRIPE_KEY_REGEX.clone(),
            "***REDACTED_STRIPE***",
            52,
            None,
        )
    }

    fn new_google_api_key_rule() -> Self {
        Self::build_from_regex(
            "google_api_key",
            GOOGLE_API_KEY_REGEX.clone(),
            "***REDACTED_GOOGLE***",
            53,
            None,
        )
    }

    fn new_private_key_rule() -> Self {
        Self::build_from_regex(
            "private_key",
            PRIVATE_KEY_REGEX.clone(),
            "***REDACTED_PRIVATE_KEY***",
            54,
            None,
        )
    }

    fn apply(&self, text: &str) -> String {
        (self.apply_fn)(&self.pattern, text, &self.replacement)
    }

    /// Returns the name of this rule.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns whether this rule is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Returns the priority of this rule (lower = earlier).
    pub fn priority(&self) -> i32 {
        self.priority
    }

    /// Sets whether this rule is enabled.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Returns whether this rule uses a literal (fixed-string) pattern.
    pub fn is_literal(&self) -> bool {
        self.is_literal
    }

    /// Creates a new builder for constructing a `MaskRule`.
    pub fn builder(name: &str) -> MaskRuleBuilder {
        MaskRuleBuilder::new(name)
    }
}

/// Builder for constructing [`MaskRule`] instances with a fluent API.
///
/// # Defaults
/// - `priority`: 100
/// - `enabled`: true
/// - `apply_fn`: standard `regex.replace(text, replacement)`
///
/// # Example
///
/// ```rust
/// use inklog::MaskRule;
///
/// let rule = MaskRule::builder("custom_phone")
///     .pattern(r"\b\d{3}-\d{4}\b")
///     .replacement("***-****")
///     .priority(50)
///     .build()
///     .unwrap();
/// ```
pub struct MaskRuleBuilder {
    name: String,
    pattern: Option<String>,
    replacement: String,
    priority: i32,
    enabled: bool,
    apply_fn: Option<ApplyFn>,
    is_literal: bool,
}

impl MaskRuleBuilder {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            pattern: None,
            replacement: String::new(),
            priority: 100,
            enabled: true,
            apply_fn: None,
            is_literal: false,
        }
    }

    /// Sets the regex pattern for this rule.
    pub fn pattern(mut self, regex: &str) -> Self {
        self.pattern = Some(regex.to_string());
        self
    }

    /// Sets the replacement string (supports capture group refs like `${1}`).
    pub fn replacement(mut self, replacement: &str) -> Self {
        self.replacement = replacement.to_string();
        self
    }

    /// Sets the execution priority (lower values execute first).
    pub fn priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    /// Sets whether this rule is enabled.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Sets a custom apply function for complex masking logic.
    pub fn apply_fn(mut self, f: ApplyFn) -> Self {
        self.apply_fn = Some(f);
        self
    }

    /// Mark this rule's pattern as a literal string (eligible for AC acceleration).
    ///
    /// When `true`, the pattern is treated as a fixed string rather than a regex,
    /// enabling the Aho-Corasick fast path when `fast-masking` feature is enabled.
    pub fn literal(mut self, is_literal: bool) -> Self {
        self.is_literal = is_literal;
        self
    }

    /// Builds the [`MaskRule`], compiling the regex pattern.
    ///
    /// # Errors
    /// Returns `Err(InklogError)` if the pattern is missing or an invalid regex.
    pub fn build(self) -> Result<MaskRule, InklogError> {
        let pattern_str = self.pattern.ok_or_else(|| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("name", &self.name);
            InklogError::ConfigError(crate::i18n::tr_args(
                "config-mask_rule_requires_pattern",
                args,
            ))
        })?;
        let regex = Regex::new(&pattern_str).map_err(|e| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("name", &self.name);
            args.set("err", e.to_string());
            InklogError::ConfigError(crate::i18n::tr_args("config-invalid_regex_in_rule", args))
        })?;
        Ok(MaskRule {
            name: self.name,
            pattern: regex,
            replacement: self.replacement,
            priority: self.priority,
            enabled: self.enabled,
            apply_fn: self.apply_fn.unwrap_or_else(|| {
                Arc::new(|regex: &Regex, text: &str, replacement: &str| {
                    regex.replace(text, replacement).to_string()
                })
            }),
            is_literal: self.is_literal,
        })
    }
}

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

    #[test]
    fn test_builder_defaults() {
        let rule = MaskRule::builder("test")
            .pattern(r"\d+")
            .replacement("***")
            .build()
            .unwrap();
        assert_eq!(rule.name(), "test");
        assert_eq!(rule.priority(), 100);
        assert!(rule.is_enabled());
        assert_eq!(rule.apply("abc123def"), "abc***def");
    }

    #[test]
    fn test_builder_custom_values() {
        let rule = MaskRule::builder("custom")
            .pattern(r"\d+")
            .replacement("###")
            .priority(50)
            .enabled(false)
            .build()
            .unwrap();
        assert_eq!(rule.priority(), 50);
        assert!(!rule.is_enabled());
    }

    #[test]
    fn test_builder_custom_apply_fn() {
        let rule = MaskRule::builder("reverse")
            .pattern(r"\w+")
            .replacement("")
            .apply_fn(Arc::new(|_re: &Regex, text: &str, _rep: &str| {
                text.chars().rev().collect()
            }))
            .build()
            .unwrap();
        assert_eq!(rule.apply("hello"), "olleh");
    }

    #[test]
    fn test_builder_missing_pattern() {
        let result = MaskRule::builder("no_pattern").replacement("***").build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_invalid_regex() {
        let result = MaskRule::builder("bad_regex").pattern(r"[invalid").build();
        assert!(result.is_err());
    }
}

pub fn mask_email(email: &str) -> String {
    EMAIL_REGEX.replace(email, "**@**.***").to_string()
}

pub fn mask_phone(phone: &str) -> String {
    PHONE_REGEX.replace(phone, "***-****-****").to_string()
}

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

    #[test]
    fn test_mask_email() {
        let test_cases = vec![
            ("test@example.com", "**@**.***"),
            ("user.name@company.co.uk", "**@**.***"),
            ("admin@localhost", "**@**.***"),
        ];

        for (input, expected) in test_cases {
            let result = mask_email(input);
            assert_eq!(result, expected, "Failed for: {}", input);
        }
    }

    #[test]
    fn test_mask_phone() {
        let test_cases = vec![
            ("13812345678", "***-****-****"),
            ("15987654321", "***-****-****"),
            ("Contact: 18655556666 now", "Contact: ***-****-**** now"),
        ];

        for (input, expected) in test_cases {
            let result = mask_phone(input);
            assert_eq!(result, expected, "Failed for: {}", input);
        }
    }

    #[test]
    fn test_data_masker() {
        let masker = DataMasker::new();

        let test_email = "user@example.com";
        assert_eq!(masker.mask(test_email), "**@**.***");

        let test_phone = "13912345678";
        assert_eq!(masker.mask(test_phone), "***-****-****");

        let mixed = "Contact user at test@example.com, phone: 13812345678";
        let result = masker.mask(mixed);
        assert!(!result.contains("test@example.com"));
        assert!(!result.contains("13812345678"));
    }

    #[test]
    fn test_mask_value() {
        let masker = DataMasker::new();

        let mut value = serde_json::json!({
            "email": "user@example.com",
            "phone": "13712345678",
            "name": "John"
        });

        masker.mask_value(&mut value);

        assert_eq!(value["email"], "**@**.***");
        assert_eq!(value["phone"], "***-****-****");
        assert_eq!(value["name"], "John");
    }

    #[test]
    fn test_mask_nested_value() {
        let masker = DataMasker::new();

        let mut value = serde_json::json!({
            "user": {
                "email": "admin@company.org",
                "contacts": ["test@email.com", "13811112222"]
            }
        });

        masker.mask_value(&mut value);

        let user = &value["user"];
        assert_eq!(user["email"], "**@**.***");

        let contacts = user["contacts"]
            .as_array()
            .expect("contacts should be an array");
        assert_eq!(contacts[0], "**@**.***");
        assert_eq!(contacts[1], "***-****-****");
    }

    #[test]
    fn test_is_sensitive_field_password() {
        assert!(DataMasker::is_sensitive_field("password"));
        assert!(DataMasker::is_sensitive_field("PASSWORD"));
        assert!(DataMasker::is_sensitive_field("Password"));
    }

    #[test]
    fn test_is_sensitive_field_api_key() {
        assert!(DataMasker::is_sensitive_field("api_key"));
        assert!(DataMasker::is_sensitive_field("apiKey"));
        assert!(DataMasker::is_sensitive_field("API_KEY"));
        assert!(DataMasker::is_sensitive_field("api-secret"));
    }

    #[test]
    fn test_is_sensitive_field_jwt() {
        assert!(DataMasker::is_sensitive_field("jwt"));
        assert!(DataMasker::is_sensitive_field("jwt_token"));
        assert!(DataMasker::is_sensitive_field("bearer_token"));
    }

    #[test]
    fn test_is_sensitive_field_aws() {
        assert!(DataMasker::is_sensitive_field("aws_secret"));
        assert!(DataMasker::is_sensitive_field("aws_key"));
        assert!(DataMasker::is_sensitive_field("aws_credentials"));
    }

    #[test]
    fn test_is_sensitive_field_credit_card() {
        assert!(DataMasker::is_sensitive_field("credit_card"));
        assert!(DataMasker::is_sensitive_field("card_number"));
        assert!(DataMasker::is_sensitive_field("cvv"));
    }

    #[test]
    fn test_is_not_sensitive_field() {
        assert!(!DataMasker::is_sensitive_field("username"));
        assert!(!DataMasker::is_sensitive_field("message"));
        assert!(!DataMasker::is_sensitive_field("content"));
        assert!(!DataMasker::is_sensitive_field("title"));
    }

    #[test]
    fn test_mask_email_variations() {
        let test_cases = vec![
            ("test@example.com", "**@**.***"),
            ("user.name@company.co.uk", "**@**.***"),
            ("admin@localhost", "**@**.***"),
            ("user+tag@example.org", "**@**.***"),
            ("user_name@test.io", "**@**.***"),
        ];
        for (input, expected) in test_cases {
            let result = mask_email(input);
            assert_eq!(result, expected, "Failed for: {}", input);
        }
    }

    #[test]
    fn test_mask_phone_variations() {
        let test_cases = vec![
            ("13812345678", "***-****-****"),
            ("15987654321", "***-****-****"),
            ("Contact: 18655556666 now", "Contact: ***-****-**** now"),
        ];
        for (input, expected) in test_cases {
            let result = mask_phone(input);
            assert_eq!(result, expected, "Failed for: {}", input);
        }
    }

    #[test]
    fn test_mask_jwt_token() {
        let masker = DataMasker::new();
        let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
        let result = masker.mask(jwt);
        assert!(result.contains("***REDACTED_JWT***"));
        assert!(!result.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"));
    }

    #[test]
    fn test_mask_aws_key() {
        let masker = DataMasker::new();
        let aws_key = "AKIAIOSFODNN7EXAMPLE";
        let result = masker.mask(aws_key);
        assert!(result.contains("***REDACTED***"));
    }

    #[test]
    fn test_mask_api_key_value() {
        let masker = DataMasker::new();
        let message = "api_key=sk-1234567890abcdefghijABCDEFGH";
        let result = masker.mask(message);
        assert!(result.contains("***REDACTED***"));
        assert!(!result.contains("sk-1234567890abcdefghijABCDEFGH"));
    }

    #[test]
    fn test_mask_password_value() {
        let masker = DataMasker::new();
        // Use a test case that matches the generic secret pattern
        let message = "mypassword=abcdefghijklmnopqrst";
        let result = masker.mask(message);
        // The password should be masked or the message should change
        assert!(result.contains("REDACTED") || !result.contains("abcdefghijklmnopqrst"));
    }

    #[test]
    fn test_mask_database_url() {
        let masker = DataMasker::new();
        let message = "db_url=postgres://user:password123@localhost:5432/mydb";
        let result = masker.mask(message);
        // URL should be masked or password should be hidden
        assert!(result.contains("REDACTED") || !result.contains("password123"));
    }

    #[test]
    fn test_mask_oauth_token() {
        let masker = DataMasker::new();
        let message = "oauth_token=ya29_token_value_here";
        let result = masker.mask(message);
        assert!(result.contains("REDACTED") || !result.contains("token_value"));
    }

    #[test]
    fn test_mask_empty_string() {
        let masker = DataMasker::new();
        let result = masker.mask("");
        assert_eq!(result, "");
    }

    #[test]
    fn test_mask_no_sensitive_data() {
        let masker = DataMasker::new();
        let message = "This is a normal log message without any sensitive data";
        let result = masker.mask(message);
        assert_eq!(result, message);
    }

    #[test]
    fn test_mask_multiple_sensitive_items() {
        let masker = DataMasker::new();
        // Test with simple email and phone that the regex can match
        let message = "Email: test@example.com, Phone: 13812345678";
        let result = masker.mask(message);
        // At least the email should be masked
        assert!(!result.contains("test@example.com"));
    }

    #[test]
    fn test_mask_hashmap() {
        let masker = DataMasker::new();
        let mut map: HashMap<String, Value> = HashMap::new();
        map.insert(
            "email".to_string(),
            Value::String("user@example.com".to_string()),
        );
        map.insert(
            "password".to_string(),
            Value::String("secret123".to_string()),
        );
        map.insert("name".to_string(), Value::String("John".to_string()));

        masker.mask_hashmap(&mut map);

        assert_eq!(map["email"], "**@**.***");
        assert_eq!(map["name"], "John");
    }

    #[test]
    fn test_mask_array_of_objects() {
        let masker = DataMasker::new();
        let mut value = serde_json::json!([
            {"email": "a@b.com", "name": "A"},
            {"email": "c@d.com", "name": "B"}
        ]);

        masker.mask_value(&mut value);

        let arr = value.as_array().unwrap();
        assert_eq!(arr[0]["email"], "**@**.***");
        assert_eq!(arr[1]["email"], "**@**.***");
    }

    #[test]
    fn test_api_key_rule_does_not_panic() {
        let masker = DataMasker::new();
        let input = "api_key=abcdefghijklmnopqrstuvwxyz1234";
        let result = masker.mask(input);
        assert!(result.contains("***REDACTED***"));
    }

    #[test]
    fn test_generic_secret_rule_does_not_panic() {
        let masker = DataMasker::new();
        let input = "my_token=abcdefghijklmnop1234";
        let result = masker.mask(input);
        assert!(result.contains("***REDACTED***"));
    }

    #[test]
    fn test_mask_skips_disabled_rules() {
        // T008: mask() should respect the enabled flag on rules
        let masker = DataMasker::builder().disable_builtin("email").build();
        let input = "user@example.com";
        let result = masker.mask(input);
        // Email should NOT be masked because the rule is disabled
        assert_eq!(result, "user@example.com");
    }

    #[test]
    fn test_mask_value_masks_sensitive_keys() {
        // T009: mask_value should check key names for sensitive fields
        let masker = DataMasker::new();
        let mut value = serde_json::json!({
            "password": "secret123",
            "name": "Alice"
        });
        masker.mask_value(&mut value);
        assert_eq!(value["password"], "***MASKED***");
        assert_eq!(value["name"], "Alice");
    }

    #[test]
    fn test_mask_hashmap_masks_sensitive_keys() {
        // T009: mask_hashmap should check key names for sensitive fields
        let masker = DataMasker::new();
        let mut map = HashMap::new();
        map.insert(
            "api_key".to_string(),
            Value::String("supersecret".to_string()),
        );
        map.insert("user".to_string(), Value::String("bob".to_string()));
        masker.mask_hashmap(&mut map);
        assert_eq!(map["api_key"], Value::String("***MASKED***".to_string()));
        assert_eq!(map["user"], Value::String("bob".to_string()));
    }

    #[test]
    fn test_mask_rule_debug() {
        let rule = MaskRule::builder("test_debug")
            .pattern(r"\d+")
            .replacement("***")
            .build()
            .unwrap();
        let debug_str = format!("{:?}", rule);
        assert!(debug_str.contains("MaskRule"));
        assert!(debug_str.contains("test_debug"));
        assert!(debug_str.contains("<fn>"));
    }

    #[test]
    fn test_builder_add_rule() {
        let custom_rule = MaskRule::builder("custom_upper")
            .pattern(r"[a-z]+")
            .replacement("REPLACED")
            .priority(1)
            .build()
            .unwrap();
        let masker = DataMasker::builder().add_rule(custom_rule).build();
        let result = masker.mask("hello");
        assert!(result.contains("REPLACED"));
    }

    #[test]
    fn test_builder_with_registry() {
        let mut registry =
            crate::support::processing::masking_registry::MaskRuleRegistry::with_builtins();
        registry.set_enabled("email", false);
        let masker = DataMasker::builder().with_registry(registry).build();
        // email rule disabled via registry, so email should not be masked
        let result = masker.mask("user@example.com");
        assert_eq!(result, "user@example.com");
    }

    #[test]
    fn test_mask_credit_card_visa() {
        let masker = DataMasker::new();
        // Valid Visa card (Luhn check passes)
        let result = masker.mask("Card: 4111111111111111");
        assert!(!result.contains("4111111111111111"));
        assert!(result.contains("****-****-****-1111"));
    }

    #[test]
    fn test_mask_credit_card_amex() {
        let masker = DataMasker::new();
        // Valid Amex card (Luhn check passes)
        let result = masker.mask("Card: 378282246310005");
        assert!(!result.contains("378282246310005"));
        assert!(result.contains("****-******-0005"));
    }

    #[test]
    fn test_mask_ipv4() {
        let masker = DataMasker::new();
        let result = masker.mask("Server IP: 192.168.1.100");
        assert!(!result.contains("192.168.1.100"));
        assert!(result.contains("***.***.***.100"));
    }

    #[test]
    fn test_mask_ipv6() {
        let masker = DataMasker::new();
        let result = masker.mask("IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334");
        assert!(!result.contains("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
        assert!(result.contains("7334"));
    }

    #[test]
    fn test_mask_mac_address_colon() {
        let masker = DataMasker::new();
        let result = masker.mask("MAC: AA:BB:CC:DD:EE:FF");
        assert!(!result.contains("AA:BB:CC:DD:EE:FF"));
        assert!(result.contains("AA:**:**:**:**:FF"));
    }

    #[test]
    fn test_mask_mac_address_dash() {
        let masker = DataMasker::new();
        let result = masker.mask("MAC: 00-1A-2B-3C-4D-5E");
        assert!(!result.contains("00-1A-2B-3C-4D-5E"));
        assert!(result.contains("00-**-**-**-**-5E"));
    }

    #[test]
    fn test_mask_passport() {
        let masker = DataMasker::new();
        let result = masker.mask("Passport: E12345678");
        assert!(!result.contains("E12345678"));
        assert!(result.contains("E******78"));
    }

    #[test]
    fn test_mask_ssn() {
        let masker = DataMasker::new();
        let result = masker.mask("SSN: 123-45-6789");
        assert!(!result.contains("123-45-6789"));
        assert!(result.contains("***-**-6789"));
    }

    #[test]
    fn test_mask_credit_card_luhn_failure_still_masked_by_bank_card() {
        // A number matching Visa pattern but failing Luhn check
        // is NOT masked by the credit_card rule, but IS masked by
        // the bank_card rule (which has lower priority = runs after).
        let masker = DataMasker::new();
        // 4111111111111112 fails Luhn (last digit changed from 1 to 2)
        let result = masker.mask("Card: 4111111111111112");
        // bank_card rule masks it with its own pattern
        assert!(!result.contains("4111111111111112"));
    }

    #[test]
    fn test_mask_builder_no_builtins_no_custom() {
        // Use with_registry with an empty (default) registry to test the empty rules path
        let registry = crate::support::processing::masking_registry::MaskRuleRegistry::default();
        let masker = DataMasker::builder().with_registry(registry).build();
        // No rules means nothing gets masked
        let result = masker.mask("user@example.com 4111111111111111");
        assert_eq!(result, "user@example.com 4111111111111111");
    }
}