copybook-core 0.4.3

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

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::context::SecurityClassification;
use super::{AuditContext, AuditResult};
use crate::Field;

/// Enterprise compliance engine for regulatory validation
pub struct ComplianceEngine {
    profiles: Vec<ComplianceProfile>,
    validators: HashMap<ComplianceProfile, Box<dyn ComplianceValidator>>,
    config: ComplianceConfig,
}

impl ComplianceEngine {
    /// Create a new compliance engine with a given configuration
    pub fn new(config: ComplianceConfig) -> Self {
        Self {
            profiles: Vec::new(),
            validators: HashMap::new(),
            config,
        }
    }

    /// Add compliance profiles to validate against
    #[must_use]
    pub fn with_profiles(mut self, profiles: &[ComplianceProfile]) -> Self {
        self.profiles = profiles.to_vec();

        // Initialize validators for each profile with its specific config
        for profile in profiles {
            let validator: Box<dyn ComplianceValidator> = match profile {
                ComplianceProfile::SOX => Box::new(SoxValidator::new(self.config.sox.clone())),
                ComplianceProfile::HIPAA => {
                    Box::new(HipaaValidator::new(self.config.hipaa.clone()))
                }
                ComplianceProfile::GDPR => Box::new(GdprValidator::new(self.config.gdpr.clone())),
                ComplianceProfile::PciDss => {
                    Box::new(PciDssValidator::new(self.config.pci_dss.clone()))
                }
            };
            self.validators.insert(*profile, validator);
        }

        self
    }

    /// Validate processing operation against all configured compliance profiles
    pub async fn validate_processing_operation(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceResult> {
        let mut violations = Vec::new();
        let mut warnings = Vec::new();

        for profile in &self.profiles {
            if let Some(validator) = self.validators.get(profile) {
                match validator.validate_operation(context).await {
                    Ok(validation_result) => {
                        violations.extend(validation_result.violations);
                        warnings.extend(validation_result.warnings);
                    }
                    Err(e) => {
                        // Add a critical violation when a validator fails completely
                        violations.push(ComplianceViolation {
                            violation_id: format!("{:?}-VALIDATOR-FAILURE", profile),
                            regulation: format!("{:?} Compliance Framework", profile),
                            severity: ComplianceSeverity::Critical,
                            title: "Compliance Validator System Failure".to_string(),
                            description: format!(
                                "Critical failure in {:?} compliance validator: {}. \n\
                                Compliance status cannot be determined for this framework.",
                                profile, e
                            ),
                            remediation: format!(
                                "Investigate and resolve {:?} validator system issues. \n\
                                Review audit logs and system health. \n\
                                Consider manual compliance review until validator is restored.",
                                profile
                            ),
                            reference_url: None,
                        });

                        // Add warning about degraded compliance monitoring
                        warnings.push(ComplianceWarning {
                            warning_id: format!("{:?}-DEGRADED-MONITORING", profile),
                            title: "Degraded Compliance Monitoring".to_string(),
                            description: format!(
                                "Compliance monitoring for {:?} framework is degraded due to validator failure",
                                profile
                            ),
                            recommendation: "Restore validator functionality to ensure complete compliance coverage".to_string(),
                        });
                    }
                }
            }
        }

        let compliance_status = if violations.is_empty() {
            if warnings.is_empty() {
                ComplianceStatus::Compliant
            } else {
                ComplianceStatus::CompliantWithWarnings
            }
        } else {
            ComplianceStatus::NonCompliant
        };

        Ok(ComplianceResult {
            status: compliance_status,
            violations,
            warnings,
            validated_profiles: self.profiles.clone(),
            validation_timestamp: chrono::Utc::now().to_rfc3339(),
        })
    }

    /// Generate compliance report for audit purposes
    pub async fn generate_compliance_report(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceReport> {
        let validation_result = self.validate_processing_operation(context).await?;

        // Generate recommendations with fallback handling
        let recommendations = match self.generate_recommendations(context).await {
            Ok(recs) => recs,
            Err(e) => {
                // Provide fallback recommendation when recommendation generation fails
                vec![ComplianceRecommendation {
                    recommendation_id: "SYSTEM-FALLBACK-REC".to_string(),
                    priority: RecommendationPriority::Critical,
                    title: "Restore Compliance Recommendation System".to_string(),
                    description: format!(
                        "The compliance recommendation system failed: {}. \n\
                        Manual compliance analysis is required.",
                        e
                    ),
                    implementation_effort: "Immediate".to_string(),
                    compliance_benefit:
                        "Restores automated compliance guidance and recommendations".to_string(),
                }]
            }
        };

        Ok(ComplianceReport {
            report_id: super::generate_audit_id(),
            operation_id: context.operation_id.clone(),
            compliance_result: validation_result,
            recommendations,
            next_review_date: self.calculate_next_review_date(),
            created_at: chrono::Utc::now().to_rfc3339(),
        })
    }

    async fn generate_recommendations(
        &self,
        context: &AuditContext,
    ) -> AuditResult<Vec<ComplianceRecommendation>> {
        let mut recommendations = Vec::new();

        for profile in &self.profiles {
            if let Some(validator) = self.validators.get(profile) {
                match validator.generate_recommendations(context).await {
                    Ok(profile_recommendations) => {
                        recommendations.extend(profile_recommendations);
                    }
                    Err(e) => {
                        // Add fallback recommendation when validator fails
                        recommendations.push(ComplianceRecommendation {
                            recommendation_id: format!("{:?}-FALLBACK-REC", profile),
                            priority: RecommendationPriority::Critical,
                            title: format!("Restore {:?} Compliance Monitoring", profile),
                            description: format!(
                                "The {:?} compliance validator failed to generate recommendations due to: {}. \n\
                                Manual compliance review is recommended until validator is restored.",
                                profile, e
                            ),
                            implementation_effort: "Immediate".to_string(),
                            compliance_benefit: format!(
                                "Restores automated {:?} compliance monitoring and recommendation generation",
                                profile
                            ),
                        });
                    }
                }
            }
        }

        Ok(recommendations)
    }

    fn calculate_next_review_date(&self) -> String {
        let review_interval = self.config.review_interval_days.unwrap_or(90);
        let next_review = chrono::Utc::now() + chrono::Duration::days(review_interval as i64);
        next_review.to_rfc3339()
    }
}

impl Default for ComplianceEngine {
    fn default() -> Self {
        Self::new(ComplianceConfig::default())
    }
}

/// Compliance profiles for different regulatory frameworks
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ComplianceProfile {
    /// Sarbanes-Oxley Act (Financial Services)
    SOX,
    /// Health Insurance Portability and Accountability Act
    HIPAA,
    /// General Data Protection Regulation
    GDPR,
    /// Payment Card Industry Data Security Standard
    PciDss,
}

/// Compliance validation trait for different regulatory frameworks
#[async_trait::async_trait]
pub trait ComplianceValidator: Send + Sync {
    /// Validate a processing operation against this compliance framework.
    async fn validate_operation(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceValidationResult>;
    /// Generate compliance recommendations based on the audit context.
    async fn generate_recommendations(
        &self,
        context: &AuditContext,
    ) -> AuditResult<Vec<ComplianceRecommendation>>;
}

/// SOX compliance validator
#[derive(Default)]
pub struct SoxValidator {
    config: SoxConfig,
}

impl SoxValidator {
    /// Creates a new SOX compliance validator with the given configuration.
    pub fn new(config: SoxConfig) -> Self {
        Self { config }
    }

    fn validate_financial_data_controls(&self, context: &AuditContext) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // SOX Section 302: Financial data integrity controls
        if !self.has_adequate_data_integrity_controls(context) {
            violations.push(ComplianceViolation {
                violation_id: "SOX-302-001".to_string(),
                regulation: "SOX Section 302".to_string(),
                severity: ComplianceSeverity::High,
                title: "Inadequate Financial Data Integrity Controls".to_string(),
                description: "Processing lacks cryptographic validation required for financial data integrity".to_string(),
                remediation: "Implement SHA-256 integrity validation for all financial data processing operations".to_string(),
                reference_url: Some("https://www.sec.gov/rules/final/33-8238.htm".to_string()),
            });
        }

        // SOX Section 404: Internal controls assessment
        if !self.has_segregation_of_duties(context) {
            violations.push(ComplianceViolation {
                violation_id: "SOX-404-001".to_string(),
                regulation: "SOX Section 404".to_string(),
                severity: ComplianceSeverity::High,
                title: "Segregation of Duties Violation".to_string(),
                description: "Single user has both processing and validation permissions".to_string(),
                remediation: "Implement role-based access control with segregation of duties for financial data processing".to_string(),
                reference_url: Some("https://www.sec.gov/rules/final/33-8238.htm".to_string()),
            });
        }

        violations
    }

    fn has_adequate_data_integrity_controls(&self, context: &AuditContext) -> bool {
        // Check if cryptographic integrity is enabled for financial data
        context.security.audit_requirements.integrity_protection
            && matches!(
                context.security.classification,
                SecurityClassification::MaterialTransaction
            )
    }

    fn has_segregation_of_duties(&self, context: &AuditContext) -> bool {
        context.security.access_control.segregation_of_duties
    }
}

#[async_trait::async_trait]
impl ComplianceValidator for SoxValidator {
    async fn validate_operation(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceValidationResult> {
        let mut violations = Vec::new();
        let mut warnings = Vec::new();

        if self.config.financial_data_validation {
            violations.extend(self.validate_financial_data_controls(context));
        }

        // Check audit trail requirements
        if context.security.audit_requirements.retention_days < 2555 {
            warnings.push(ComplianceWarning {
                warning_id: "SOX-AUDIT-001".to_string(),
                title: "Audit Retention Below Recommended".to_string(),
                description:
                    "Audit retention period is less than 7 years recommended for SOX compliance"
                        .to_string(),
                recommendation: "Set audit retention to at least 2555 days (7 years)".to_string(),
            });
        }

        Ok(ComplianceValidationResult {
            violations,
            warnings,
        })
    }

    async fn generate_recommendations(
        &self,
        context: &AuditContext,
    ) -> AuditResult<Vec<ComplianceRecommendation>> {
        let mut recommendations = Vec::new();

        if self.config.executive_certification_required
            && matches!(
                context.security.classification,
                SecurityClassification::MaterialTransaction
            )
        {
            recommendations.push(ComplianceRecommendation {
                recommendation_id: "SOX-REC-001".to_string(),
                priority: RecommendationPriority::High,
                title: "Implement Executive Certification Process".to_string(),
                description:
                    "Establish automated executive certification for financial data processing"
                        .to_string(),
                implementation_effort: "2-3 weeks".to_string(),
                compliance_benefit:
                    "Ensures SOX Section 302 compliance for executive accountability".to_string(),
            });
        }

        if self.config.quarterly_reporting {
            recommendations.push(ComplianceRecommendation {
                recommendation_id: "SOX-REC-002".to_string(),
                priority: RecommendationPriority::Medium,
                title: "Quarterly Compliance Reporting".to_string(),
                description: "Implement automated quarterly compliance reporting for SOX audits"
                    .to_string(),
                implementation_effort: "1-2 weeks".to_string(),
                compliance_benefit: "Streamlines SOX audit process and reduces compliance burden"
                    .to_string(),
            });
        }

        Ok(recommendations)
    }
}

/// HIPAA compliance validator
#[derive(Default)]
pub struct HipaaValidator {
    config: HipaaConfig,
}

impl HipaaValidator {
    /// Creates a new HIPAA compliance validator with the given configuration.
    pub fn new(config: HipaaConfig) -> Self {
        Self { config }
    }

    fn validate_phi_protection(&self, context: &AuditContext) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // HIPAA Security Rule: Administrative Safeguards
        if !self.has_adequate_administrative_safeguards(context) {
            violations.push(ComplianceViolation {
                violation_id: "HIPAA-ADMIN-001".to_string(),
                regulation: "HIPAA Security Rule §164.308(a)".to_string(),
                severity: ComplianceSeverity::High,
                title: "Inadequate Administrative Safeguards".to_string(),
                description: "PHI processing lacks required administrative safeguards".to_string(),
                remediation:
                    "Implement role-based access control and user training for PHI handling"
                        .to_string(),
                reference_url: Some(
                    "https://www.hhs.gov/hipaa/for-professionals/security/index.html".to_string(),
                ),
            });
        }

        // HIPAA Security Rule: Technical Safeguards
        if self.config.phi_encryption_required && !self.has_adequate_technical_safeguards(context) {
            violations.push(ComplianceViolation {
                violation_id: "HIPAA-TECH-001".to_string(),
                regulation: "HIPAA Security Rule §164.312".to_string(),
                severity: ComplianceSeverity::Critical,
                title: "Inadequate Technical Safeguards".to_string(),
                description: "PHI processing lacks required encryption and access controls"
                    .to_string(),
                remediation: "Implement AES-256 encryption and comprehensive access logging"
                    .to_string(),
                reference_url: Some(
                    "https://www.hhs.gov/hipaa/for-professionals/security/index.html".to_string(),
                ),
            });
        }

        violations
    }

    fn has_adequate_administrative_safeguards(&self, context: &AuditContext) -> bool {
        context.security.access_control.role_based_access &&
        context.security.access_control.authorization_required &&
        context.security.access_control.multi_factor_authentication && // PHI requires MFA
        context.metadata.contains_key("phi_access_justification") // PHI access must be justified
    }

    fn has_adequate_technical_safeguards(&self, context: &AuditContext) -> bool {
        matches!(
            context.security.encryption.at_rest,
            super::context::EncryptionStandard::AES256
        ) && context.security.audit_requirements.comprehensive_logging
    }
}

#[async_trait::async_trait]
impl ComplianceValidator for HipaaValidator {
    async fn validate_operation(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceValidationResult> {
        let mut violations = Vec::new();
        let mut warnings = Vec::new();

        // Only validate if PHI is involved
        if matches!(context.security.classification, SecurityClassification::PHI) {
            violations.extend(self.validate_phi_protection(context));

            // Check minimum necessary requirement
            if self.config.minimum_necessary_enforcement
                && !context
                    .metadata
                    .contains_key("minimum_necessary_justification")
            {
                warnings.push(ComplianceWarning {
                    warning_id: "HIPAA-MIN-001".to_string(),
                    title: "Minimum Necessary Justification Missing".to_string(),
                    description: "PHI processing should include minimum necessary justification"
                        .to_string(),
                    recommendation: "Add minimum necessary justification to audit context metadata"
                        .to_string(),
                });
            }
        }

        Ok(ComplianceValidationResult {
            violations,
            warnings,
        })
    }

    async fn generate_recommendations(
        &self,
        context: &AuditContext,
    ) -> AuditResult<Vec<ComplianceRecommendation>> {
        let mut recommendations = Vec::new();

        if self.config.breach_notification_automation
            && matches!(context.security.classification, SecurityClassification::PHI)
        {
            recommendations.push(ComplianceRecommendation {
                recommendation_id: "HIPAA-REC-001".to_string(),
                priority: RecommendationPriority::High,
                title: "Implement Breach Detection Automation".to_string(),
                description:
                    "Automated monitoring for potential PHI breaches with notification workflows"
                        .to_string(),
                implementation_effort: "3-4 weeks".to_string(),
                compliance_benefit: "Ensures HIPAA Breach Notification Rule compliance".to_string(),
            });
        }

        Ok(recommendations)
    }
}

/// GDPR compliance validator
#[derive(Default)]
pub struct GdprValidator {
    config: GdprConfig,
}

impl GdprValidator {
    /// Creates a new GDPR compliance validator with the given configuration.
    pub fn new(config: GdprConfig) -> Self {
        Self { config }
    }

    fn validate_data_protection_principles(
        &self,
        context: &AuditContext,
    ) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // GDPR Article 5: Principles of data processing
        if self.config.legal_basis_validation && !self.has_legal_basis_documentation(context) {
            violations.push(ComplianceViolation {
                violation_id: "GDPR-ART5-001".to_string(),
                regulation: "GDPR Article 5(1)(a)".to_string(),
                severity: ComplianceSeverity::High,
                title: "Legal Basis Not Documented".to_string(),
                description: "Personal data processing lacks documented legal basis".to_string(),
                remediation: "Document legal basis for processing in audit context metadata"
                    .to_string(),
                reference_url: Some(
                    "https://gdpr.eu/article-5-how-to-process-personal-data/".to_string(),
                ),
            });
        }

        // GDPR Article 25: Data protection by design
        if !self.has_data_minimization_controls(context) {
            violations.push(ComplianceViolation {
                violation_id: "GDPR-ART25-001".to_string(),
                regulation: "GDPR Article 25".to_string(),
                severity: ComplianceSeverity::Medium,
                title: "Data Minimization Controls Missing".to_string(),
                description: "Processing does not implement data minimization by design"
                    .to_string(),
                remediation:
                    "Implement data minimization controls to process only necessary personal data"
                        .to_string(),
                reference_url: Some(
                    "https://gdpr.eu/article-25-data-protection-by-design/".to_string(),
                ),
            });
        }

        violations
    }

    fn has_legal_basis_documentation(&self, context: &AuditContext) -> bool {
        context.metadata.contains_key("gdpr_legal_basis")
            || context.metadata.contains_key("processing_purpose")
    }

    fn has_data_minimization_controls(&self, context: &AuditContext) -> bool {
        // Check if processing configuration indicates data minimization
        context.processing_config.batch_size.is_some() // Simple check for controlled processing
    }
}

#[async_trait::async_trait]
impl ComplianceValidator for GdprValidator {
    async fn validate_operation(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceValidationResult> {
        let mut violations = Vec::new();
        let mut warnings = Vec::new();

        violations.extend(self.validate_data_protection_principles(context));

        // Check data subject rights support
        if !context.metadata.contains_key("data_subject_rights_enabled") {
            warnings.push(ComplianceWarning {
                warning_id: "GDPR-DSR-001".to_string(),
                title: "Data Subject Rights Support Not Indicated".to_string(),
                description:
                    "Processing should support data subject rights (access, rectification, erasure)"
                        .to_string(),
                recommendation: "Implement data subject rights handling capabilities".to_string(),
            });
        }

        Ok(ComplianceValidationResult {
            violations,
            warnings,
        })
    }

    async fn generate_recommendations(
        &self,
        _context: &AuditContext,
    ) -> AuditResult<Vec<ComplianceRecommendation>> {
        let mut recommendations = Vec::new();
        if self.config.data_subject_rights_automation {
            recommendations.push(ComplianceRecommendation {
                recommendation_id: "GDPR-REC-001".to_string(),
                priority: RecommendationPriority::High,
                title: "Implement Data Subject Rights Portal".to_string(),
                description:
                    "Automated portal for data subject access, rectification, and erasure requests"
                        .to_string(),
                implementation_effort: "4-6 weeks".to_string(),
                compliance_benefit:
                    "Ensures GDPR Articles 15-17 compliance for data subject rights".to_string(),
            });
        }
        Ok(recommendations)
    }
}

/// PCI DSS compliance validator
#[derive(Default)]
pub struct PciDssValidator {
    config: PciDssConfig,
}

impl PciDssValidator {
    /// Creates a new PCI DSS compliance validator with the given configuration.
    pub fn new(config: PciDssConfig) -> Self {
        Self { config }
    }

    /// Validate PCI DSS Requirement 3: Protect stored cardholder data
    fn validate_cardholder_data_protection(
        &self,
        context: &AuditContext,
    ) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // PCI DSS Requirement 3.1: Keep cardholder data storage to a minimum
        if self.config.cardholder_data_validation
            && context.metadata.contains_key("stores_full_pan")
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-3.1-001".to_string(),
                regulation: "PCI DSS Requirement 3.1".to_string(),
                severity: ComplianceSeverity::Critical,
                title: "Full PAN Storage Detected".to_string(),
                description: "Full Primary Account Number (PAN) is being stored in violation of PCI DSS data minimization requirements".to_string(),
                remediation: "Implement PAN truncation (display only first 6 and last 4 digits) or use tokenization".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        // PCI DSS Requirement 3.2: Render PAN unreadable
        if self.config.cardholder_data_validation && !context.security.encryption.at_rest_encrypted
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-3.2-001".to_string(),
                regulation: "PCI DSS Requirement 3.2".to_string(),
                severity: ComplianceSeverity::Critical,
                title: "Cardholder Data Not Encrypted at Rest".to_string(),
                description: "Cardholder data is stored without encryption at rest".to_string(),
                remediation: "Implement strong cryptography (AES-256 or equivalent) for all cardholder data at rest".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        // PCI DSS Requirement 3.4: Render PAN unreadable when displayed
        if self.config.cardholder_data_validation
            && context.metadata.contains_key("displays_full_pan")
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-3.4-001".to_string(),
                regulation: "PCI DSS Requirement 3.4".to_string(),
                severity: ComplianceSeverity::High,
                title: "Full PAN Displayed in Logs/UI".to_string(),
                description: "Full PAN is displayed in logs or user interface in violation of PCI DSS masking requirements".to_string(),
                remediation: "Implement PAN masking to display only first 6 and last 4 digits (e.g., XXXXXX123456XXXX)".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        // PCI DSS Requirement 3.5: Protect cryptographic keys
        if self.config.cardholder_data_validation
            && context.security.encryption.at_rest_encrypted
            && !context.security.audit_requirements.key_management
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-3.5-001".to_string(),
                regulation: "PCI DSS Requirement 3.5".to_string(),
                severity: ComplianceSeverity::Critical,
                title: "Inadequate Key Management".to_string(),
                description: "Cryptographic keys are not properly managed according to PCI DSS requirements".to_string(),
                remediation: "Implement secure key generation, distribution, storage, rotation, and destruction processes".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        violations
    }

    /// Validate PCI DSS Requirement 4: Encrypt transmission of cardholder data
    fn validate_transmission_encryption(&self, context: &AuditContext) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // PCI DSS Requirement 4.1: Use strong cryptography
        if self.config.cardholder_data_validation
            && context.metadata.contains_key("transmits_cardholder_data")
            && !context.security.encryption.transit_encrypted
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-4.1-001".to_string(),
                regulation: "PCI DSS Requirement 4.1".to_string(),
                severity: ComplianceSeverity::Critical,
                title: "Unencrypted Cardholder Data Transmission".to_string(),
                description: "Cardholder data is transmitted over open networks without encryption".to_string(),
                remediation: "Implement TLS 1.2 or higher with strong cipher suites for all cardholder data transmission".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        violations
    }

    /// Validate PCI DSS Requirement 7: Restrict access to cardholder data
    fn validate_access_controls(&self, context: &AuditContext) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // PCI DSS Requirement 7.1: Limit access based on need-to-know
        if self.config.cardholder_data_validation
            && !context.security.access_control.role_based_access
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-7.1-001".to_string(),
                regulation: "PCI DSS Requirement 7.1".to_string(),
                severity: ComplianceSeverity::High,
                title: "Inadequate Access Control".to_string(),
                description:
                    "Access to cardholder data is not restricted based on business need-to-know"
                        .to_string(),
                remediation: "Implement role-based access control with least privilege principles"
                    .to_string(),
                reference_url: Some(
                    "https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string(),
                ),
            });
        }

        // PCI DSS Requirement 8.2: Identify and authenticate access
        if self.config.mfa_required && !context.security.access_control.multi_factor_authentication
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-8.2-001".to_string(),
                regulation: "PCI DSS Requirement 8.2".to_string(),
                severity: ComplianceSeverity::High,
                title: "Missing Multi-Factor Authentication".to_string(),
                description:
                    "Multi-factor authentication is not required for access to cardholder data"
                        .to_string(),
                remediation: "Implement MFA for all access to cardholder data environments"
                    .to_string(),
                reference_url: Some(
                    "https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string(),
                ),
            });
        }

        violations
    }

    /// Validate PCI DSS Requirement 10: Track and monitor all access
    fn validate_audit_logging(&self, context: &AuditContext) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        // PCI DSS Requirement 10.1: Implement audit trails
        if self.config.cardholder_data_validation
            && !context.security.audit_requirements.comprehensive_logging
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-10.1-001".to_string(),
                regulation: "PCI DSS Requirement 10.1".to_string(),
                severity: ComplianceSeverity::High,
                title: "Inadequate Audit Trails".to_string(),
                description: "Comprehensive audit trails for all access to cardholder data are not implemented".to_string(),
                remediation: "Implement audit trails that record all access to cardholder data, including user identity, timestamp, and action".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        // PCI DSS Requirement 10.5.1: Secure audit trails
        if self.config.cardholder_data_validation
            && !context.security.audit_requirements.integrity_protection
        {
            violations.push(ComplianceViolation {
                violation_id: "PCI-10.5.1-001".to_string(),
                regulation: "PCI DSS Requirement 10.5.1".to_string(),
                severity: ComplianceSeverity::High,
                title: "Audit Trail Integrity Not Protected".to_string(),
                description: "Audit trails are not protected against tampering or unauthorized modification".to_string(),
                remediation: "Implement cryptographic integrity checks and immutable logging for audit trails".to_string(),
                reference_url: Some("https://www.pcisecuritystandards.org/documents/PCI_DSS_v4-0.pdf".to_string()),
            });
        }

        violations
    }
}

#[async_trait::async_trait]
impl ComplianceValidator for PciDssValidator {
    async fn validate_operation(
        &self,
        context: &AuditContext,
    ) -> AuditResult<ComplianceValidationResult> {
        let mut violations = Vec::new();
        let mut warnings = Vec::new();

        // Only validate if cardholder data is involved
        if self.config.cardholder_data_validation
            && (context.metadata.contains_key("has_cardholder_data")
                || context.metadata.contains_key("stores_full_pan")
                || context.metadata.contains_key("transmits_cardholder_data"))
        {
            violations.extend(self.validate_cardholder_data_protection(context));
            violations.extend(self.validate_transmission_encryption(context));
            violations.extend(self.validate_access_controls(context));
            violations.extend(self.validate_audit_logging(context));

            // PCI DSS Requirement 12: Maintain information security policy
            if !context.metadata.contains_key("pci_security_policy") {
                warnings.push(ComplianceWarning {
                    warning_id: "PCI-12-001".to_string(),
                    title: "Security Policy Not Documented".to_string(),
                    description: "PCI DSS security policy documentation is not referenced".to_string(),
                    recommendation: "Ensure PCI DSS information security policy is documented and communicated to all personnel".to_string(),
                });
            }
        }

        Ok(ComplianceValidationResult {
            violations,
            warnings,
        })
    }

    async fn generate_recommendations(
        &self,
        context: &AuditContext,
    ) -> AuditResult<Vec<ComplianceRecommendation>> {
        let mut recommendations = Vec::new();

        if self.config.cardholder_data_validation
            && (context.metadata.contains_key("has_cardholder_data")
                || context.metadata.contains_key("stores_full_pan"))
        {
            recommendations.push(ComplianceRecommendation {
                recommendation_id: "PCI-REC-001".to_string(),
                priority: RecommendationPriority::Critical,
                title: "Implement Tokenization for Cardholder Data".to_string(),
                description: "Replace sensitive cardholder data with non-sensitive equivalents (tokens) to reduce PCI DSS scope".to_string(),
                implementation_effort: "4-6 weeks".to_string(),
                compliance_benefit: "Significantly reduces PCI DSS compliance scope and risk exposure".to_string(),
            });

            recommendations.push(ComplianceRecommendation {
                recommendation_id: "PCI-REC-002".to_string(),
                priority: RecommendationPriority::High,
                title: "Implement Continuous Compliance Monitoring".to_string(),
                description: "Deploy automated monitoring for PCI DSS compliance with real-time violation detection".to_string(),
                implementation_effort: "3-4 weeks".to_string(),
                compliance_benefit: "Ensures ongoing PCI DSS compliance and reduces audit preparation time".to_string(),
            });
        }

        Ok(recommendations)
    }
}

// Configuration structures

/// Configuration for all compliance framework validators.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceConfig {
    /// Number of days between scheduled compliance reviews.
    pub review_interval_days: Option<u32>,
    /// SOX-specific compliance settings.
    pub sox: SoxConfig,
    /// HIPAA-specific compliance settings.
    pub hipaa: HipaaConfig,
    /// GDPR-specific compliance settings.
    pub gdpr: GdprConfig,
    /// PCI DSS-specific compliance settings.
    pub pci_dss: PciDssConfig,
}

impl Default for ComplianceConfig {
    fn default() -> Self {
        Self {
            review_interval_days: Some(90),
            sox: SoxConfig::default(),
            hipaa: HipaaConfig::default(),
            gdpr: GdprConfig::default(),
            pci_dss: PciDssConfig::default(),
        }
    }
}

/// Configuration for SOX (Sarbanes-Oxley) compliance validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SoxConfig {
    /// Whether to validate financial data integrity controls.
    pub financial_data_validation: bool,
    /// Whether executive certification is required for financial data.
    pub executive_certification_required: bool,
    /// Whether to enforce quarterly compliance reporting.
    pub quarterly_reporting: bool,
}

impl Default for SoxConfig {
    fn default() -> Self {
        Self {
            financial_data_validation: true,
            executive_certification_required: true,
            quarterly_reporting: true,
        }
    }
}

/// Configuration for HIPAA compliance validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HipaaConfig {
    /// Whether PHI encryption at rest is required.
    pub phi_encryption_required: bool,
    /// Whether automated breach notification is enabled.
    pub breach_notification_automation: bool,
    /// Whether minimum-necessary access enforcement is enabled.
    pub minimum_necessary_enforcement: bool,
}

impl Default for HipaaConfig {
    fn default() -> Self {
        Self {
            phi_encryption_required: true,
            breach_notification_automation: true,
            minimum_necessary_enforcement: true,
        }
    }
}

/// Configuration for GDPR compliance validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GdprConfig {
    /// Whether legal basis documentation is validated.
    pub legal_basis_validation: bool,
    /// Whether automated data subject rights handling is enabled.
    pub data_subject_rights_automation: bool,
}

impl Default for GdprConfig {
    fn default() -> Self {
        Self {
            legal_basis_validation: true,
            data_subject_rights_automation: true,
        }
    }
}

/// Configuration for PCI DSS compliance validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PciDssConfig {
    /// Whether cardholder data protection rules are validated.
    pub cardholder_data_validation: bool,
    /// Whether multi-factor authentication is required.
    pub mfa_required: bool,
}

impl Default for PciDssConfig {
    fn default() -> Self {
        Self {
            cardholder_data_validation: true,
            mfa_required: true,
        }
    }
}

// Result structures

/// Aggregated result from compliance validation across all profiles.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceResult {
    /// Overall compliance status.
    pub status: ComplianceStatus,
    /// List of compliance violations found.
    pub violations: Vec<ComplianceViolation>,
    /// List of compliance warnings found.
    pub warnings: Vec<ComplianceWarning>,
    /// Profiles that were validated.
    pub validated_profiles: Vec<ComplianceProfile>,
    /// ISO 8601 timestamp of when validation was performed.
    pub validation_timestamp: String,
}

impl ComplianceResult {
    /// Returns `true` if the result indicates a compliant or compliant-with-warnings status.
    pub fn is_compliant(&self) -> bool {
        matches!(
            self.status,
            ComplianceStatus::Compliant | ComplianceStatus::CompliantWithWarnings
        )
    }

    /// Returns `true` if any violation has critical severity.
    pub fn has_critical_violations(&self) -> bool {
        self.violations
            .iter()
            .any(|v| matches!(v.severity, ComplianceSeverity::Critical))
    }
}

/// Overall compliance status after validation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ComplianceStatus {
    /// All checks passed with no violations or warnings.
    Compliant,
    /// No violations but advisory warnings exist.
    CompliantWithWarnings,
    /// One or more compliance violations were found.
    NonCompliant,
}

/// A specific compliance violation with remediation guidance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceViolation {
    /// Unique identifier for this violation.
    pub violation_id: String,
    /// Regulatory reference (e.g., "SOX Section 302").
    pub regulation: String,
    /// Severity level of the violation.
    pub severity: ComplianceSeverity,
    /// Short title describing the violation.
    pub title: String,
    /// Detailed description of the violation.
    pub description: String,
    /// Recommended remediation steps.
    pub remediation: String,
    /// Optional URL to the relevant regulation or standard.
    pub reference_url: Option<String>,
}

/// Severity level for a compliance violation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ComplianceSeverity {
    /// Low-impact informational finding.
    Low,
    /// Moderate risk requiring attention.
    Medium,
    /// High-risk violation requiring prompt remediation.
    High,
    /// Critical violation requiring immediate action.
    Critical,
}

/// An advisory compliance warning that does not block processing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceWarning {
    /// Unique identifier for this warning.
    pub warning_id: String,
    /// Short title describing the warning.
    pub title: String,
    /// Detailed description of the warning.
    pub description: String,
    /// Recommended action to address the warning.
    pub recommendation: String,
}

/// Raw validation output from a single compliance validator.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceValidationResult {
    /// Violations discovered during validation.
    pub violations: Vec<ComplianceViolation>,
    /// Warnings discovered during validation.
    pub warnings: Vec<ComplianceWarning>,
}

/// Full compliance report including validation results and recommendations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceReport {
    /// Unique identifier for this report.
    pub report_id: String,
    /// Identifier of the audited operation.
    pub operation_id: String,
    /// Aggregated compliance validation result.
    pub compliance_result: ComplianceResult,
    /// Actionable recommendations for improving compliance.
    pub recommendations: Vec<ComplianceRecommendation>,
    /// ISO 8601 date of the next scheduled review.
    pub next_review_date: String,
    /// ISO 8601 timestamp when this report was created.
    pub created_at: String,
}

/// A compliance recommendation with implementation guidance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceRecommendation {
    /// Unique identifier for this recommendation.
    pub recommendation_id: String,
    /// Priority level for implementation.
    pub priority: RecommendationPriority,
    /// Short title describing the recommendation.
    pub title: String,
    /// Detailed description of the recommendation.
    pub description: String,
    /// Estimated effort to implement (e.g., "2-3 weeks").
    pub implementation_effort: String,
    /// Expected compliance benefit from implementation.
    pub compliance_benefit: String,
}

/// Priority level for a compliance recommendation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RecommendationPriority {
    /// Low priority — address when convenient.
    Low,
    /// Medium priority — plan for near-term resolution.
    Medium,
    /// High priority — address promptly.
    High,
    /// Critical priority — requires immediate action.
    Critical,
}

/// Patterns per compliance profile for sensitive field detection
fn sensitive_patterns_for_profile(profile: ComplianceProfile) -> &'static [&'static str] {
    match profile {
        ComplianceProfile::SOX => &["ACCOUNT", "BALANCE", "TRANSACTION", "LEDGER", "REVENUE"],
        ComplianceProfile::HIPAA => &["SSN", "DOB", "PATIENT", "DIAGNOSIS", "INSURANCE", "MEDICAL"],
        ComplianceProfile::PciDss => &["CARD", "PAN", "CVV", "EXPIRY", "CVC"],
        ComplianceProfile::GDPR => &[
            "NAME",
            "ADDRESS",
            "EMAIL",
            "PHONE",
            "NATIONAL-ID",
            "PASSPORT",
        ],
    }
}

fn check_field_against_profiles(
    field: &Field,
    profiles: &[ComplianceProfile],
    warnings: &mut Vec<ComplianceWarning>,
) {
    let upper_name = field.name.to_ascii_uppercase();
    for &profile in profiles {
        for &pattern in sensitive_patterns_for_profile(profile) {
            if upper_name.contains(pattern) {
                warnings.push(ComplianceWarning {
                    warning_id: format!("{:?}-FIELD-{}", profile, field.name),
                    title: format!("Sensitive field detected ({profile:?})"),
                    description: format!(
                        "Field '{}' matches {profile:?} sensitive pattern '{pattern}'",
                        field.name,
                    ),
                    recommendation: format!(
                        "Review field '{}' to ensure {profile:?} compliance requirements are met",
                        field.name,
                    ),
                });
                // Only emit one warning per (field, profile) pair
                break;
            }
        }
    }
    // Recurse into children
    for child in &field.children {
        check_field_against_profiles(child, profiles, warnings);
    }
}

/// Detect fields in a schema that may contain regulated data under the given compliance profiles.
///
/// Recursively inspects all fields (including group children) and emits a [`ComplianceWarning`]
/// for each field name that matches a profile-specific sensitive-data pattern.
pub fn detect_sensitive_fields(
    fields: &[Field],
    profiles: &[ComplianceProfile],
) -> Vec<ComplianceWarning> {
    let mut warnings = Vec::new();
    for field in fields {
        check_field_against_profiles(field, profiles, &mut warnings);
    }
    warnings
}

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

    #[test]
    fn test_compliance_engine_creation() {
        let engine = ComplianceEngine::default()
            .with_profiles(&[ComplianceProfile::SOX, ComplianceProfile::HIPAA]);

        assert_eq!(engine.profiles.len(), 2);
        assert!(engine.profiles.contains(&ComplianceProfile::SOX));
        assert!(engine.profiles.contains(&ComplianceProfile::HIPAA));
    }

    #[tokio::test]
    async fn test_sox_compliance_validation() {
        let context = AuditContext::new()
            .with_security_classification(SecurityClassification::MaterialTransaction);

        let sox_validator = SoxValidator::new(SoxConfig::default());
        let result = sox_validator
            .validate_operation(&context)
            .await
            .expect("SOX validation should not fail in test environment");

        // Should have violations due to missing controls in default context
        assert!(!result.violations.is_empty());
    }

    #[tokio::test]
    async fn test_hipaa_compliance_validation() {
        let context = AuditContext::new().with_security_classification(SecurityClassification::PHI);

        let hipaa_validator = HipaaValidator::new(HipaaConfig::default());
        let result = hipaa_validator
            .validate_operation(&context)
            .await
            .expect("HIPAA validation should not fail in test environment");

        // Should have violations due to missing PHI protections in default context
        assert!(!result.violations.is_empty());
    }

    #[tokio::test]
    async fn test_pci_dss_compliance_validation() {
        let mut context = AuditContext::new()
            .with_metadata("has_cardholder_data", "true")
            .with_metadata("stores_full_pan", "true");

        // Set up context with violations
        context.security.encryption.at_rest_encrypted = false;
        context.security.access_control.multi_factor_authentication = false;

        let pci_validator = PciDssValidator::new(PciDssConfig::default());
        let result = pci_validator
            .validate_operation(&context)
            .await
            .expect("PCI DSS validation should not fail in test environment");

        // Should have violations due to missing PCI DSS protections
        assert!(!result.violations.is_empty());

        // Check for specific violations
        let has_pan_storage_violation = result
            .violations
            .iter()
            .any(|v| v.violation_id == "PCI-3.1-001");
        assert!(
            has_pan_storage_violation,
            "Should detect full PAN storage violation"
        );

        let has_encryption_violation = result
            .violations
            .iter()
            .any(|v| v.violation_id == "PCI-3.2-001");
        assert!(
            has_encryption_violation,
            "Should detect encryption violation"
        );

        let has_mfa_violation = result
            .violations
            .iter()
            .any(|v| v.violation_id == "PCI-8.2-001");
        assert!(has_mfa_violation, "Should detect MFA violation");
    }

    #[tokio::test]
    async fn test_pci_dss_compliant_context() {
        let mut context = AuditContext::new()
            .with_metadata("has_cardholder_data", "true")
            .with_metadata("pci_security_policy", "documented");

        // Set up context with proper protections
        context.security.encryption.at_rest_encrypted = true;
        context.security.encryption.transit_encrypted = true;
        context.security.access_control.multi_factor_authentication = true;
        context.security.access_control.role_based_access = true;
        context.security.audit_requirements.comprehensive_logging = true;
        context.security.audit_requirements.integrity_protection = true;
        context.security.audit_requirements.key_management = true;

        let pci_validator = PciDssValidator::new(PciDssConfig::default());
        let result = pci_validator
            .validate_operation(&context)
            .await
            .expect("PCI DSS validation should not fail in test environment");

        // Should have no violations with proper protections
        assert!(
            result.violations.is_empty(),
            "Should be compliant with proper protections"
        );
    }

    #[tokio::test]
    async fn test_pci_dss_recommendations() {
        let context = AuditContext::new()
            .with_metadata("has_cardholder_data", "true")
            .with_metadata("stores_full_pan", "true");

        let pci_validator = PciDssValidator::new(PciDssConfig::default());
        let recommendations = pci_validator
            .generate_recommendations(&context)
            .await
            .expect("PCI DSS recommendations should not fail in test environment");

        // Should have recommendations for cardholder data
        assert!(!recommendations.is_empty());

        let has_tokenization_rec = recommendations
            .iter()
            .any(|r| r.recommendation_id == "PCI-REC-001");
        assert!(has_tokenization_rec, "Should recommend tokenization");

        let has_monitoring_rec = recommendations
            .iter()
            .any(|r| r.recommendation_id == "PCI-REC-002");
        assert!(has_monitoring_rec, "Should recommend continuous monitoring");
    }

    #[test]
    fn test_compliance_result_status() {
        let compliant_result = ComplianceResult {
            status: ComplianceStatus::Compliant,
            violations: Vec::new(),
            warnings: Vec::new(),
            validated_profiles: vec![ComplianceProfile::SOX],
            validation_timestamp: chrono::Utc::now().to_rfc3339(),
        };

        assert!(compliant_result.is_compliant());
        assert!(!compliant_result.has_critical_violations());

        let non_compliant_result = ComplianceResult {
            status: ComplianceStatus::NonCompliant,
            violations: vec![ComplianceViolation {
                violation_id: "TEST-001".to_string(),
                regulation: "Test Regulation".to_string(),
                severity: ComplianceSeverity::Critical,
                title: "Test Violation".to_string(),
                description: "Test Description".to_string(),
                remediation: "Test Remediation".to_string(),
                reference_url: None,
            }],
            warnings: Vec::new(),
            validated_profiles: vec![ComplianceProfile::SOX],
            validation_timestamp: chrono::Utc::now().to_rfc3339(),
        };

        assert!(!non_compliant_result.is_compliant());
        assert!(non_compliant_result.has_critical_violations());
    }

    #[test]
    fn test_calculate_next_review_date_arithmetic() {
        let engine = ComplianceEngine::default();

        // Test default 90-day calculation
        let review_date = engine.calculate_next_review_date();
        let current_time = chrono::Utc::now();

        // Parse the returned date to verify arithmetic
        let parsed_review_date = chrono::DateTime::parse_from_rfc3339(&review_date)
            .expect("Review date should be valid RFC3339 format in test");
        let actual_timestamp = parsed_review_date.timestamp();

        // Should be approximately 90 days (allow small variance for execution time)
        let days_diff = (actual_timestamp - current_time.timestamp()) / (24 * 3600);
        assert!(
            days_diff >= 89,
            "Review date should be at least 89 days from now"
        );
        assert!(
            days_diff <= 91,
            "Review date should be at most 91 days from now"
        );

        // Test custom review interval arithmetic
        let custom_config = ComplianceConfig {
            review_interval_days: Some(365), // 1 year
            ..Default::default()
        };
        let custom_engine = ComplianceEngine::new(custom_config);
        let custom_review_date = custom_engine.calculate_next_review_date();

        let parsed_custom_date = chrono::DateTime::parse_from_rfc3339(&custom_review_date)
            .expect("Custom review date should be valid RFC3339 format in test");
        let custom_days_diff =
            (parsed_custom_date.timestamp() - current_time.timestamp()) / (24 * 3600);
        assert!(
            custom_days_diff >= 364,
            "Custom review date should be at least 364 days from now"
        );
        assert!(
            custom_days_diff <= 366,
            "Custom review date should be at most 366 days from now"
        );
    }

    #[tokio::test]
    async fn test_sox_retention_calculation_logic() {
        // Test the specific arithmetic operation in line 237: retention_days < 2555
        // Create a context with retention exactly at threshold (2555)
        let mut context_compliant = AuditContext::new()
            .with_security_classification(SecurityClassification::MaterialTransaction);
        context_compliant.security.audit_requirements.retention_days = 2555; // Exactly the threshold

        let sox_validator = SoxValidator::new(SoxConfig::default());
        let result = sox_validator
            .validate_operation(&context_compliant)
            .await
            .expect("SOX validation should not fail in test with compliant context");

        // At exactly 2555 days, should not trigger warning (not < 2555)
        let retention_warnings: Vec<_> = result
            .warnings
            .iter()
            .filter(|w| w.warning_id == "SOX-AUDIT-001")
            .collect();
        assert!(
            retention_warnings.is_empty(),
            "Should not warn at exactly 2555 days"
        );

        // Test just below threshold
        let mut context_warning = AuditContext::new()
            .with_security_classification(SecurityClassification::MaterialTransaction);
        context_warning.security.audit_requirements.retention_days = 2554; // Just below threshold

        let result_warning = sox_validator
            .validate_operation(&context_warning)
            .await
            .expect("SOX validation should not fail in test with warning context");

        // Should trigger warning when < 2555
        let retention_warnings: Vec<_> = result_warning
            .warnings
            .iter()
            .filter(|w| w.warning_id == "SOX-AUDIT-001")
            .collect();
        assert!(
            !retention_warnings.is_empty(),
            "Should warn when retention < 2555 days"
        );

        // Test well above threshold
        let mut context_good = AuditContext::new()
            .with_security_classification(SecurityClassification::MaterialTransaction);
        context_good.security.audit_requirements.retention_days = 3000; // Well above threshold

        let result_good = sox_validator
            .validate_operation(&context_good)
            .await
            .expect("SOX validation should not fail in test with good context");

        // Should not trigger warning when > 2555
        let retention_warnings_good: Vec<_> = result_good
            .warnings
            .iter()
            .filter(|w| w.warning_id == "SOX-AUDIT-001")
            .collect();
        assert!(
            retention_warnings_good.is_empty(),
            "Should not warn when retention > 2555 days"
        );
    }

    #[test]
    fn test_compliance_status_determination_logic() {
        // Test the arithmetic/logic for determining ComplianceStatus

        // Case 1: Empty violations and warnings -> Compliant
        let mut violations = Vec::new();
        let mut warnings = Vec::new();

        let status = if violations.is_empty() {
            if warnings.is_empty() {
                ComplianceStatus::Compliant
            } else {
                ComplianceStatus::CompliantWithWarnings
            }
        } else {
            ComplianceStatus::NonCompliant
        };
        assert_eq!(status, ComplianceStatus::Compliant);

        // Case 2: No violations but has warnings -> CompliantWithWarnings
        warnings.push(ComplianceWarning {
            warning_id: "TEST-001".to_string(),
            title: "Test Warning".to_string(),
            description: "Test".to_string(),
            recommendation: "Test".to_string(),
        });

        let status = if violations.is_empty() {
            if warnings.is_empty() {
                ComplianceStatus::Compliant
            } else {
                ComplianceStatus::CompliantWithWarnings
            }
        } else {
            ComplianceStatus::NonCompliant
        };
        assert_eq!(status, ComplianceStatus::CompliantWithWarnings);

        // Case 3: Has violations -> NonCompliant
        violations.push(ComplianceViolation {
            violation_id: "TEST-001".to_string(),
            regulation: "Test".to_string(),
            severity: ComplianceSeverity::Medium,
            title: "Test".to_string(),
            description: "Test".to_string(),
            remediation: "Test".to_string(),
            reference_url: None,
        });

        let status = if violations.is_empty() {
            if warnings.is_empty() {
                ComplianceStatus::Compliant
            } else {
                ComplianceStatus::CompliantWithWarnings
            }
        } else {
            ComplianceStatus::NonCompliant
        };
        assert_eq!(status, ComplianceStatus::NonCompliant);
    }

    // Helper to create a minimal leaf Field for testing
    fn make_field(name: &str) -> crate::Field {
        crate::Field {
            path: name.to_string(),
            name: name.to_string(),
            level: 5,
            kind: crate::FieldKind::Alphanum { len: 10 },
            offset: 0,
            len: 10,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: Vec::new(),
        }
    }

    fn make_group(name: &str, children: Vec<crate::Field>) -> crate::Field {
        crate::Field {
            path: name.to_string(),
            name: name.to_string(),
            level: 1,
            kind: crate::FieldKind::Group,
            offset: 0,
            len: 0,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children,
        }
    }

    #[test]
    fn test_detect_sensitive_fields_empty() {
        let warnings = detect_sensitive_fields(&[], &[ComplianceProfile::SOX]);
        assert!(warnings.is_empty(), "No fields means no warnings");
    }

    #[test]
    fn test_detect_sensitive_fields_sox_match() {
        let fields = vec![make_field("ACCOUNT-NUMBER"), make_field("CUSTOMER-NAME")];
        let warnings = detect_sensitive_fields(&fields, &[ComplianceProfile::SOX]);
        assert_eq!(warnings.len(), 1, "Only ACCOUNT-NUMBER should match SOX");
        assert!(warnings[0].warning_id.contains("SOX"));
        assert!(warnings[0].description.contains("ACCOUNT-NUMBER"));
    }

    #[test]
    fn test_detect_sensitive_fields_hipaa_match() {
        let fields = vec![make_field("PATIENT-ID"), make_field("DIAGNOSIS-CODE")];
        let warnings = detect_sensitive_fields(&fields, &[ComplianceProfile::HIPAA]);
        assert_eq!(warnings.len(), 2, "Both fields should match HIPAA");
        let ids: Vec<_> = warnings.iter().map(|w| &w.warning_id).collect();
        assert!(ids.iter().any(|id| id.contains("PATIENT")));
        assert!(ids.iter().any(|id| id.contains("DIAGNOSIS")));
    }

    #[test]
    fn test_detect_sensitive_fields_pci_match() {
        let fields = vec![make_field("CARD-NUM"), make_field("CVV-VALUE")];
        let warnings = detect_sensitive_fields(&fields, &[ComplianceProfile::PciDss]);
        assert_eq!(warnings.len(), 2, "Both fields should match PCI DSS");
    }

    #[test]
    fn test_detect_sensitive_fields_gdpr_match() {
        let fields = vec![make_field("CUSTOMER-EMAIL"), make_field("HOME-ADDRESS")];
        let warnings = detect_sensitive_fields(&fields, &[ComplianceProfile::GDPR]);
        assert_eq!(warnings.len(), 2, "Both fields should match GDPR");
    }

    #[test]
    fn test_detect_sensitive_fields_no_match() {
        let fields = vec![make_field("RECORD-TYPE"), make_field("FILLER")];
        let warnings = detect_sensitive_fields(
            &fields,
            &[
                ComplianceProfile::SOX,
                ComplianceProfile::HIPAA,
                ComplianceProfile::PciDss,
                ComplianceProfile::GDPR,
            ],
        );
        assert!(
            warnings.is_empty(),
            "Generic fields should not match any profile"
        );
    }

    #[test]
    fn test_detect_sensitive_fields_recurses_into_children() {
        let child = make_field("SSN-FIELD");
        let group = make_group("CUSTOMER-RECORD", vec![child]);
        let warnings = detect_sensitive_fields(&[group], &[ComplianceProfile::HIPAA]);
        assert_eq!(warnings.len(), 1, "Should find SSN in nested child");
        assert!(warnings[0].description.contains("SSN-FIELD"));
    }

    #[test]
    fn test_detect_sensitive_fields_multiple_profiles() {
        let fields = vec![make_field("BALANCE"), make_field("PATIENT-NAME")];
        let warnings =
            detect_sensitive_fields(&fields, &[ComplianceProfile::SOX, ComplianceProfile::HIPAA]);
        // BALANCE matches SOX, PATIENT-NAME matches HIPAA
        assert_eq!(warnings.len(), 2);
    }

    #[test]
    fn test_detect_sensitive_fields_case_insensitive() {
        let fields = vec![make_field("account-balance")];
        let warnings = detect_sensitive_fields(&fields, &[ComplianceProfile::SOX]);
        // "account-balance" uppercased contains both "ACCOUNT" and "BALANCE"
        // but we break after the first match per (field, profile)
        assert_eq!(warnings.len(), 1, "Should match case-insensitively");
    }
}