term-guard 0.0.2

A Rust data validation library providing Deequ-like capabilities without Spark dependencies
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
//! Unified format validation constraint for pattern matching and content validation.
//!
//! This module provides a single flexible constraint that consolidates all pattern-based
//! validation including email, URL, credit card detection, phone numbers, postal codes,
//! UUIDs, IP addresses, JSON, and custom regex patterns.
//!
//! ## Overview
//!
//! The `FormatConstraint` replaces multiple individual constraint types with a single,
//! powerful constraint that supports:
//!
//! - **Built-in formats**: Email, URL, phone, postal codes, UUIDs, IP addresses, JSON, dates
//! - **Custom regex patterns**: Full regex support with security validation
//! - **Rich configuration**: Case sensitivity, trimming, null handling
//! - **Performance optimization**: Pattern caching and compiled regex reuse
//! - **Security**: ReDoS protection and SQL injection prevention
//!
//! ## Quick Start Examples
//!
//! ### Basic Format Validation
//!
//! ```rust
//! use term_guard::constraints::FormatConstraint;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Email validation - require 95% of values to be valid emails
//! let email_check = FormatConstraint::email("email", 0.95)?;
//!
//! // URL validation with localhost support
//! let url_check = FormatConstraint::url("website", 0.90, true)?;
//!
//! // US phone number validation
//! let phone_check = FormatConstraint::phone("phone", 0.98, Some("US".to_string()))?;
//!
//! // UUID validation (any version)
//! let uuid_check = FormatConstraint::uuid("session_id", 1.0)?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Advanced Configuration with FormatOptions
//!
//! ```rust
//! use term_guard::constraints::{FormatConstraint, FormatType, FormatOptions};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Case-insensitive email validation with trimming
//! let flexible_email = FormatConstraint::new(
//!     "email",
//!     FormatType::Email,
//!     0.95,
//!     FormatOptions::lenient()  // case insensitive + trimming + allows nulls
//! )?;
//!
//! // Strict phone validation (no nulls, case sensitive)
//! let strict_phone = FormatConstraint::new(
//!     "phone",
//!     FormatType::Phone { country: Some("US".to_string()) },
//!     0.99,
//!     FormatOptions::strict()  // null_is_valid = false
//! )?;
//!
//! // Custom regex with options
//! let product_code = FormatConstraint::new(
//!     "product_code",
//!     FormatType::Regex(r"^[A-Z]{2}\d{4}$".to_string()),
//!     0.98,
//!     FormatOptions::new()
//!         .case_sensitive(false)
//!         .trim_before_check(true)
//! )?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Specialized Format Types
//!
//! ```rust
//! use term_guard::constraints::FormatConstraint;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Postal codes for different countries
//! let us_zip = FormatConstraint::postal_code("zip", 0.95, "US")?;
//! let uk_postcode = FormatConstraint::postal_code("postcode", 0.95, "UK")?;
//! let ca_postal = FormatConstraint::postal_code("postal", 0.95, "CA")?;
//!
//! // IP address validation
//! let ipv4_check = FormatConstraint::ipv4("client_ip", 0.99)?;
//! let ipv6_check = FormatConstraint::ipv6("server_ip", 0.99)?;
//!
//! // JSON format validation
//! let json_check = FormatConstraint::json("config", 0.98)?;
//!
//! // ISO 8601 datetime validation
//! let datetime_check = FormatConstraint::iso8601_datetime("order_date", 1.0)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Migration from Individual Constraints
//!
//! ### Before (Deprecated)
//! ```rust,ignore
//! use term_guard::constraints::{PatternConstraint, EmailConstraint, UrlConstraint};
//!
//! let email_old = EmailConstraint::new("email", 0.95);
//! let pattern_old = PatternConstraint::new("phone", r"^\d{3}-\d{3}-\d{4}$", 0.90)?;
//! let url_old = UrlConstraint::new("website", 0.85);
//! ```
//!
//! ### After (Unified API)
//! ```rust
//! use term_guard::constraints::FormatConstraint;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let email_new = FormatConstraint::email("email", 0.95)?;
//! let phone_new = FormatConstraint::phone("phone", 0.90, Some("US".to_string()))?;
//! let url_new = FormatConstraint::url("website", 0.85, false)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Performance Considerations
//!
//! - **Pattern Caching**: Compiled regex patterns are cached for reuse
//! - **Built-in Patterns**: Predefined patterns are optimized and tested
//! - **Security**: All patterns are validated to prevent ReDoS attacks
//! - **Memory Efficiency**: Single constraint type reduces memory overhead
//!
//! ## Common Patterns and Use Cases
//!
//! ### Data Quality Checks
//! ```rust
//! use term_guard::constraints::{FormatConstraint, FormatOptions};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Customer data validation
//! let email_quality = FormatConstraint::new(
//!     "customer_email",
//!     term_guard::constraints::FormatType::Email,
//!     0.98,  // 98% must be valid emails
//!     FormatOptions::lenient()  // Allow some flexibility
//! )?;
//!
//! // Credit card detection (for PII scanning)
//! let cc_detection = FormatConstraint::credit_card("description", 0.01, true)?; // Detect if > 1% contain CCs
//! # Ok(())
//! # }
//! ```
//!
//! ### International Data
//! ```rust
//! use term_guard::constraints::FormatConstraint;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Multi-region phone validation
//! let us_phones = FormatConstraint::phone("us_phone", 0.95, Some("US".to_string()))?;
//! let uk_phones = FormatConstraint::phone("uk_phone", 0.95, Some("UK".to_string()))?;
//! let intl_phones = FormatConstraint::phone("intl_phone", 0.90, None)?; // E.164 format
//!
//! // Multi-country postal codes
//! let postal_codes = vec![
//!     FormatConstraint::postal_code("us_zip", 0.99, "US")?,
//!     FormatConstraint::postal_code("ca_postal", 0.99, "CA")?,
//!     FormatConstraint::postal_code("uk_postcode", 0.99, "UK")?,
//! ];
//! # Ok(())
//! # }
//! ```

use crate::core::{current_validation_context, Constraint, ConstraintMetadata, ConstraintResult};
use crate::prelude::*;
use crate::security::SqlSecurity;
use arrow::array::Array;
use async_trait::async_trait;
use datafusion::prelude::*;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::RwLock;
use tracing::instrument;
/// Lazy static pattern cache for compiled regex patterns
static PATTERN_CACHE: Lazy<RwLock<HashMap<String, String>>> =
    Lazy::new(|| RwLock::new(HashMap::new()));

/// Types of format validation that can be performed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FormatType {
    /// Custom regular expression pattern
    Regex(String),
    /// Email address validation
    Email,
    /// URL validation with optional localhost support
    Url { allow_localhost: bool },
    /// Credit card number detection with optional detection-only mode
    CreditCard { detect_only: bool },
    /// Phone number validation with optional country specification
    Phone { country: Option<String> },
    /// Postal code validation for a specific country
    PostalCode { country: String },
    /// UUID (v1, v4, or any) validation
    UUID,
    /// IPv4 address validation
    IPv4,
    /// IPv6 address validation
    IPv6,
    /// JSON format validation
    Json,
    /// ISO 8601 date-time format validation
    Iso8601DateTime,
    /// Social Security Number (SSN) pattern detection
    SocialSecurityNumber,
}

impl FormatType {
    /// Returns the regex pattern for this format type.
    fn get_pattern(&self) -> Result<String> {
        let cache_key = format!("{self:?}");

        // Check cache first
        {
            let cache = PATTERN_CACHE.read().map_err(|_| {
                TermError::Internal("Failed to acquire read lock on pattern cache".to_string())
            })?;
            if let Some(pattern) = cache.get(&cache_key) {
                return Ok(pattern.clone());
            }
        }

        let pattern = match self {
            FormatType::Regex(pattern) => {
                SqlSecurity::validate_regex_pattern(pattern)?;
                pattern.clone()
            }
            FormatType::Email => {
                // More comprehensive email pattern
                r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$".to_string()
            }
            FormatType::Url { allow_localhost } => {
                if *allow_localhost {
                    r"^https?://(?:localhost|(?:[a-zA-Z0-9.-]+\.?[a-zA-Z]{2,}|(?:\d{1,3}\.){3}\d{1,3}))(?::\d+)?(?:/[^\s]*)?$".to_string()
                } else {
                    r"^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?(?:/[^\s]*)?$".to_string()
                }
            }
            FormatType::CreditCard { .. } => {
                // Pattern for major credit card formats (Visa, MasterCard, Amex, Discover)
                r"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3[0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$|^(?:\d{4}[-\s]?){3}\d{4}$".to_string()
            }
            FormatType::Phone { country } => {
                match country.as_deref() {
                    Some("US") | Some("CA") => r"^(\+?1[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$".to_string(),
                    Some("UK") => r"^(\+44\s?)?(?:\(?0\d{4}\)?\s?\d{6}|\(?0\d{3}\)?\s?\d{7}|\(?0\d{2}\)?\s?\d{8})$".to_string(),
                    Some("DE") => r"^(\+49\s?)?(?:\(?0\d{2,5}\)?\s?\d{4,12})$".to_string(),
                    Some("FR") => r"^(\+33\s?)?(?:\(?0\d{1}\)?\s?\d{8})$".to_string(),
                    _ => r"^[\+]?[1-9][\d]{0,15}$".to_string(), // E.164 international format
                }
            }
            FormatType::PostalCode { country } => {
                match country.as_str() {
                    "US" => r"^\d{5}(-\d{4})?$".to_string(),
                    "CA" => r"^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$".to_string(),
                    "UK" => r"^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$".to_string(),
                    "DE" => r"^\d{5}$".to_string(),
                    "FR" => r"^\d{5}$".to_string(),
                    "JP" => r"^\d{3}-\d{4}$".to_string(),
                    "AU" => r"^\d{4}$".to_string(),
                    _ => r"^[A-Za-z0-9\s-]{3,10}$".to_string(), // Generic postal code
                }
            }
            FormatType::UUID => {
                r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$".to_string()
            }
            FormatType::IPv4 => {
                r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$".to_string()
            }
            FormatType::IPv6 => {
                // Simplified IPv6 pattern that handles most common cases
                r"^([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]{0,4})?$|^::$|^::1$|^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$".to_string()
            }
            FormatType::Json => {
                // Simple JSON structure validation - starts with { or [
                r"^\s*[\{\[].*[\}\]]\s*$".to_string()
            }
            FormatType::Iso8601DateTime => {
                // ISO 8601 date-time format (basic validation)
                r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$".to_string()
            }
            FormatType::SocialSecurityNumber => {
                // SSN patterns: XXX-XX-XXXX or XXXXXXXXX
                // Matches valid SSN ranges (001-899 except 666) in first 3 digits
                // Middle 2 digits must be 01-99, last 4 must be 0001-9999
                // This regex avoids look-ahead by explicitly listing valid ranges
                r"^(00[1-9]|0[1-9][0-9]|[1-5][0-9]{2}|6[0-5][0-9]|66[0-5]|667|66[89]|6[7-9][0-9]|[7-8][0-9]{2})-?(0[1-9]|[1-9][0-9])-?(000[1-9]|00[1-9][0-9]|0[1-9][0-9]{2}|[1-9][0-9]{3})$".to_string()
            }
        };

        // Cache the pattern
        {
            let mut cache = PATTERN_CACHE.write().map_err(|_| {
                TermError::Internal("Failed to acquire write lock on pattern cache".to_string())
            })?;
            cache.insert(cache_key, pattern.clone());
        }

        Ok(pattern)
    }

    /// Returns a human-readable name for this format type.
    pub fn name(&self) -> &str {
        match self {
            FormatType::Regex(_) => "regex",
            FormatType::Email => "email",
            FormatType::Url { .. } => "url",
            FormatType::CreditCard { .. } => "credit_card",
            FormatType::Phone { .. } => "phone",
            FormatType::PostalCode { .. } => "postal_code",
            FormatType::UUID => "uuid",
            FormatType::IPv4 => "ipv4",
            FormatType::IPv6 => "ipv6",
            FormatType::Json => "json",
            FormatType::Iso8601DateTime => "iso8601_datetime",
            FormatType::SocialSecurityNumber => "social_security_number",
        }
    }

    /// Returns a human-readable description for this format type.
    pub fn description(&self) -> String {
        match self {
            FormatType::Regex(pattern) => format!("matches pattern '{pattern}'"),
            FormatType::Email => "are valid email addresses".to_string(),
            FormatType::Url { allow_localhost } => {
                if *allow_localhost {
                    "are valid URLs (including localhost)".to_string()
                } else {
                    "are valid URLs".to_string()
                }
            }
            FormatType::CreditCard { detect_only } => {
                if *detect_only {
                    "contain credit card number patterns".to_string()
                } else {
                    "are valid credit card numbers".to_string()
                }
            }
            FormatType::Phone { country } => match country.as_deref() {
                Some(c) => format!("are valid {c} phone numbers"),
                None => "are valid phone numbers".to_string(),
            },
            FormatType::PostalCode { country } => {
                format!("are valid {country} postal codes")
            }
            FormatType::UUID => "are valid UUIDs".to_string(),
            FormatType::IPv4 => "are valid IPv4 addresses".to_string(),
            FormatType::IPv6 => "are valid IPv6 addresses".to_string(),
            FormatType::Json => "are valid JSON documents".to_string(),
            FormatType::Iso8601DateTime => "are valid ISO 8601 date-time strings".to_string(),
            FormatType::SocialSecurityNumber => {
                "contain Social Security Number patterns".to_string()
            }
        }
    }
}

/// Options for format constraint behavior.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FormatOptions {
    /// Whether pattern matching should be case sensitive
    pub case_sensitive: bool,
    /// Whether to trim whitespace before checking format
    pub trim_before_check: bool,
    /// Whether NULL values should be considered valid
    pub null_is_valid: bool,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            case_sensitive: true,
            trim_before_check: false,
            null_is_valid: true, // NULL values are typically considered valid in data quality
        }
    }
}

impl FormatOptions {
    /// Creates new format options with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets case sensitivity for pattern matching.
    pub fn case_sensitive(mut self, case_sensitive: bool) -> Self {
        self.case_sensitive = case_sensitive;
        self
    }

    /// Sets whether to trim whitespace before format checking.
    pub fn trim_before_check(mut self, trim: bool) -> Self {
        self.trim_before_check = trim;
        self
    }

    /// Sets whether NULL values should be considered valid.
    pub fn null_is_valid(mut self, null_valid: bool) -> Self {
        self.null_is_valid = null_valid;
        self
    }

    /// Creates format options for case-insensitive matching.
    ///
    /// This is a convenience method that sets case_sensitive to false.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use term_guard::constraints::FormatOptions;
    ///
    /// let options = FormatOptions::case_insensitive();
    /// assert_eq!(options.case_sensitive, false);
    /// ```
    pub fn case_insensitive() -> Self {
        Self::new().case_sensitive(false)
    }

    /// Creates format options for strict validation (no nulls, case sensitive, no trimming).
    ///
    /// This is a convenience method for the most restrictive validation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use term_guard::constraints::FormatOptions;
    ///
    /// let options = FormatOptions::strict();
    /// assert_eq!(options.case_sensitive, true);
    /// assert_eq!(options.trim_before_check, false);
    /// assert_eq!(options.null_is_valid, false);
    /// ```
    pub fn strict() -> Self {
        Self::new().null_is_valid(false)
    }

    /// Creates format options for lenient validation (case insensitive, trimming, nulls allowed).
    ///
    /// This is a convenience method for the most permissive validation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use term_guard::constraints::FormatOptions;
    ///
    /// let options = FormatOptions::lenient();
    /// assert_eq!(options.case_sensitive, false);
    /// assert_eq!(options.trim_before_check, true);
    /// assert_eq!(options.null_is_valid, true);
    /// ```
    pub fn lenient() -> Self {
        Self::new()
            .case_sensitive(false)
            .trim_before_check(true)
            .null_is_valid(true)
    }

    /// Creates format options with trimming enabled.
    ///
    /// This is a convenience method that enables whitespace trimming before validation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use term_guard::constraints::FormatOptions;
    ///
    /// let options = FormatOptions::with_trimming();
    /// assert_eq!(options.trim_before_check, true);
    /// ```
    pub fn with_trimming() -> Self {
        Self::new().trim_before_check(true)
    }
}

/// A unified constraint that validates data formats and patterns.
///
/// This constraint replaces individual format constraints (PatternConstraint,
/// EmailConstraint, UrlConstraint, CreditCardConstraint) and adds support
/// for many additional formats.
///
/// # Examples
///
/// ```rust
/// use term_guard::constraints::{FormatConstraint, FormatType, FormatOptions};
/// use term_guard::core::Constraint;
///
/// // Email validation
/// let email_constraint = FormatConstraint::new(
///     "email",
///     FormatType::Email,
///     0.95,
///     FormatOptions::default()
/// ).unwrap();
///
/// // Phone number validation for US
/// let phone_constraint = FormatConstraint::new(
///     "phone",
///     FormatType::Phone { country: Some("US".to_string()) },
///     0.90,
///     FormatOptions::new().trim_before_check(true)
/// ).unwrap();
///
/// // Custom regex pattern
/// let code_constraint = FormatConstraint::new(
///     "product_code",
///     FormatType::Regex(r"^[A-Z]{2}\d{4}$".to_string()),
///     1.0,
///     FormatOptions::default()
/// ).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct FormatConstraint {
    /// The column to validate
    column: String,
    /// The format type to check
    format: FormatType,
    /// The minimum ratio of values that must match the format (0.0 to 1.0)
    threshold: f64,
    /// Options for format validation behavior
    options: FormatOptions,
}

impl FormatConstraint {
    /// Creates a new format constraint.
    ///
    /// # Arguments
    ///
    /// * `column` - The column to check
    /// * `format` - The format type to validate
    /// * `threshold` - The minimum ratio of values that must match (0.0 to 1.0)
    /// * `options` - Format validation options
    ///
    /// # Errors
    ///
    /// Returns error if column name is invalid or threshold is out of range
    pub fn new(
        column: impl Into<String>,
        format: FormatType,
        threshold: f64,
        options: FormatOptions,
    ) -> Result<Self> {
        let column_str = column.into();

        // Validate inputs
        SqlSecurity::validate_identifier(&column_str)?;

        if !(0.0..=1.0).contains(&threshold) {
            return Err(TermError::SecurityError(
                "Threshold must be between 0.0 and 1.0".to_string(),
            ));
        }

        // Validate that the format can generate a pattern
        format.get_pattern()?;

        Ok(Self {
            column: column_str,
            format,
            threshold,
            options,
        })
    }

    /// Creates a format constraint for email validation.
    pub fn email(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::Email,
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for URL validation.
    pub fn url(column: impl Into<String>, threshold: f64, allow_localhost: bool) -> Result<Self> {
        Self::new(
            column,
            FormatType::Url { allow_localhost },
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for credit card detection.
    pub fn credit_card(
        column: impl Into<String>,
        threshold: f64,
        detect_only: bool,
    ) -> Result<Self> {
        Self::new(
            column,
            FormatType::CreditCard { detect_only },
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for phone number validation.
    pub fn phone(
        column: impl Into<String>,
        threshold: f64,
        country: Option<String>,
    ) -> Result<Self> {
        Self::new(
            column,
            FormatType::Phone { country },
            threshold,
            FormatOptions::new().trim_before_check(true),
        )
    }

    /// Creates a format constraint for postal code validation.
    pub fn postal_code(
        column: impl Into<String>,
        threshold: f64,
        country: impl Into<String>,
    ) -> Result<Self> {
        Self::new(
            column,
            FormatType::PostalCode {
                country: country.into(),
            },
            threshold,
            FormatOptions::new().trim_before_check(true),
        )
    }

    /// Creates a format constraint for UUID validation.
    pub fn uuid(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::UUID,
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for IPv4 address validation.
    pub fn ipv4(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::IPv4,
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for IPv6 address validation.
    pub fn ipv6(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::IPv6,
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for JSON validation.
    pub fn json(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::Json,
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for ISO 8601 date-time validation.
    pub fn iso8601_datetime(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::Iso8601DateTime,
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for custom regex pattern validation.
    pub fn regex(
        column: impl Into<String>,
        pattern: impl Into<String>,
        threshold: f64,
    ) -> Result<Self> {
        Self::new(
            column,
            FormatType::Regex(pattern.into()),
            threshold,
            FormatOptions::default(),
        )
    }

    /// Creates a format constraint for Social Security Number pattern detection.
    ///
    /// This method checks for SSN patterns (XXX-XX-XXXX or XXXXXXXXX) and excludes
    /// known invalid SSNs such as those starting with 000, 666, or 900-999.
    ///
    /// # Arguments
    ///
    /// * `column` - The column to check for SSN patterns
    /// * `threshold` - The minimum ratio of values that must match the SSN pattern (0.0 to 1.0)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use term_guard::constraints::FormatConstraint;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Check that at least 95% of values are valid SSN patterns
    /// let ssn_check = FormatConstraint::social_security_number("ssn", 0.95)?;
    ///
    /// // For PII detection - flag if more than 1% contain SSN patterns
    /// let ssn_detection = FormatConstraint::social_security_number("description", 0.01)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn social_security_number(column: impl Into<String>, threshold: f64) -> Result<Self> {
        Self::new(
            column,
            FormatType::SocialSecurityNumber,
            threshold,
            FormatOptions::new().trim_before_check(true),
        )
    }
}

#[async_trait]
impl Constraint for FormatConstraint {
    #[instrument(skip(self, ctx), fields(
        column = %self.column,
        format = %self.format.name(),
        threshold = %self.threshold
    ))]
    async fn evaluate(&self, ctx: &SessionContext) -> Result<ConstraintResult> {
        // Get the table name from the validation context
        let validation_ctx = current_validation_context();
        let table_name = validation_ctx.table_name();

        let column_identifier = SqlSecurity::escape_identifier(&self.column)?;
        let pattern = self.format.get_pattern()?;
        let escaped_pattern = SqlSecurity::validate_regex_pattern(&pattern)?;

        // Build the SQL based on options
        let column_expr = if self.options.trim_before_check {
            format!("TRIM({column_identifier})")
        } else {
            column_identifier.clone()
        };

        let pattern_operator = if self.options.case_sensitive {
            "~"
        } else {
            "~*"
        };

        let sql = if self.options.null_is_valid {
            format!(
                "SELECT 
                    COUNT(CASE WHEN {column_expr} {pattern_operator} '{escaped_pattern}' OR {column_identifier} IS NULL THEN 1 END) as matches,
                    COUNT(*) as total
                 FROM {table_name}"
            )
        } else {
            format!(
                "SELECT 
                    COUNT(CASE WHEN {column_expr} {pattern_operator} '{escaped_pattern}' THEN 1 END) as matches,
                    COUNT(*) as total
                 FROM {table_name}"
            )
        };

        let df = ctx.sql(&sql).await?;
        let batches = df.collect().await?;

        if batches.is_empty() {
            return Ok(ConstraintResult::skipped("No data to validate"));
        }

        let batch = &batches[0];
        if batch.num_rows() == 0 {
            return Ok(ConstraintResult::skipped("No data to validate"));
        }

        let matches = batch
            .column(0)
            .as_any()
            .downcast_ref::<arrow::array::Int64Array>()
            .ok_or_else(|| TermError::Internal("Failed to extract match count".to_string()))?
            .value(0) as f64;

        let total = batch
            .column(1)
            .as_any()
            .downcast_ref::<arrow::array::Int64Array>()
            .ok_or_else(|| TermError::Internal("Failed to extract total count".to_string()))?
            .value(0) as f64;

        if total == 0.0 {
            return Ok(ConstraintResult::skipped("No data to validate"));
        }

        let match_ratio = matches / total;

        // Determine success based on format type and threshold
        let is_success = match &self.format {
            FormatType::CreditCard { detect_only: true } => {
                // For credit card detection, we want the ratio to be <= threshold
                match_ratio <= self.threshold
            }
            _ => {
                // For other formats, we want the ratio to be >= threshold
                match_ratio >= self.threshold
            }
        };

        if is_success {
            Ok(ConstraintResult::success_with_metric(match_ratio))
        } else {
            let message = match &self.format {
                FormatType::CreditCard { detect_only: true } => {
                    format!(
                        "Credit card detection ratio {match_ratio:.3} exceeds threshold {:.3}",
                        self.threshold
                    )
                }
                _ => {
                    let desc = self.format.description();
                    format!(
                        "Format validation ratio {match_ratio:.3} is below threshold {:.3} - values that {desc}",
                        self.threshold
                    )
                }
            };

            Ok(ConstraintResult::failure_with_metric(match_ratio, message))
        }
    }

    fn name(&self) -> &str {
        self.format.name()
    }

    fn column(&self) -> Option<&str> {
        Some(&self.column)
    }

    fn metadata(&self) -> ConstraintMetadata {
        let description = match &self.format {
            FormatType::CreditCard { detect_only: true } => {
                let threshold_pct = self.threshold * 100.0;
                let desc = self.format.description();
                format!(
                    "Checks that no more than {threshold_pct:.1}% of values in '{}' {desc}",
                    self.column
                )
            }
            _ => {
                let threshold_pct = self.threshold * 100.0;
                let desc = self.format.description();
                format!(
                    "Checks that at least {threshold_pct:.1}% of values in '{}' {desc}",
                    self.column
                )
            }
        };

        ConstraintMetadata::for_column(&self.column)
            .with_description(description)
            .with_custom("format_type", self.format.name())
            .with_custom("threshold", self.threshold.to_string())
            .with_custom("case_sensitive", self.options.case_sensitive.to_string())
            .with_custom(
                "trim_before_check",
                self.options.trim_before_check.to_string(),
            )
            .with_custom("null_is_valid", self.options.null_is_valid.to_string())
            .with_custom("constraint_type", "format")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ConstraintStatus;
    use arrow::array::StringArray;
    use arrow::datatypes::{DataType, Field, Schema};
    use arrow::record_batch::RecordBatch;
    use datafusion::datasource::MemTable;
    use std::sync::Arc;

    use crate::test_helpers::evaluate_constraint_with_context;
    async fn create_test_context(values: Vec<Option<&str>>) -> SessionContext {
        let ctx = SessionContext::new();

        let schema = Arc::new(Schema::new(vec![Field::new(
            "text_col",
            DataType::Utf8,
            true,
        )]));

        let array = StringArray::from(values);
        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();

        let provider = MemTable::try_new(schema, vec![vec![batch]]).unwrap();
        ctx.register_table("data", Arc::new(provider)).unwrap();

        ctx
    }

    #[tokio::test]
    async fn test_email_format_constraint() {
        let values = vec![
            Some("test@example.com"),
            Some("user@domain.org"),
            Some("invalid-email"),
            Some("another@test.net"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::email("text_col", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are emails
        assert_eq!(constraint.name(), "email");
    }

    #[tokio::test]
    async fn test_url_format_constraint() {
        let values = vec![
            Some("https://example.com"),
            Some("http://test.org"),
            Some("not-a-url"),
            Some("https://another.site.net/path"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::url("text_col", 0.7, false).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are URLs
        assert_eq!(constraint.name(), "url");
    }

    #[tokio::test]
    async fn test_url_with_localhost() {
        let values = vec![
            Some("https://localhost:3000"),
            Some("http://localhost"),
            Some("https://example.com"),
            Some("not-a-url"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::url("text_col", 0.7, true).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are URLs (including localhost)
    }

    #[tokio::test]
    async fn test_credit_card_detection() {
        let values = vec![
            Some("4111-1111-1111-1111"),
            Some("5555 5555 5555 4444"),
            Some("normal text"),
            Some("4111111111111111"), // Visa format
        ];
        let ctx = create_test_context(values).await;

        // Expect no more than 80% to be credit card numbers
        let constraint = FormatConstraint::credit_card("text_col", 0.8, true).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(constraint.name(), "credit_card");
    }

    #[tokio::test]
    async fn test_phone_number_us() {
        let values = vec![
            Some("(555) 123-4567"),
            Some("555-123-4567"),
            Some("5551234567"),
            Some("invalid-phone"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::phone("text_col", 0.7, Some("US".to_string())).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(constraint.name(), "phone");
    }

    #[tokio::test]
    async fn test_postal_code_us() {
        let values = vec![
            Some("12345"),
            Some("12345-6789"),
            Some("invalid"),
            Some("98765"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::postal_code("text_col", 0.7, "US").unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are valid US postal codes
        assert_eq!(constraint.name(), "postal_code");
    }

    #[tokio::test]
    async fn test_uuid_format() {
        let values = vec![
            Some("550e8400-e29b-41d4-a716-446655440000"),
            Some("6ba7b810-9dad-11d1-80b4-00c04fd430c8"),
            Some("invalid-uuid"),
            Some("6ba7b811-9dad-11d1-80b4-00c04fd430c8"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::uuid("text_col", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are UUIDs
        assert_eq!(constraint.name(), "uuid");
    }

    #[tokio::test]
    async fn test_ipv4_format() {
        let values = vec![
            Some("192.168.1.1"),
            Some("10.0.0.1"),
            Some("256.256.256.256"), // Invalid - out of range
            Some("172.16.0.1"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::ipv4("text_col", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are valid IPv4
        assert_eq!(constraint.name(), "ipv4");
    }

    #[tokio::test]
    async fn test_ipv6_format() {
        let values = vec![
            Some("2001:0db8:85a3:0000:0000:8a2e:0370:7334"),
            Some("2001:db8:85a3::8a2e:370:7334"),
            Some("invalid-ipv6"),
            Some("::1"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::ipv6("text_col", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are valid IPv6
        assert_eq!(constraint.name(), "ipv6");
    }

    #[tokio::test]
    async fn test_json_format() {
        let values = vec![
            Some(r#"{"key": "value"}"#),
            Some(r#"[1, 2, 3]"#),
            Some("not json"),
            Some(r#"{"nested": {"key": "value"}}"#),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::json("text_col", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 look like JSON
        assert_eq!(constraint.name(), "json");
    }

    #[tokio::test]
    async fn test_iso8601_datetime_format() {
        let values = vec![
            Some("2023-12-25T10:30:00Z"),
            Some("2023-12-25T10:30:00.123Z"),
            Some("invalid-datetime"),
            Some("2023-12-25T10:30:00+05:30"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::iso8601_datetime("text_col", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are ISO 8601
        assert_eq!(constraint.name(), "iso8601_datetime");
    }

    #[tokio::test]
    async fn test_custom_regex_format() {
        let values = vec![
            Some("ABC123"),
            Some("DEF456"),
            Some("invalid"),
            Some("GHI789"),
        ];
        let ctx = create_test_context(values).await;

        // Pattern to match 3 letters followed by 3 digits
        let constraint = FormatConstraint::regex("text_col", r"^[A-Z]{3}\d{3}$", 0.7).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 match
        assert_eq!(constraint.name(), "regex");
    }

    #[tokio::test]
    async fn test_format_options_case_insensitive() {
        let values = vec![
            Some("abc123"),
            Some("DEF456"),
            Some("invalid"),
            Some("ghi789"),
        ];
        let ctx = create_test_context(values).await;

        // Pattern should match both upper and lower case when case_insensitive is true
        let constraint = FormatConstraint::new(
            "text_col",
            FormatType::Regex(r"^[A-Z]{3}\d{3}$".to_string()),
            0.7,
            FormatOptions::new().case_sensitive(false),
        )
        .unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 match (case insensitive)
    }

    #[tokio::test]
    async fn test_format_options_trim_whitespace() {
        let values = vec![
            Some("  test@example.com  "),
            Some("user@domain.org"),
            Some("  invalid-email  "),
            Some(" another@test.net "),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::new(
            "text_col",
            FormatType::Email,
            0.7,
            FormatOptions::new().trim_before_check(true),
        )
        .unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.75)); // 3 out of 4 are emails after trimming
    }

    #[tokio::test]
    async fn test_format_options_null_handling() {
        let values = vec![Some("test@example.com"), None, Some("invalid-email"), None];
        let ctx = create_test_context(values).await;

        // With null_is_valid = true (default)
        let constraint1 = FormatConstraint::new(
            "text_col",
            FormatType::Email,
            0.6,
            FormatOptions::new().null_is_valid(true),
        )
        .unwrap();

        let result1 = evaluate_constraint_with_context(&constraint1, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result1.status, ConstraintStatus::Success);
        assert_eq!(result1.metric, Some(0.75)); // 1 email + 2 nulls out of 4

        // With null_is_valid = false
        let constraint2 = FormatConstraint::new(
            "text_col",
            FormatType::Email,
            0.2,
            FormatOptions::new().null_is_valid(false),
        )
        .unwrap();

        let result2 = evaluate_constraint_with_context(&constraint2, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result2.status, ConstraintStatus::Success);
        assert_eq!(result2.metric, Some(0.25)); // Only 1 email out of 4
    }

    #[tokio::test]
    async fn test_constraint_failure() {
        let values = vec![
            Some("invalid"),
            Some("also_invalid"),
            Some("nope"),
            Some("still_invalid"),
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::email("text_col", 0.5).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Failure);
        assert_eq!(result.metric, Some(0.0)); // No values are emails
        assert!(result.message.is_some());
    }

    #[tokio::test]
    async fn test_empty_data() {
        let ctx = create_test_context(vec![]).await;
        let constraint = FormatConstraint::email("text_col", 0.9).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Skipped);
    }

    #[test]
    fn test_invalid_threshold() {
        let result = FormatConstraint::email("col", 1.5);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Threshold must be between 0.0 and 1.0"));
    }

    #[test]
    fn test_pattern_caching() {
        // Test that patterns are cached for performance
        let format1 = FormatType::Email;
        let format2 = FormatType::Email;

        let pattern1 = format1.get_pattern().unwrap();
        let pattern2 = format2.get_pattern().unwrap();

        assert_eq!(pattern1, pattern2);

        // Accessing cache multiple times should be fast
        for _ in 0..100 {
            let _ = format1.get_pattern().unwrap();
        }
    }

    #[test]
    fn test_format_type_descriptions() {
        assert_eq!(FormatType::Email.description(), "are valid email addresses");
        assert_eq!(
            FormatType::Url {
                allow_localhost: true
            }
            .description(),
            "are valid URLs (including localhost)"
        );
        assert_eq!(
            FormatType::Phone {
                country: Some("US".to_string())
            }
            .description(),
            "are valid US phone numbers"
        );
        assert_eq!(
            FormatType::PostalCode {
                country: "CA".to_string()
            }
            .description(),
            "are valid CA postal codes"
        );
    }

    #[test]
    fn test_all_format_types_have_patterns() {
        // Ensure all format types can generate valid patterns
        let formats = vec![
            FormatType::Email,
            FormatType::Url {
                allow_localhost: false,
            },
            FormatType::Url {
                allow_localhost: true,
            },
            FormatType::CreditCard { detect_only: false },
            FormatType::Phone { country: None },
            FormatType::Phone {
                country: Some("US".to_string()),
            },
            FormatType::PostalCode {
                country: "US".to_string(),
            },
            FormatType::UUID,
            FormatType::IPv4,
            FormatType::IPv6,
            FormatType::Json,
            FormatType::Iso8601DateTime,
            FormatType::Regex(r"^\d+$".to_string()),
        ];

        for format in formats {
            assert!(
                format.get_pattern().is_ok(),
                "Format {format:?} should have a valid pattern"
            );
        }
    }

    #[test]
    fn test_format_options_convenience_methods() {
        // Test case_insensitive()
        let options = FormatOptions::case_insensitive();
        assert!(!options.case_sensitive);
        assert!(!options.trim_before_check);
        assert!(options.null_is_valid);

        // Test strict()
        let options = FormatOptions::strict();
        assert!(options.case_sensitive);
        assert!(!options.trim_before_check);
        assert!(!options.null_is_valid);

        // Test lenient()
        let options = FormatOptions::lenient();
        assert!(!options.case_sensitive);
        assert!(options.trim_before_check);
        assert!(options.null_is_valid);

        // Test with_trimming()
        let options = FormatOptions::with_trimming();
        assert!(options.case_sensitive);
        assert!(options.trim_before_check);
        assert!(options.null_is_valid);
    }

    #[tokio::test]
    async fn test_ssn_format_valid() {
        let values = vec![
            Some("123-45-6789"), // Valid hyphenated
            Some("123456789"),   // Valid non-hyphenated
            Some("456-78-9012"), // Valid hyphenated
            Some("789012345"),   // Valid non-hyphenated
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::social_security_number("text_col", 0.95).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(1.0)); // All are valid SSNs
        assert_eq!(constraint.name(), "social_security_number");
    }

    #[tokio::test]
    async fn test_ssn_format_invalid_patterns() {
        let values = vec![
            Some("000-12-3456"), // Invalid: starts with 000
            Some("666-12-3456"), // Invalid: starts with 666
            Some("900-12-3456"), // Invalid: starts with 9xx
            Some("123-00-4567"), // Invalid: middle is 00
            Some("123-45-0000"), // Invalid: last four are 0000
        ];
        let ctx = create_test_context(values).await;

        // Threshold means we expect AT LEAST that percentage to be valid
        // Since none are valid (0.0), and we're expecting at least 0.0, it's Success
        let constraint = FormatConstraint::social_security_number("text_col", 0.0).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        // None of these should be valid with our regex
        // 0.0 >= 0.0 means Success
        assert_eq!(result.status, ConstraintStatus::Success);
        assert_eq!(result.metric, Some(0.0)); // None should be valid
    }

    #[tokio::test]
    async fn test_ssn_format_mixed() {
        let values = vec![
            Some("123-45-6789"), // Valid
            Some("not-an-ssn"),  // Invalid format
            Some("666-12-3456"), // Invalid: starts with 666
            Some("456789012"),   // Valid non-hyphenated
            Some("123 45 6789"), // Invalid: spaces instead of hyphens
            Some("789-01-2345"), // Valid
            None,                // Null value
            Some("234-56-7890"), // Valid
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::social_security_number("text_col", 0.5).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success);
        // Valid SSNs: 123-45-6789, 456789012, 789-01-2345, 234-56-7890
        // Invalid: not-an-ssn, 666-12-3456, "123 45 6789" (spaces)
        // Null is handled by default options (null_is_valid = true in FormatOptions)
        // So we have 4 valid + 1 null = 5 matches out of 8 total = 0.625
        assert_eq!(result.metric, Some(0.625));
    }

    #[tokio::test]
    async fn test_ssn_format_threshold() {
        let values = vec![
            Some("123-45-6789"), // Valid
            Some("invalid"),     // Invalid
            Some("234-56-7890"), // Valid
            Some("not-ssn"),     // Invalid
        ];
        let ctx = create_test_context(values).await;

        // Test with threshold that should fail
        let constraint = FormatConstraint::social_security_number("text_col", 0.8).unwrap();
        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Failure); // 0.5 < 0.8
        assert_eq!(result.metric, Some(0.5));

        // Test with threshold that should pass
        let constraint = FormatConstraint::social_security_number("text_col", 0.4).unwrap();
        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        assert_eq!(result.status, ConstraintStatus::Success); // 0.5 >= 0.4
        assert_eq!(result.metric, Some(0.5));
    }

    #[tokio::test]
    async fn test_ssn_edge_cases() {
        let values = vec![
            Some("078-05-1120"),  // Valid: Woolworth's SSN (historically used in examples)
            Some("219-09-9999"),  // Valid: Used in advertisements
            Some("457-55-5462"),  // Valid: Used in LifeLock ads
            Some("999-99-9999"),  // Invalid: starts with 9xx
            Some("123-45-67890"), // Invalid: too many digits
            Some("12-345-6789"),  // Invalid: wrong format
            Some("ABC-DE-FGHI"),  // Invalid: letters
            Some(""),             // Invalid: empty string
        ];
        let ctx = create_test_context(values).await;

        let constraint = FormatConstraint::social_security_number("text_col", 0.3).unwrap();

        let result = evaluate_constraint_with_context(&constraint, &ctx, "data")
            .await
            .unwrap();
        // Only first 3 are valid
        assert_eq!(result.metric, Some(0.375)); // 3 out of 8
        assert_eq!(result.status, ConstraintStatus::Success); // 0.375 >= 0.3
    }
}