latticearc 0.6.1

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), post-quantum TLS, and FIPS 140-3 backend — one crate, zero unsafe.
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
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
//! # LatticeArc Logging Utilities
//!
//! Security-conscious logging utilities for LatticeArc Core.
//! Provides structured logging with tracing while ensuring no sensitive
//! cryptographic material is logged.
//!
//! ## Security Features
//!
//! - **No Sensitive Data**: Automatic sanitization of cryptographic keys and secrets
//! - **Structured Logging**: Consistent log format across all components
//! - **Performance Conscious**: Minimal overhead in cryptographic operations
//! - **Configurable**: Environment-based log levels and output formats
//!
//! ## Usage
//!
//! ```rust,no_run
//! use latticearc::unified_api::logging::{init_tracing, sanitize_data};
//!
//! // Initialize logging (sets global tracing subscriber — call once per process)
//! init_tracing().expect("Failed to init tracing");
//!
//! // Log with automatic sanitization
//! let key_data = b"sensitive_key_material";
//! tracing::info!("Key operation completed: {}", sanitize_data(key_data));
//! ```

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use tracing::info;
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
use uuid::Uuid;

// ============================================================================
// Key Lifecycle Event Types for Audit Logging
// ============================================================================

/// Key type classification for lifecycle events.
///
/// Distinguishes between different key categories for proper audit logging
/// and compliance reporting.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyType {
    /// Symmetric keys (e.g., AES-256)
    Symmetric,
    /// Asymmetric public keys (can be shared)
    AsymmetricPublic,
    /// Asymmetric private keys (must be protected)
    AsymmetricPrivate,
    /// Complete keypair (public + private)
    KeyPair,
}

impl fmt::Display for KeyType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyType::Symmetric => write!(f, "Symmetric"),
            KeyType::AsymmetricPublic => write!(f, "AsymmetricPublic"),
            KeyType::AsymmetricPrivate => write!(f, "AsymmetricPrivate"),
            KeyType::KeyPair => write!(f, "KeyPair"),
        }
    }
}

/// Key purpose classification per NIST SP 800-57.
///
/// Defines the intended use of a cryptographic key for audit and
/// compliance tracking.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyPurpose {
    /// Key used for encryption operations
    Encryption,
    /// Key used for digital signature creation
    Signing,
    /// Key used for key exchange protocols (e.g., KEM, DH)
    KeyExchange,
    /// Key used for authentication operations
    Authentication,
    /// Key used for wrapping other keys
    KeyWrapping,
}

impl fmt::Display for KeyPurpose {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyPurpose::Encryption => write!(f, "Encryption"),
            KeyPurpose::Signing => write!(f, "Signing"),
            KeyPurpose::KeyExchange => write!(f, "KeyExchange"),
            KeyPurpose::Authentication => write!(f, "Authentication"),
            KeyPurpose::KeyWrapping => write!(f, "KeyWrapping"),
        }
    }
}

/// Reason for key rotation.
///
/// Tracks why a key was rotated for compliance and audit purposes.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RotationReason {
    /// Scheduled rotation per policy
    Scheduled,
    /// Key was potentially compromised
    Compromised,
    /// Policy or compliance requirements changed
    PolicyChange,
    /// Key reached its cryptoperiod end
    Expiration,
    /// Manual rotation by administrator
    Manual,
}

impl fmt::Display for RotationReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RotationReason::Scheduled => write!(f, "Scheduled"),
            RotationReason::Compromised => write!(f, "Compromised"),
            RotationReason::PolicyChange => write!(f, "PolicyChange"),
            RotationReason::Expiration => write!(f, "Expiration"),
            RotationReason::Manual => write!(f, "Manual"),
        }
    }
}

/// Method used for key destruction.
///
/// Documents how key material was destroyed for compliance verification.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DestructionMethod {
    /// Memory zeroization (software)
    Zeroization,
    /// Cryptographic erasure (key deletion from encrypted storage)
    CryptoErase,
    /// Manual destruction by administrator
    Manual,
}

impl fmt::Display for DestructionMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DestructionMethod::Zeroization => write!(f, "Zeroization"),
            DestructionMethod::CryptoErase => write!(f, "CryptoErase"),
            DestructionMethod::Manual => write!(f, "Manual"),
        }
    }
}

/// Key lifecycle events for comprehensive audit logging.
///
/// These events track all significant operations on cryptographic keys
/// throughout their lifecycle, from generation to destruction.
///
/// # Audit Trail Compliance
///
/// This enum supports compliance with:
/// - NIST SP 800-57 (Key Management)
/// - FIPS 140-3 (Cryptographic Module Security)
/// - SOC 2 Type II (Security Controls)
/// - PCI DSS (Payment Card Industry)
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::{KeyLifecycleEvent, KeyType, KeyPurpose};
///
/// let event = KeyLifecycleEvent::Generated {
///     key_id: "key-001".to_string(),
///     algorithm: "ML-KEM-768".to_string(),
///     key_type: KeyType::KeyPair,
///     purpose: KeyPurpose::KeyExchange,
/// };
///
/// // Log the event using the provided macros
/// // log_key_generated!("key-001", "ML-KEM-768", KeyType::KeyPair, KeyPurpose::KeyExchange);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum KeyLifecycleEvent {
    /// Key was generated.
    ///
    /// Logged when new cryptographic key material is created.
    Generated {
        /// Unique identifier for the key
        key_id: String,
        /// Algorithm used (e.g., "ML-KEM-768", "AES-256-GCM")
        algorithm: String,
        /// Type of key generated
        key_type: KeyType,
        /// Intended purpose of the key
        purpose: KeyPurpose,
    },

    /// Key was rotated (old key deprecated, new key active).
    ///
    /// Logged when a key is replaced with a new key while
    /// maintaining service continuity.
    Rotated {
        /// ID of the key being replaced
        old_key_id: String,
        /// ID of the replacement key
        new_key_id: String,
        /// Algorithm (should match for proper rotation)
        algorithm: String,
        /// Reason for the rotation
        reason: RotationReason,
    },

    /// Key was marked as deprecated.
    ///
    /// Logged when a key is scheduled for retirement but
    /// may still be used for decryption of existing data.
    Deprecated {
        /// ID of the deprecated key
        key_id: String,
        /// When the deprecation takes effect
        deprecation_date: DateTime<Utc>,
        /// Human-readable reason for deprecation
        reason: String,
    },

    /// Key was suspended (temporarily disabled).
    ///
    /// Logged when a key is temporarily disabled, typically
    /// due to a suspected security incident.
    Suspended {
        /// ID of the suspended key
        key_id: String,
        /// Reason for suspension
        reason: String,
    },

    /// Key was destroyed/zeroized.
    ///
    /// Logged when key material is permanently destroyed.
    /// This is a critical audit event.
    Destroyed {
        /// ID of the destroyed key
        key_id: String,
        /// Method used for destruction
        method: DestructionMethod,
    },

    /// Key was accessed for an operation.
    ///
    /// Logged when a key is used for a cryptographic operation.
    /// This may be logged at DEBUG level to avoid log volume issues.
    Accessed {
        /// ID of the accessed key
        key_id: String,
        /// Type of operation (e.g., "encrypt", "sign", "decrypt")
        operation: String,
        /// Optional accessor identity (user, service, etc.)
        accessor: Option<String>,
    },

    /// Key was exported (if allowed by policy).
    ///
    /// Logged when a key is exported from the system.
    /// This is a security-sensitive event.
    Exported {
        /// ID of the exported key
        key_id: String,
        /// Export format (e.g., "PEM", "PKCS#12", "raw")
        format: String,
        /// Destination identifier
        destination: String,
    },

    /// Key was imported into the system.
    ///
    /// Logged when external key material is imported.
    Imported {
        /// ID assigned to the imported key
        key_id: String,
        /// Algorithm of the imported key
        algorithm: String,
        /// Source of the key material
        source: String,
    },
}

impl KeyLifecycleEvent {
    /// Get the key ID associated with this event.
    #[must_use]
    pub fn key_id(&self) -> &str {
        match self {
            KeyLifecycleEvent::Generated { key_id, .. }
            | KeyLifecycleEvent::Deprecated { key_id, .. }
            | KeyLifecycleEvent::Suspended { key_id, .. }
            | KeyLifecycleEvent::Destroyed { key_id, .. }
            | KeyLifecycleEvent::Accessed { key_id, .. }
            | KeyLifecycleEvent::Exported { key_id, .. }
            | KeyLifecycleEvent::Imported { key_id, .. } => key_id,
            KeyLifecycleEvent::Rotated { new_key_id, .. } => new_key_id,
        }
    }

    /// Get the event type as a string for logging.
    #[must_use]
    pub fn event_type(&self) -> &'static str {
        match self {
            KeyLifecycleEvent::Generated { .. } => "generated",
            KeyLifecycleEvent::Rotated { .. } => "rotated",
            KeyLifecycleEvent::Deprecated { .. } => "deprecated",
            KeyLifecycleEvent::Suspended { .. } => "suspended",
            KeyLifecycleEvent::Destroyed { .. } => "destroyed",
            KeyLifecycleEvent::Accessed { .. } => "accessed",
            KeyLifecycleEvent::Exported { .. } => "exported",
            KeyLifecycleEvent::Imported { .. } => "imported",
        }
    }

    /// Create a new Generated event.
    #[must_use]
    pub fn generated(
        key_id: impl Into<String>,
        algorithm: impl Into<String>,
        key_type: KeyType,
        purpose: KeyPurpose,
    ) -> Self {
        Self::Generated { key_id: key_id.into(), algorithm: algorithm.into(), key_type, purpose }
    }

    /// Create a new Rotated event.
    #[must_use]
    pub fn rotated(
        old_key_id: impl Into<String>,
        new_key_id: impl Into<String>,
        algorithm: impl Into<String>,
        reason: RotationReason,
    ) -> Self {
        Self::Rotated {
            old_key_id: old_key_id.into(),
            new_key_id: new_key_id.into(),
            algorithm: algorithm.into(),
            reason,
        }
    }

    /// Create a new Destroyed event.
    #[must_use]
    pub fn destroyed(key_id: impl Into<String>, method: DestructionMethod) -> Self {
        Self::Destroyed { key_id: key_id.into(), method }
    }

    /// Create a new Accessed event.
    #[must_use]
    pub fn accessed(
        key_id: impl Into<String>,
        operation: impl Into<String>,
        accessor: Option<String>,
    ) -> Self {
        Self::Accessed { key_id: key_id.into(), operation: operation.into(), accessor }
    }

    /// Create a new Imported event.
    #[must_use]
    pub fn imported(
        key_id: impl Into<String>,
        algorithm: impl Into<String>,
        source: impl Into<String>,
    ) -> Self {
        Self::Imported { key_id: key_id.into(), algorithm: algorithm.into(), source: source.into() }
    }

    /// Create a new Exported event.
    #[must_use]
    pub fn exported(
        key_id: impl Into<String>,
        format: impl Into<String>,
        destination: impl Into<String>,
    ) -> Self {
        Self::Exported {
            key_id: key_id.into(),
            format: format.into(),
            destination: destination.into(),
        }
    }

    /// Create a new Deprecated event.
    #[must_use]
    pub fn deprecated(
        key_id: impl Into<String>,
        deprecation_date: DateTime<Utc>,
        reason: impl Into<String>,
    ) -> Self {
        Self::Deprecated { key_id: key_id.into(), deprecation_date, reason: reason.into() }
    }

    /// Create a new Suspended event.
    #[must_use]
    pub fn suspended(key_id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::Suspended { key_id: key_id.into(), reason: reason.into() }
    }
}

// ============================================================================
// Correlation ID Infrastructure
// ============================================================================
//
// Thread-local correlation ID storage for async context propagation.
// The correlation ID is stored per-thread and can be propagated across async
// task boundaries using the `CorrelationGuard` RAII guard or the
// `with_correlation_id` function.
// ============================================================================

thread_local! {
    static CORRELATION_ID: RefCell<Option<String>> = const { RefCell::new(None) };
}

/// Global counter for generating lightweight correlation IDs.
///
/// This counter is used by [`generate_lightweight_correlation_id`] when
/// UUID generation overhead is not acceptable.
static CORRELATION_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Generate a new correlation ID using UUID v4.
///
/// This function generates a cryptographically random UUID v4 string
/// suitable for distributed tracing and audit logging.
///
/// # Returns
///
/// A UUID v4 string in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::generate_correlation_id;
///
/// let id = generate_correlation_id();
/// assert_eq!(id.len(), 36); // UUID format with hyphens
/// ```
#[must_use]
pub fn generate_correlation_id() -> String {
    Uuid::new_v4().to_string()
}

/// Generate a lightweight correlation ID using an atomic counter.
///
/// This function generates a correlation ID based on an atomic counter,
/// which is faster than UUID generation but provides less uniqueness
/// across distributed systems.
///
/// # Returns
///
/// A string in the format `corr-{counter:016x}`.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::generate_lightweight_correlation_id;
///
/// let id1 = generate_lightweight_correlation_id();
/// let id2 = generate_lightweight_correlation_id();
/// assert_ne!(id1, id2);
/// assert!(id1.starts_with("corr-"));
/// ```
#[must_use]
pub fn generate_lightweight_correlation_id() -> String {
    let counter = CORRELATION_COUNTER.fetch_add(1, Ordering::SeqCst);
    format!("corr-{counter:016x}")
}

/// Set the correlation ID for the current thread/task.
///
/// This function stores a correlation ID in thread-local storage,
/// making it available to all logging calls on the current thread.
///
/// # Arguments
///
/// * `id` - The correlation ID to set.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::{set_correlation_id, current_correlation_id};
///
/// set_correlation_id("request-12345");
/// assert_eq!(current_correlation_id(), Some("request-12345".to_string()));
/// ```
pub fn set_correlation_id(id: impl Into<String>) {
    CORRELATION_ID.with(|cell| {
        *cell.borrow_mut() = Some(id.into());
    });
}

/// Get the current correlation ID, if set.
///
/// This function retrieves the correlation ID from thread-local storage.
///
/// # Returns
///
/// `Some(id)` if a correlation ID is set, `None` otherwise.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::{set_correlation_id, current_correlation_id, clear_correlation_id};
///
/// assert_eq!(current_correlation_id(), None);
/// set_correlation_id("test-id".to_string());
/// assert_eq!(current_correlation_id(), Some("test-id".to_string()));
/// clear_correlation_id();
/// assert_eq!(current_correlation_id(), None);
/// ```
#[must_use]
pub fn current_correlation_id() -> Option<String> {
    CORRELATION_ID.with(|cell| cell.borrow().clone())
}

/// Clear the correlation ID for the current thread.
///
/// This function removes the correlation ID from thread-local storage.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::{set_correlation_id, current_correlation_id, clear_correlation_id};
///
/// set_correlation_id("test-id".to_string());
/// clear_correlation_id();
/// assert_eq!(current_correlation_id(), None);
/// ```
pub fn clear_correlation_id() {
    CORRELATION_ID.with(|cell| {
        *cell.borrow_mut() = None;
    });
}

/// Execute a closure with a specific correlation ID.
///
/// This function sets the correlation ID for the duration of the closure
/// execution, then restores the previous correlation ID (if any) afterward.
///
/// # Arguments
///
/// * `id` - The correlation ID to use during the closure execution.
/// * `f` - The closure to execute.
///
/// # Returns
///
/// The return value of the closure.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::{with_correlation_id, current_correlation_id};
///
/// let result = with_correlation_id("request-123".to_string(), || {
///     assert_eq!(current_correlation_id(), Some("request-123".to_string()));
///     42
/// });
/// assert_eq!(result, 42);
/// assert_eq!(current_correlation_id(), None);
/// ```
pub fn with_correlation_id<F, R>(id: String, f: F) -> R
where
    F: FnOnce() -> R,
{
    let old = current_correlation_id();
    set_correlation_id(id);
    let result = f();
    match old {
        Some(prev_id) => set_correlation_id(prev_id),
        None => clear_correlation_id(),
    }
    result
}

/// RAII guard for correlation ID scope management.
///
/// This guard automatically sets a correlation ID when created and restores
/// the previous correlation ID (if any) when dropped. This is useful for
/// propagating correlation IDs across async task boundaries.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::{CorrelationGuard, current_correlation_id};
///
/// {
///     let guard = CorrelationGuard::new();
///     let id = guard.id();
///     assert!(id.is_some());
///     // Correlation ID is automatically set
/// }
/// // Correlation ID is restored to previous value (None in this case)
/// ```
pub struct CorrelationGuard {
    previous: Option<String>,
}

impl CorrelationGuard {
    /// Create a new correlation scope with an automatically generated UUID v4.
    ///
    /// # Returns
    ///
    /// A new `CorrelationGuard` that sets and manages the correlation ID.
    #[must_use]
    pub fn new() -> Self {
        let previous = current_correlation_id();
        set_correlation_id(generate_correlation_id());
        Self { previous }
    }

    /// Create a new correlation scope with a specific ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The correlation ID to use.
    ///
    /// # Returns
    ///
    /// A new `CorrelationGuard` that sets and manages the correlation ID.
    #[must_use]
    pub fn with_id(id: impl Into<String>) -> Self {
        let previous = current_correlation_id();
        set_correlation_id(id);
        Self { previous }
    }

    /// Create a new correlation scope with a lightweight counter-based ID.
    ///
    /// # Returns
    ///
    /// A new `CorrelationGuard` with a lightweight correlation ID.
    #[must_use]
    pub fn lightweight() -> Self {
        let previous = current_correlation_id();
        set_correlation_id(generate_lightweight_correlation_id());
        Self { previous }
    }

    /// Get the current correlation ID.
    ///
    /// # Returns
    ///
    /// The current correlation ID, if set.
    #[must_use]
    pub fn id(&self) -> Option<String> {
        current_correlation_id()
    }

    /// Get the previous correlation ID that will be restored on drop.
    ///
    /// # Returns
    ///
    /// The previous correlation ID, if any.
    #[must_use]
    pub fn previous_id(&self) -> Option<&String> {
        self.previous.as_ref()
    }
}

impl Drop for CorrelationGuard {
    fn drop(&mut self) {
        match &self.previous {
            Some(id) => set_correlation_id(id.clone()),
            None => clear_correlation_id(),
        }
    }
}

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

// ============================================================================
// Metadata Sanitization Constants and Functions
// ============================================================================

/// Keys that indicate potentially sensitive data.
///
/// Any metadata key containing these patterns (case-insensitive) will be redacted
/// to prevent sensitive data leakage in audit logs.
pub const SENSITIVE_KEY_PATTERNS: &[&str] = &[
    "key",
    "secret",
    "password",
    "token",
    "credential",
    "private",
    "auth",
    "session",
    "bearer",
    "api_key",
    "apikey",
    "passphrase",
];

/// Maximum length for metadata values before truncation.
///
/// Values longer than this will be truncated with a length indicator.
pub const MAX_METADATA_VALUE_LENGTH: usize = 1000;

/// Check if a metadata key might contain sensitive data.
///
/// Performs a case-insensitive check against known sensitive key patterns.
///
/// # Arguments
///
/// * `key` - The metadata key to check
///
/// # Returns
///
/// `true` if the key matches any sensitive pattern, `false` otherwise.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::is_potentially_sensitive;
///
/// assert!(is_potentially_sensitive("api_key"));
/// assert!(is_potentially_sensitive("user_password"));
/// assert!(is_potentially_sensitive("AuthToken"));
/// assert!(!is_potentially_sensitive("username"));
/// assert!(!is_potentially_sensitive("operation_id"));
/// ```
#[must_use]
pub fn is_potentially_sensitive(key: &str) -> bool {
    let lower = key.to_lowercase();
    SENSITIVE_KEY_PATTERNS.iter().any(|pattern| lower.contains(pattern))
}

/// Sanitize a single metadata value based on its key.
///
/// This function applies the following rules:
/// 1. If the key is potentially sensitive, the value is replaced with `[REDACTED]`
/// 2. If the value exceeds `MAX_METADATA_VALUE_LENGTH`, it is truncated
/// 3. Otherwise, the value is returned as-is
///
/// # Arguments
///
/// * `key` - The metadata key (used to determine if the value is sensitive)
/// * `value` - The metadata value to sanitize
///
/// # Returns
///
/// A sanitized string safe for logging.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::sanitize_value;
///
/// // Sensitive keys are redacted
/// assert_eq!(sanitize_value("api_key", "sk-12345"), "[REDACTED]");
///
/// // Normal keys pass through
/// assert_eq!(sanitize_value("operation", "encrypt"), "encrypt");
///
/// // Long values are truncated
/// let long_value = "x".repeat(2000);
/// assert!(sanitize_value("data", &long_value).contains("chars truncated"));
/// ```
#[must_use]
pub fn sanitize_value(key: &str, value: &str) -> String {
    if is_potentially_sensitive(key) {
        "[REDACTED]".to_string()
    } else if value.len() > MAX_METADATA_VALUE_LENGTH {
        format!("[{} chars truncated]", value.len())
    } else {
        value.to_string()
    }
}

/// Compute the first 16 hex characters of a SHA-256 hash.
///
/// This provides a fingerprint for data correlation without revealing content.
/// Uses the first 8 bytes of the SHA-256 hash, producing 16 hex characters.
fn sha256_first_16_hex(data: &[u8]) -> String {
    // Route through the primitives wrapper rather than importing `sha2` directly,
    // so hash backends remain swappable from a single place. The fingerprinted
    // inputs here are log-payload fragments — orders of magnitude smaller than
    // the 1 GiB DoS cap that guards the wrapper — so treating the Result as
    // infallible is sound.
    let Ok(result) = crate::primitives::hash::sha2::sha256(data) else {
        return String::from("hash-error");
    };
    // SHA-256 always produces 32 bytes, so .get(..8) will always succeed.
    // Using .get() for safe array access per project lint rules.
    result.get(..8).map_or_else(|| hex::encode(result), hex::encode)
}

/// Sanitize byte data for logging.
///
/// This function ensures raw bytes (which could be cryptographic keys or other
/// sensitive material) are never logged directly. Instead, it produces a safe
/// representation showing:
/// - For data <= 32 bytes: just the length
/// - For data > 32 bytes: length plus a fingerprint hash for correlation
///
/// # Arguments
///
/// * `data` - The byte data to sanitize
///
/// # Returns
///
/// A safe string representation of the data.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::sanitize_bytes;
///
/// // Small data shows only length
/// assert_eq!(sanitize_bytes(&[1, 2, 3]), "[3 bytes]");
///
/// // Larger data shows length and fingerprint
/// let large = vec![0u8; 100];
/// let result = sanitize_bytes(&large);
/// assert!(result.contains("100 bytes"));
/// assert!(result.contains("fingerprint:"));
/// ```
#[must_use]
pub fn sanitize_bytes(data: &[u8]) -> String {
    if data.len() <= 32 {
        format!("[{} bytes]", data.len())
    } else {
        // Show length and truncated hash for correlation
        let fingerprint = sha256_first_16_hex(data);
        format!("[{} bytes, fingerprint: {}]", data.len(), fingerprint)
    }
}

/// Sanitize an entire metadata map.
///
/// Applies `sanitize_value` to each key-value pair in the metadata map,
/// ensuring all sensitive values are redacted and long values are truncated.
///
/// # Arguments
///
/// * `metadata` - The metadata map to sanitize
///
/// # Returns
///
/// A new map with all values sanitized.
///
/// # Example
///
/// ```rust
/// use std::collections::HashMap;
/// use latticearc::unified_api::logging::sanitize_metadata;
///
/// let mut metadata = HashMap::new();
/// metadata.insert("operation".to_string(), "encrypt".to_string());
/// metadata.insert("api_key".to_string(), "secret-123".to_string());
///
/// let sanitized = sanitize_metadata(&metadata);
/// assert_eq!(sanitized.get("operation"), Some(&"encrypt".to_string()));
/// assert_eq!(sanitized.get("api_key"), Some(&"[REDACTED]".to_string()));
/// ```
#[must_use]
pub fn sanitize_metadata(metadata: &HashMap<String, String>) -> HashMap<String, String> {
    metadata.iter().map(|(k, v)| (k.clone(), sanitize_value(k, v))).collect()
}

/// Initialize tracing with security-conscious defaults.
///
/// Sets up structured logging with:
/// - Environment-based filtering (RUST_LOG)
/// - JSON output for production
/// - Sensitive data sanitization
/// - Performance-optimized formatting
///
/// # Errors
///
/// Returns an error if the tracing subscriber cannot be initialized,
/// typically due to a subscriber already being set.
pub fn init_tracing() -> Result<(), Box<dyn std::error::Error>> {
    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("latticearc=info"));

    let subscriber = tracing_subscriber::registry().with(filter).with(
        tracing_subscriber::fmt::layer()
            .with_target(false)
            .with_thread_ids(false)
            .with_thread_names(false)
            .compact(),
    );

    subscriber.init();

    info!("LatticeArc logging initialized");
    Ok(())
}

/// Sanitize data to prevent logging of sensitive information
///
/// This function replaces potentially sensitive byte sequences with
/// safe placeholder text. Used automatically in logging macros.
#[must_use]
pub fn sanitize_data(data: &[u8]) -> SanitizedData<'_> {
    SanitizedData(data)
}

/// Wrapper type for sanitized data display
pub struct SanitizedData<'a>(&'a [u8]);

impl<'a> fmt::Display for SanitizedData<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // For small data, show length only
        if self.0.len() <= 32 {
            write!(f, "[{} bytes]", self.0.len())
        } else {
            // For larger data, show truncated hash-like representation
            let hash = blake2_hash(self.0);
            write!(f, "[{} bytes, hash: {}]", self.0.len(), &hash[..16])
        }
    }
}

/// Compute a simple hash for data identification without revealing content
fn blake2_hash(data: &[u8]) -> String {
    // Route through the primitives wrapper rather than importing `blake2` directly.
    hex::encode(crate::primitives::hash::blake2::blake2s_256(data))
}

/// Security-conscious logging macros
///
/// These macros automatically sanitize sensitive data and provide
/// consistent logging across the LatticeArc codebase.
/// Log cryptographic operation start
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_start {
    ($operation:expr) => {
        trace!("Starting crypto operation: {}", $operation);
    };
    ($operation:expr, $($field:tt)*) => {
        trace!("Starting crypto operation: {} {}", $operation, format_args!($($field)*));
    };
}

/// Log cryptographic operation completion
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_complete {
    ($operation:expr) => {
        trace!("Completed crypto operation: {}", $operation);
    };
    ($operation:expr, $($field:tt)*) => {
        trace!("Completed crypto operation: {} {}", $operation, format_args!($($field)*));
    };
}

/// Log cryptographic operation error
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_error {
    ($operation:expr, $error:expr) => {
        error!("Crypto operation failed: {} - {}", $operation, $error);
    };
}

/// Log key generation
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_generation {
    ($algorithm:expr, $key_type:expr) => {
        info!("Generated {} key using {}", $key_type, $algorithm);
    };
}

/// Log encryption operation
#[doc(hidden)]
#[macro_export]
macro_rules! log_encryption {
    ($algorithm:expr, $data_len:expr) => {
        debug!("Encrypted {} bytes using {}", $data_len, $algorithm);
    };
}

/// Log decryption operation
#[doc(hidden)]
#[macro_export]
macro_rules! log_decryption {
    ($algorithm:expr, $data_len:expr) => {
        debug!("Decrypted {} bytes using {}", $data_len, $algorithm);
    };
}

/// Log signature operation
#[doc(hidden)]
#[macro_export]
macro_rules! log_signature {
    ($algorithm:expr) => {
        debug!("Created signature using {}", $algorithm);
    };
}

/// Log verification operation
#[doc(hidden)]
#[macro_export]
macro_rules! log_verification {
    ($algorithm:expr, $result:expr) => {
        debug!(
            "Verification {} using {}",
            if $result { "succeeded" } else { "failed" },
            $algorithm
        );
    };
}

/// Log security event (always logged, never filtered)
#[doc(hidden)]
#[macro_export]
macro_rules! log_security_event {
    ($event:expr) => {
        tracing::event!(Level::ERROR, security_event = true, "{}", $event);
    };
    ($event:expr, $($field:tt)*) => {
        tracing::event!(Level::ERROR, security_event = true, "{} {}", $event, format_args!($($field)*));
    };
}

/// Log performance metrics
#[doc(hidden)]
#[macro_export]
macro_rules! log_performance {
    ($operation:expr, $duration:expr) => {
        debug!("Performance: {} took {:?}", $operation, $duration);
    };
}

// ============================================================================
// Key Lifecycle Audit Logging Macros
// ============================================================================

/// Log a key generation event.
///
/// Logs at INFO level when new cryptographic key material is created.
/// This is an auditable event for compliance tracking.
///
/// # Arguments
///
/// * `$key_id` - Unique identifier for the key
/// * `$algorithm` - Algorithm used (e.g., "ML-KEM-768")
/// * `$key_type` - Type of key (use `KeyType` enum)
/// * `$purpose` - Purpose of key (use `KeyPurpose` enum)
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_generated;
/// use latticearc::unified_api::logging::{KeyType, KeyPurpose};
///
/// log_key_generated!("key-001", "ML-KEM-768", KeyType::KeyPair, KeyPurpose::KeyExchange);
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_generated {
    ($key_id:expr, $algorithm:expr, $key_type:expr, $purpose:expr) => {
        tracing::info!(
            target: "key_lifecycle::generated",
            key_id = %$key_id,
            algorithm = %$algorithm,
            key_type = ?$key_type,
            purpose = ?$purpose,
            "Key generated"
        );
    };
}

/// Log a key rotation event.
///
/// Logs at WARN level (notable event requiring attention) when a key
/// is replaced with a new key. This is a critical audit event.
///
/// # Arguments
///
/// * `$old_key_id` - ID of the key being replaced
/// * `$new_key_id` - ID of the replacement key
/// * `$algorithm` - Algorithm (should match)
/// * `$reason` - Reason for rotation (use `RotationReason` enum)
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_rotated;
/// use latticearc::unified_api::logging::RotationReason;
///
/// log_key_rotated!("key-001", "key-002", "ML-KEM-768", RotationReason::Scheduled);
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_rotated {
    ($old_key_id:expr, $new_key_id:expr, $algorithm:expr, $reason:expr) => {
        tracing::warn!(
            target: "key_lifecycle::rotated",
            old_key_id = %$old_key_id,
            new_key_id = %$new_key_id,
            algorithm = %$algorithm,
            reason = ?$reason,
            "Key rotated"
        );
    };
}

/// Log a key destruction event.
///
/// Logs at WARN level (critical audit event) when key material is
/// permanently destroyed. This is required for compliance verification.
///
/// # Arguments
///
/// * `$key_id` - ID of the destroyed key
/// * `$method` - Method used (use `DestructionMethod` enum)
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_destroyed;
/// use latticearc::unified_api::logging::DestructionMethod;
///
/// log_key_destroyed!("key-001", DestructionMethod::Zeroization);
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_destroyed {
    ($key_id:expr, $method:expr) => {
        tracing::warn!(
            target: "key_lifecycle::destroyed",
            key_id = %$key_id,
            method = ?$method,
            "Key destroyed"
        );
    };
}

/// Log a key access event.
///
/// Logs at DEBUG level (high volume, may be rate-limited) when a key
/// is used for a cryptographic operation. Useful for access auditing.
///
/// # Arguments
///
/// * `$key_id` - ID of the accessed key
/// * `$operation` - Type of operation (e.g., "encrypt", "sign")
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_accessed;
///
/// log_key_accessed!("key-001", "encrypt");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_accessed {
    ($key_id:expr, $operation:expr) => {
        tracing::debug!(
            target: "key_lifecycle::accessed",
            key_id = %$key_id,
            operation = %$operation,
            "Key accessed"
        );
    };
    ($key_id:expr, $operation:expr, $accessor:expr) => {
        tracing::debug!(
            target: "key_lifecycle::accessed",
            key_id = %$key_id,
            operation = %$operation,
            accessor = %$accessor,
            "Key accessed"
        );
    };
}

/// Log a key deprecation event.
///
/// Logs at INFO level when a key is scheduled for retirement.
/// The key may still be used for decryption of existing data.
///
/// # Arguments
///
/// * `$key_id` - ID of the deprecated key
/// * `$reason` - Human-readable reason for deprecation
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_deprecated;
///
/// log_key_deprecated!("key-001", "Scheduled retirement per policy");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_deprecated {
    ($key_id:expr, $reason:expr) => {
        tracing::info!(
            target: "key_lifecycle::deprecated",
            key_id = %$key_id,
            reason = %$reason,
            "Key deprecated"
        );
    };
}

/// Log a key suspension event.
///
/// Logs at WARN level when a key is temporarily disabled,
/// typically due to a suspected security incident.
///
/// # Arguments
///
/// * `$key_id` - ID of the suspended key
/// * `$reason` - Reason for suspension
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_suspended;
///
/// log_key_suspended!("key-001", "Suspected compromise");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_suspended {
    ($key_id:expr, $reason:expr) => {
        tracing::warn!(
            target: "key_lifecycle::suspended",
            key_id = %$key_id,
            reason = %$reason,
            "Key suspended"
        );
    };
}

/// Log a key export event.
///
/// Logs at WARN level (security-sensitive) when a key is exported.
/// This is a critical audit event requiring special attention.
///
/// # Arguments
///
/// * `$key_id` - ID of the exported key
/// * `$format` - Export format (e.g., "PEM", "PKCS#12")
/// * `$destination` - Destination identifier
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_exported;
///
/// log_key_exported!("key-001", "PEM", "backup-hsm-01");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_exported {
    ($key_id:expr, $format:expr, $destination:expr) => {
        tracing::warn!(
            target: "key_lifecycle::exported",
            key_id = %$key_id,
            format = %$format,
            destination = %$destination,
            "Key exported"
        );
    };
}

/// Log a key import event.
///
/// Logs at INFO level when external key material is imported.
/// Important for tracking key provenance.
///
/// # Arguments
///
/// * `$key_id` - ID assigned to the imported key
/// * `$algorithm` - Algorithm of the imported key
/// * `$source` - Source of the key material
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_key_imported;
///
/// log_key_imported!("key-001", "ML-KEM-768", "external-hsm-02");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_key_imported {
    ($key_id:expr, $algorithm:expr, $source:expr) => {
        tracing::info!(
            target: "key_lifecycle::imported",
            key_id = %$key_id,
            algorithm = %$algorithm,
            source = %$source,
            "Key imported"
        );
    };
}

// ============================================================================
// Correlation-Aware Crypto Logging Macros
// ============================================================================

/// Log a cryptographic operation with automatic correlation ID inclusion.
///
/// This macro automatically includes the current correlation ID (if set)
/// in log events, enabling distributed tracing across async boundaries.
///
/// # Example
///
/// ```rust,no_run
/// use latticearc::log_crypto_operation;
/// use latticearc::unified_api::logging::{set_correlation_id, CorrelationGuard};
///
/// // Set a correlation ID
/// let _guard = CorrelationGuard::new();
///
/// // Log includes correlation_id automatically
/// log_crypto_operation!("encrypt", algorithm = "AES-256-GCM", data_size = 1024);
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_operation {
    ($op:expr, $($field:tt)*) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::debug!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                $($field)*
            );
        } else {
            tracing::debug!(
                target: "crypto::operation",
                operation = $op,
                $($field)*
            );
        }
    };
    ($op:expr) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::debug!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
            );
        } else {
            tracing::debug!(
                target: "crypto::operation",
                operation = $op,
            );
        }
    };
}

/// Log a cryptographic operation start with correlation ID.
///
/// Similar to [`log_crypto_operation`] but at TRACE level for detailed tracing.
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_operation_start {
    ($op:expr, $($field:tt)*) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::trace!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                phase = "start",
                $($field)*
            );
        } else {
            tracing::trace!(
                target: "crypto::operation",
                operation = $op,
                phase = "start",
                $($field)*
            );
        }
    };
    ($op:expr) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::trace!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                phase = "start",
            );
        } else {
            tracing::trace!(
                target: "crypto::operation",
                operation = $op,
                phase = "start",
            );
        }
    };
}

/// Log a cryptographic operation completion with correlation ID.
///
/// Similar to [`log_crypto_operation`] but at TRACE level for detailed tracing.
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_operation_complete {
    ($op:expr, $($field:tt)*) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::trace!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                phase = "complete",
                $($field)*
            );
        } else {
            tracing::trace!(
                target: "crypto::operation",
                operation = $op,
                phase = "complete",
                $($field)*
            );
        }
    };
    ($op:expr) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::trace!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                phase = "complete",
            );
        } else {
            tracing::trace!(
                target: "crypto::operation",
                operation = $op,
                phase = "complete",
            );
        }
    };
}

/// Log a cryptographic operation error with correlation ID.
///
/// Logs at ERROR level and includes the correlation ID for tracing.
#[doc(hidden)]
#[macro_export]
macro_rules! log_crypto_operation_error {
    ($op:expr, $error:expr, $($field:tt)*) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::error!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                error = %$error,
                phase = "error",
                $($field)*
            );
        } else {
            tracing::error!(
                target: "crypto::operation",
                operation = $op,
                error = %$error,
                phase = "error",
                $($field)*
            );
        }
    };
    ($op:expr, $error:expr) => {
        if let Some(corr_id) = $crate::unified_api::logging::current_correlation_id() {
            tracing::error!(
                target: "crypto::operation",
                correlation_id = %corr_id,
                operation = $op,
                error = %$error,
                phase = "error",
            );
        } else {
            tracing::error!(
                target: "crypto::operation",
                operation = $op,
                error = %$error,
                phase = "error",
            );
        }
    };
}

// ============================================================================
// Zero Trust Audit Logging Macros
// ============================================================================

/// Log Zero Trust authentication attempt.
///
/// Logs the initiation of a Zero Trust authentication attempt with session ID.
/// Session ID is logged as hex string for audit traceability.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_auth_attempt {
    ($session_id_hex:expr) => {
        tracing::info!(
            target: "zero_trust::auth",
            session_id = %$session_id_hex,
            "Zero Trust authentication attempt initiated"
        );
    };
}

/// Log Zero Trust authentication success.
///
/// Logs successful authentication with session ID and achieved trust level.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_auth_success {
    ($session_id_hex:expr, $trust_level:expr) => {
        tracing::info!(
            target: "zero_trust::auth",
            session_id = %$session_id_hex,
            trust_level = ?$trust_level,
            "Zero Trust authentication succeeded"
        );
    };
}

/// Log Zero Trust authentication failure.
///
/// Logs failed authentication attempts with session ID and reason.
/// Reason should never contain sensitive data.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_auth_failure {
    ($session_id_hex:expr, $reason:expr) => {
        tracing::error!(
            target: "zero_trust::auth",
            session_id = %$session_id_hex,
            reason = %$reason,
            "Zero Trust authentication failed"
        );
    };
}

/// Log Zero Trust session creation.
///
/// Logs the creation of a new verified session with trust level and expiration.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_session_created {
    ($session_id_hex:expr, $trust_level:expr, $expires_at:expr) => {
        tracing::info!(
            target: "zero_trust::session",
            session_id = %$session_id_hex,
            trust_level = ?$trust_level,
            expires_at = %$expires_at,
            "Zero Trust session created"
        );
    };
}

/// Log Zero Trust session verification success.
///
/// Logs successful session verification for ongoing trust validation.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_session_verified {
    ($session_id_hex:expr) => {
        tracing::info!(
            target: "zero_trust::session",
            session_id = %$session_id_hex,
            "Zero Trust session verified"
        );
    };
}

/// Log Zero Trust session verification failure.
///
/// Logs failed session verification with session ID and reason.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_session_verification_failed {
    ($session_id_hex:expr, $reason:expr) => {
        tracing::error!(
            target: "zero_trust::session",
            session_id = %$session_id_hex,
            reason = %$reason,
            "Zero Trust session verification failed"
        );
    };
}

/// Log Zero Trust session expiration.
///
/// Logs when a session has expired during a validation check.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_session_expired {
    ($session_id_hex:expr) => {
        tracing::warn!(
            target: "zero_trust::session",
            session_id = %$session_id_hex,
            "Zero Trust session expired"
        );
    };
}

/// Log Zero Trust trust level transition.
///
/// Logs trust level changes (upgrades or downgrades) for audit trail.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_trust_level_changed {
    ($session_id_hex:expr, $from_level:expr, $to_level:expr) => {
        tracing::info!(
            target: "zero_trust::trust",
            session_id = %$session_id_hex,
            from_level = ?$from_level,
            to_level = ?$to_level,
            "Zero Trust trust level changed"
        );
    };
}

/// Log SecurityMode::Unverified usage (warning).
///
/// Logs when an operation is performed in Unverified mode.
/// This is a security-relevant event that should trigger audit review.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_unverified_mode {
    ($operation:expr) => {
        tracing::warn!(
            target: "zero_trust::security",
            operation = %$operation,
            "Operation performed in SecurityMode::Unverified - no session verification"
        );
    };
}

/// Log Zero Trust challenge generation.
///
/// Logs challenge generation for authentication flows.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_challenge_generated {
    ($complexity:expr) => {
        tracing::debug!(
            target: "zero_trust::auth",
            complexity = ?$complexity,
            "Zero Trust challenge generated"
        );
    };
}

/// Log Zero Trust proof verification result.
///
/// Logs the outcome of proof verification attempts.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_proof_verified {
    ($result:expr) => {
        if $result {
            tracing::debug!(
                target: "zero_trust::auth",
                "Zero Trust proof verification succeeded"
            );
        } else {
            tracing::warn!(
                target: "zero_trust::auth",
                "Zero Trust proof verification failed"
            );
        }
    };
}

/// Log Zero Trust access control decision.
///
/// Logs access control decisions for audit trail compliance.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_access_decision {
    ($session_id_hex:expr, $allowed:expr, $reason:expr) => {
        if $allowed {
            tracing::info!(
                target: "zero_trust::access",
                session_id = %$session_id_hex,
                allowed = $allowed,
                reason = %$reason,
                "Zero Trust access granted"
            );
        } else {
            tracing::warn!(
                target: "zero_trust::access",
                session_id = %$session_id_hex,
                allowed = $allowed,
                reason = %$reason,
                "Zero Trust access denied"
            );
        }
    };
}

/// Log Zero Trust session revocation.
///
/// Logs when a session is explicitly revoked.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_session_revoked {
    ($session_id_hex:expr) => {
        tracing::info!(
            target: "zero_trust::session",
            session_id = %$session_id_hex,
            "Zero Trust session revoked"
        );
    };
}

/// Log Zero Trust continuous verification status.
///
/// Logs periodic verification status updates.
#[doc(hidden)]
#[macro_export]
macro_rules! log_zero_trust_continuous_verification {
    ($session_id_hex:expr, $status:expr) => {
        tracing::debug!(
            target: "zero_trust::session",
            session_id = %$session_id_hex,
            status = ?$status,
            "Zero Trust continuous verification status"
        );
    };
}

// ============================================================================
// Zero Trust Logging Utility Functions
// ============================================================================

/// Convert a session ID (byte array) to a hex string for safe logging.
///
/// This function converts raw session ID bytes to a hexadecimal string,
/// which is safe to log and useful for audit trail correlation.
///
/// # Arguments
///
/// * `session_id` - The raw session ID bytes
///
/// # Returns
///
/// A hexadecimal string representation of the session ID.
///
/// # Example
///
/// ```rust
/// use latticearc::unified_api::logging::session_id_to_hex;
///
/// let session_id = [0x12, 0x34, 0xAB, 0xCD];
/// assert_eq!(session_id_to_hex(&session_id), "1234abcd");
/// ```
#[must_use]
pub fn session_id_to_hex(session_id: &[u8]) -> String {
    hex::encode(session_id)
}

/// Initialize tracing with file output for persistent logging.
///
/// # Errors
///
/// Returns an error if:
/// - The tracing subscriber cannot be initialized
/// - The log file cannot be created or written to
pub fn init_tracing_with_file(log_file: &str) -> Result<(), Box<dyn std::error::Error>> {
    use tracing_appender::rolling::{RollingFileAppender, Rotation};

    let file_appender = RollingFileAppender::new(Rotation::DAILY, "logs", log_file);

    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("latticearc=info"));

    let subscriber = tracing_subscriber::registry()
        .with(filter)
        .with(tracing_subscriber::fmt::layer().with_target(false).with_writer(file_appender));

    subscriber.init();

    info!("LatticeArc logging to file initialized: {}", log_file);
    Ok(())
}

#[cfg(test)]
#[allow(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::arithmetic_side_effects,
    clippy::panic_in_result_fn,
    clippy::unnecessary_wraps,
    clippy::redundant_clone,
    clippy::useless_vec,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::clone_on_copy,
    clippy::len_zero,
    clippy::single_match,
    clippy::unnested_or_patterns,
    clippy::default_constructed_unit_structs,
    clippy::redundant_closure_for_method_calls,
    clippy::semicolon_if_nothing_returned,
    clippy::unnecessary_unwrap,
    clippy::redundant_pattern_matching,
    clippy::missing_const_for_thread_local,
    clippy::get_first,
    clippy::float_cmp,
    clippy::needless_borrows_for_generic_args,
    clippy::unnecessary_map_or,
    clippy::option_as_ref_deref,
    unused_qualifications
)]
mod tests {
    use super::*;

    #[test]
    fn test_sanitize_data_small_has_correct_format() {
        let data = b"short";
        let sanitized = sanitize_data(data);
        assert_eq!(format!("{}", sanitized), "[5 bytes]");
    }

    #[test]
    fn test_sanitize_data_large_has_correct_format() {
        let data = vec![0u8; 100];
        let sanitized = sanitize_data(&data);
        let output = format!("{}", sanitized);
        assert!(output.contains("[100 bytes"));
        assert!(output.contains("hash:"));
    }

    #[test]
    fn test_blake2_hash_has_correct_format() {
        let data = b"test data";
        let hash = blake2_hash(data);
        assert_eq!(hash.len(), 64); // Blake2s256 produces 32 bytes, hex encoded = 64 chars
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
    }

    // ========================================================================
    // Metadata Sanitization Tests
    // ========================================================================

    #[test]
    fn test_is_potentially_sensitive_matches_sensitive_keys_succeeds() {
        // Direct matches
        assert!(is_potentially_sensitive("key"));
        assert!(is_potentially_sensitive("secret"));
        assert!(is_potentially_sensitive("password"));
        assert!(is_potentially_sensitive("token"));
        assert!(is_potentially_sensitive("credential"));
        assert!(is_potentially_sensitive("private"));
        assert!(is_potentially_sensitive("auth"));
        assert!(is_potentially_sensitive("session"));
        assert!(is_potentially_sensitive("bearer"));
        assert!(is_potentially_sensitive("api_key"));
        assert!(is_potentially_sensitive("apikey"));
        assert!(is_potentially_sensitive("passphrase"));
    }

    #[test]
    fn test_is_potentially_sensitive_matches_compound_keys_succeeds() {
        // Compound keys containing sensitive patterns
        assert!(is_potentially_sensitive("user_password"));
        assert!(is_potentially_sensitive("api_key_header"));
        assert!(is_potentially_sensitive("auth_token"));
        assert!(is_potentially_sensitive("private_key_pem"));
        assert!(is_potentially_sensitive("session_id"));
        assert!(is_potentially_sensitive("bearer_token"));
        assert!(is_potentially_sensitive("encryption_key"));
        assert!(is_potentially_sensitive("secret_value"));
        assert!(is_potentially_sensitive("credential_store"));
    }

    #[test]
    fn test_is_potentially_sensitive_case_insensitive_succeeds() {
        // Case insensitive matching
        assert!(is_potentially_sensitive("API_KEY"));
        assert!(is_potentially_sensitive("Password"));
        assert!(is_potentially_sensitive("SECRET"));
        assert!(is_potentially_sensitive("AuthToken"));
        assert!(is_potentially_sensitive("BEARER_TOKEN"));
        assert!(is_potentially_sensitive("PrivateKey"));
    }

    #[test]
    fn test_is_potentially_sensitive_non_sensitive_keys_returns_false_succeeds() {
        // Keys that should NOT be flagged
        assert!(!is_potentially_sensitive("username"));
        assert!(!is_potentially_sensitive("operation"));
        assert!(!is_potentially_sensitive("timestamp"));
        assert!(!is_potentially_sensitive("request_id"));
        assert!(!is_potentially_sensitive("user_id"));
        assert!(!is_potentially_sensitive("algorithm"));
        assert!(!is_potentially_sensitive("data_size"));
        assert!(!is_potentially_sensitive("operation_type"));
        assert!(!is_potentially_sensitive("status"));
        assert!(!is_potentially_sensitive("result"));
    }

    #[test]
    fn test_sanitize_value_redacts_sensitive_keys_succeeds() {
        assert_eq!(sanitize_value("api_key", "sk-12345abcdef"), "[REDACTED]");
        assert_eq!(sanitize_value("password", "super_secret_123"), "[REDACTED]");
        assert_eq!(sanitize_value("auth_token", "Bearer xyz"), "[REDACTED]");
        assert_eq!(sanitize_value("private_key", "-----BEGIN PRIVATE KEY-----"), "[REDACTED]");
    }

    #[test]
    fn test_sanitize_value_passes_normal_values_unchanged_succeeds() {
        assert_eq!(sanitize_value("operation", "encrypt"), "encrypt");
        assert_eq!(sanitize_value("algorithm", "ML-KEM-768"), "ML-KEM-768");
        assert_eq!(sanitize_value("user_id", "user123"), "user123");
        assert_eq!(sanitize_value("status", "success"), "success");
    }

    #[test]
    fn test_sanitize_value_truncates_long_values_succeeds() {
        let long_value = "x".repeat(2000);
        let result = sanitize_value("data", &long_value);
        assert_eq!(result, "[2000 chars truncated]");

        // Exactly at limit should pass through
        let exact_value = "x".repeat(MAX_METADATA_VALUE_LENGTH);
        let result = sanitize_value("data", &exact_value);
        assert_eq!(result, exact_value);

        // One over limit should truncate
        let over_value = "x".repeat(MAX_METADATA_VALUE_LENGTH + 1);
        let result = sanitize_value("data", &over_value);
        assert!(result.contains("chars truncated"));
    }

    #[test]
    fn test_sanitize_value_sensitive_key_takes_precedence_succeeds() {
        // Even long sensitive values are just redacted, not truncated
        let long_secret = "x".repeat(5000);
        let result = sanitize_value("api_key", &long_secret);
        assert_eq!(result, "[REDACTED]");
    }

    #[test]
    fn test_sanitize_bytes_small_data_succeeds() {
        assert_eq!(sanitize_bytes(&[]), "[0 bytes]");
        assert_eq!(sanitize_bytes(&[1]), "[1 bytes]");
        assert_eq!(sanitize_bytes(&[1, 2, 3]), "[3 bytes]");
        assert_eq!(sanitize_bytes(&[0u8; 32]), "[32 bytes]");
    }

    #[test]
    fn test_sanitize_bytes_large_data_has_fingerprint_format_has_correct_size() {
        let data = vec![0u8; 33];
        let result = sanitize_bytes(&data);
        assert!(result.contains("33 bytes"));
        assert!(result.contains("fingerprint:"));

        let data = vec![0u8; 100];
        let result = sanitize_bytes(&data);
        assert!(result.contains("100 bytes"));
        assert!(result.contains("fingerprint:"));
    }

    #[test]
    fn test_sanitize_bytes_fingerprint_is_consistent() {
        // Same data should produce same fingerprint
        let data = b"test data for fingerprint consistency check";
        let result1 = sanitize_bytes(data);
        let result2 = sanitize_bytes(data);
        assert_eq!(result1, result2);
    }

    #[test]
    fn test_sanitize_bytes_fingerprint_differs_for_different_data_succeeds() {
        let data1 = vec![0u8; 100];
        let data2 = vec![1u8; 100];
        let result1 = sanitize_bytes(&data1);
        let result2 = sanitize_bytes(&data2);
        assert_ne!(result1, result2);
    }

    #[test]
    fn test_sha256_first_16_hex_has_correct_format() {
        // Known test vector - SHA-256 of empty string
        let empty_hash = sha256_first_16_hex(&[]);
        assert_eq!(empty_hash.len(), 16);
        // SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
        // First 8 bytes = e3b0c44298fc1c14
        assert_eq!(empty_hash, "e3b0c44298fc1c14");

        // Verify it's valid hex
        assert!(empty_hash.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_sanitize_metadata_full_map_succeeds() {
        let mut metadata = HashMap::new();
        metadata.insert("operation".to_string(), "encrypt".to_string());
        metadata.insert("api_key".to_string(), "sk-secret-123".to_string());
        metadata.insert("user_id".to_string(), "user_456".to_string());
        metadata.insert("password_hash".to_string(), "hashed_value".to_string());
        metadata.insert("algorithm".to_string(), "ML-KEM-768".to_string());

        let sanitized = sanitize_metadata(&metadata);

        // Non-sensitive keys pass through
        assert_eq!(sanitized.get("operation"), Some(&"encrypt".to_string()));
        assert_eq!(sanitized.get("user_id"), Some(&"user_456".to_string()));
        assert_eq!(sanitized.get("algorithm"), Some(&"ML-KEM-768".to_string()));

        // Sensitive keys are redacted
        assert_eq!(sanitized.get("api_key"), Some(&"[REDACTED]".to_string()));
        assert_eq!(sanitized.get("password_hash"), Some(&"[REDACTED]".to_string()));
    }

    #[test]
    fn test_sanitize_metadata_empty_map_succeeds() {
        let metadata = HashMap::new();
        let sanitized = sanitize_metadata(&metadata);
        assert!(sanitized.is_empty());
    }

    #[test]
    fn test_sanitize_metadata_preserves_all_keys_succeeds() {
        let mut metadata = HashMap::new();
        metadata.insert("key1".to_string(), "value1".to_string());
        metadata.insert("key2".to_string(), "value2".to_string());
        metadata.insert("secret".to_string(), "hidden".to_string());

        let sanitized = sanitize_metadata(&metadata);

        // All keys should still be present
        assert_eq!(sanitized.len(), 3);
        assert!(sanitized.contains_key("key1"));
        assert!(sanitized.contains_key("key2"));
        assert!(sanitized.contains_key("secret"));
    }

    #[test]
    fn test_sanitize_metadata_with_long_values_succeeds() {
        let mut metadata = HashMap::new();
        let long_value = "x".repeat(2000);
        metadata.insert("description".to_string(), long_value);
        metadata.insert("short".to_string(), "brief".to_string());

        let sanitized = sanitize_metadata(&metadata);

        assert!(sanitized.get("description").map_or(false, |v| v.contains("chars truncated")));
        assert_eq!(sanitized.get("short"), Some(&"brief".to_string()));
    }

    #[test]
    fn test_session_id_to_hex_has_correct_format() {
        let session_id = [0x12, 0x34, 0xAB, 0xCD];
        assert_eq!(session_id_to_hex(&session_id), "1234abcd");

        let empty: [u8; 0] = [];
        assert_eq!(session_id_to_hex(&empty), "");

        let all_zeros = [0u8; 16];
        assert_eq!(session_id_to_hex(&all_zeros), "00000000000000000000000000000000");
    }

    // ========================================================================
    // Correlation ID Tests
    // ========================================================================

    #[test]
    fn test_generate_correlation_id_is_valid_uuid_succeeds() {
        let id = generate_correlation_id();
        // UUID v4 format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (36 chars with hyphens)
        assert_eq!(id.len(), 36);
        assert_eq!(id.chars().filter(|c| *c == '-').count(), 4);
        // Verify it parses as a valid UUID
        assert!(Uuid::parse_str(&id).is_ok());
    }

    #[test]
    fn test_generate_correlation_id_is_unique_succeeds() {
        let id1 = generate_correlation_id();
        let id2 = generate_correlation_id();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_generate_lightweight_correlation_id_has_correct_format() {
        let id = generate_lightweight_correlation_id();
        assert!(id.starts_with("corr-"));
        // corr- (5 chars) + 16 hex chars = 21 chars total
        assert_eq!(id.len(), 21);
        // Verify the hex part is valid
        let hex_part = &id[5..];
        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_generate_lightweight_correlation_id_increments_succeeds() {
        let id1 = generate_lightweight_correlation_id();
        let id2 = generate_lightweight_correlation_id();
        assert_ne!(id1, id2);
        // Extract counter values and verify they're sequential
        let counter1 = u64::from_str_radix(&id1[5..], 16);
        let counter2 = u64::from_str_radix(&id2[5..], 16);
        assert!(counter1.is_ok());
        assert!(counter2.is_ok());
    }

    #[test]
    fn test_set_and_get_correlation_id_succeeds() {
        // Clear any existing correlation ID
        clear_correlation_id();
        assert_eq!(current_correlation_id(), None);

        // Set a correlation ID
        set_correlation_id("test-correlation-123".to_string());
        assert_eq!(current_correlation_id(), Some("test-correlation-123".to_string()));

        // Clean up
        clear_correlation_id();
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_clear_correlation_id_succeeds() {
        set_correlation_id("to-be-cleared".to_string());
        assert!(current_correlation_id().is_some());

        clear_correlation_id();
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_with_correlation_id_executes_closure_succeeds() {
        clear_correlation_id();

        let result = with_correlation_id("request-456".to_string(), || {
            assert_eq!(current_correlation_id(), Some("request-456".to_string()));
            42
        });

        assert_eq!(result, 42);
        // After closure, correlation ID should be cleared (was None before)
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_with_correlation_id_restores_previous_succeeds() {
        clear_correlation_id();
        set_correlation_id("outer-id".to_string());

        with_correlation_id("inner-id".to_string(), || {
            assert_eq!(current_correlation_id(), Some("inner-id".to_string()));
        });

        // Should restore the outer ID
        assert_eq!(current_correlation_id(), Some("outer-id".to_string()));

        // Clean up
        clear_correlation_id();
    }

    #[test]
    fn test_correlation_guard_new_sets_uuid_succeeds() {
        clear_correlation_id();

        {
            let guard = CorrelationGuard::new();
            let id = guard.id();
            assert!(id.is_some());
            let id_str = id.as_ref().map(String::as_str);
            // Should be a valid UUID
            assert!(id_str.map_or(false, |s| Uuid::parse_str(s).is_ok()));
        }

        // After guard drops, should be cleared
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_correlation_guard_with_id_succeeds() {
        clear_correlation_id();

        {
            let guard = CorrelationGuard::with_id("custom-id-789".to_string());
            assert_eq!(guard.id(), Some("custom-id-789".to_string()));
            assert_eq!(current_correlation_id(), Some("custom-id-789".to_string()));
        }

        // After guard drops, should be cleared
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_correlation_guard_lightweight_succeeds() {
        clear_correlation_id();

        {
            let guard = CorrelationGuard::lightweight();
            let id = guard.id();
            assert!(id.is_some());
            assert!(id.as_ref().map_or(false, |s| s.starts_with("corr-")));
        }

        // After guard drops, should be cleared
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_correlation_guard_restores_previous_on_drop_succeeds() {
        clear_correlation_id();
        set_correlation_id("original-id".to_string());

        {
            let guard = CorrelationGuard::with_id("temporary-id".to_string());
            assert_eq!(guard.previous_id(), Some(&"original-id".to_string()));
            assert_eq!(current_correlation_id(), Some("temporary-id".to_string()));
        }

        // Should restore original ID after guard drops
        assert_eq!(current_correlation_id(), Some("original-id".to_string()));

        // Clean up
        clear_correlation_id();
    }

    #[test]
    fn test_correlation_guard_nested_succeeds() {
        clear_correlation_id();

        {
            let guard1 = CorrelationGuard::with_id("level-1".to_string());
            assert_eq!(current_correlation_id(), Some("level-1".to_string()));

            {
                let guard2 = CorrelationGuard::with_id("level-2".to_string());
                assert_eq!(current_correlation_id(), Some("level-2".to_string()));
                assert_eq!(guard2.previous_id(), Some(&"level-1".to_string()));
            }

            // After inner guard drops, should restore level-1
            assert_eq!(current_correlation_id(), Some("level-1".to_string()));
            assert_eq!(guard1.previous_id(), None);
        }

        // After outer guard drops, should be cleared
        assert_eq!(current_correlation_id(), None);
    }

    #[test]
    fn test_correlation_guard_default_succeeds() {
        clear_correlation_id();

        {
            let guard = CorrelationGuard::default();
            let id = guard.id();
            assert!(id.is_some());
            // Default should create a UUID
            assert!(id.as_ref().map_or(false, |s| Uuid::parse_str(s).is_ok()));
        }

        assert_eq!(current_correlation_id(), None);
    }

    // ========================================================================
    // Key Lifecycle Event Tests
    // ========================================================================

    #[test]
    fn test_key_type_display_has_correct_format() {
        assert_eq!(KeyType::Symmetric.to_string(), "Symmetric");
        assert_eq!(KeyType::AsymmetricPublic.to_string(), "AsymmetricPublic");
        assert_eq!(KeyType::AsymmetricPrivate.to_string(), "AsymmetricPrivate");
        assert_eq!(KeyType::KeyPair.to_string(), "KeyPair");
    }

    #[test]
    fn test_key_purpose_display_has_correct_format() {
        assert_eq!(KeyPurpose::Encryption.to_string(), "Encryption");
        assert_eq!(KeyPurpose::Signing.to_string(), "Signing");
        assert_eq!(KeyPurpose::KeyExchange.to_string(), "KeyExchange");
        assert_eq!(KeyPurpose::Authentication.to_string(), "Authentication");
        assert_eq!(KeyPurpose::KeyWrapping.to_string(), "KeyWrapping");
    }

    #[test]
    fn test_rotation_reason_display_has_correct_format() {
        assert_eq!(RotationReason::Scheduled.to_string(), "Scheduled");
        assert_eq!(RotationReason::Compromised.to_string(), "Compromised");
        assert_eq!(RotationReason::PolicyChange.to_string(), "PolicyChange");
        assert_eq!(RotationReason::Expiration.to_string(), "Expiration");
        assert_eq!(RotationReason::Manual.to_string(), "Manual");
    }

    #[test]
    fn test_destruction_method_display_has_correct_format() {
        assert_eq!(DestructionMethod::Zeroization.to_string(), "Zeroization");
        assert_eq!(DestructionMethod::CryptoErase.to_string(), "CryptoErase");
        assert_eq!(DestructionMethod::Manual.to_string(), "Manual");
    }

    #[test]
    fn test_key_lifecycle_event_generated_has_correct_format() {
        let event = KeyLifecycleEvent::generated(
            "key-001",
            "ML-KEM-768",
            KeyType::KeyPair,
            KeyPurpose::KeyExchange,
        );

        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "generated");

        // Verify internal structure
        match event {
            KeyLifecycleEvent::Generated { key_id, algorithm, key_type, purpose } => {
                assert_eq!(key_id, "key-001");
                assert_eq!(algorithm, "ML-KEM-768");
                assert_eq!(key_type, KeyType::KeyPair);
                assert_eq!(purpose, KeyPurpose::KeyExchange);
            }
            _ => panic!("Expected Generated event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_rotated_has_correct_format() {
        let event = KeyLifecycleEvent::rotated(
            "old-key-001",
            "new-key-002",
            "ML-KEM-768",
            RotationReason::Scheduled,
        );

        assert_eq!(event.key_id(), "new-key-002");
        assert_eq!(event.event_type(), "rotated");

        match event {
            KeyLifecycleEvent::Rotated { old_key_id, new_key_id, algorithm, reason } => {
                assert_eq!(old_key_id, "old-key-001");
                assert_eq!(new_key_id, "new-key-002");
                assert_eq!(algorithm, "ML-KEM-768");
                assert_eq!(reason, RotationReason::Scheduled);
            }
            _ => panic!("Expected Rotated event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_destroyed_has_correct_format() {
        let event = KeyLifecycleEvent::destroyed("key-001", DestructionMethod::Zeroization);

        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "destroyed");

        match event {
            KeyLifecycleEvent::Destroyed { key_id, method } => {
                assert_eq!(key_id, "key-001");
                assert_eq!(method, DestructionMethod::Zeroization);
            }
            _ => panic!("Expected Destroyed event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_accessed_has_correct_format() {
        // Without accessor
        let event = KeyLifecycleEvent::accessed("key-001", "encrypt", None);
        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "accessed");

        // With accessor
        let event_with_accessor =
            KeyLifecycleEvent::accessed("key-002", "sign", Some("user-123".to_string()));
        match event_with_accessor {
            KeyLifecycleEvent::Accessed { key_id, operation, accessor } => {
                assert_eq!(key_id, "key-002");
                assert_eq!(operation, "sign");
                assert_eq!(accessor, Some("user-123".to_string()));
            }
            _ => panic!("Expected Accessed event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_imported_has_correct_format() {
        let event = KeyLifecycleEvent::imported("key-001", "ML-KEM-768", "external-hsm");

        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "imported");

        match event {
            KeyLifecycleEvent::Imported { key_id, algorithm, source } => {
                assert_eq!(key_id, "key-001");
                assert_eq!(algorithm, "ML-KEM-768");
                assert_eq!(source, "external-hsm");
            }
            _ => panic!("Expected Imported event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_exported_has_correct_format() {
        let event = KeyLifecycleEvent::exported("key-001", "PEM", "backup-server");

        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "exported");

        match event {
            KeyLifecycleEvent::Exported { key_id, format, destination } => {
                assert_eq!(key_id, "key-001");
                assert_eq!(format, "PEM");
                assert_eq!(destination, "backup-server");
            }
            _ => panic!("Expected Exported event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_deprecated_has_correct_format() {
        let deprecation_date = Utc::now();
        let event = KeyLifecycleEvent::deprecated("key-001", deprecation_date, "End of life");

        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "deprecated");

        match event {
            KeyLifecycleEvent::Deprecated { key_id, deprecation_date: date, reason } => {
                assert_eq!(key_id, "key-001");
                assert_eq!(date, deprecation_date);
                assert_eq!(reason, "End of life");
            }
            _ => panic!("Expected Deprecated event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_suspended_has_correct_format() {
        let event = KeyLifecycleEvent::suspended("key-001", "Suspected compromise");

        assert_eq!(event.key_id(), "key-001");
        assert_eq!(event.event_type(), "suspended");

        match event {
            KeyLifecycleEvent::Suspended { key_id, reason } => {
                assert_eq!(key_id, "key-001");
                assert_eq!(reason, "Suspected compromise");
            }
            _ => panic!("Expected Suspended event"),
        }
    }

    #[test]
    fn test_key_lifecycle_event_serializes_correctly_succeeds() {
        let event = KeyLifecycleEvent::generated(
            "key-001",
            "ML-KEM-768",
            KeyType::KeyPair,
            KeyPurpose::KeyExchange,
        );

        // Test JSON serialization
        let json = serde_json::to_string(&event);
        assert!(json.is_ok());

        let json_str = json.as_ref().map(String::as_str);
        assert!(json_str.map_or(false, |s| s.contains("key-001")));
        assert!(json_str.map_or(false, |s| s.contains("ML-KEM-768")));
        assert!(json_str.map_or(false, |s| s.contains("KeyPair")));
        assert!(json_str.map_or(false, |s| s.contains("KeyExchange")));

        // Test deserialization
        let deserialized: Result<KeyLifecycleEvent, _> =
            serde_json::from_str(json.as_ref().map_or("", String::as_str));
        assert!(deserialized.is_ok());

        if let Ok(KeyLifecycleEvent::Generated { key_id, algorithm, key_type, purpose }) =
            deserialized
        {
            assert_eq!(key_id, "key-001");
            assert_eq!(algorithm, "ML-KEM-768");
            assert_eq!(key_type, KeyType::KeyPair);
            assert_eq!(purpose, KeyPurpose::KeyExchange);
        } else {
            panic!("Failed to deserialize Generated event");
        }
    }

    #[test]
    fn test_key_type_serializes_correctly_succeeds() {
        for key_type in [
            KeyType::Symmetric,
            KeyType::AsymmetricPublic,
            KeyType::AsymmetricPrivate,
            KeyType::KeyPair,
        ] {
            let json = serde_json::to_string(&key_type);
            assert!(json.is_ok());
            let deserialized: Result<KeyType, _> =
                serde_json::from_str(json.as_ref().map_or("", String::as_str));
            assert!(deserialized.is_ok());
            assert_eq!(
                deserialized.unwrap_or_else(|_| panic!("Failed to deserialize {:?}", key_type)),
                key_type
            );
        }
    }

    #[test]
    fn test_key_purpose_serializes_correctly_succeeds() {
        for purpose in [
            KeyPurpose::Encryption,
            KeyPurpose::Signing,
            KeyPurpose::KeyExchange,
            KeyPurpose::Authentication,
            KeyPurpose::KeyWrapping,
        ] {
            let json = serde_json::to_string(&purpose);
            assert!(json.is_ok());
            let deserialized: Result<KeyPurpose, _> =
                serde_json::from_str(json.as_ref().map_or("", String::as_str));
            assert!(deserialized.is_ok());
            assert_eq!(
                deserialized.unwrap_or_else(|_| panic!("Failed to deserialize {:?}", purpose)),
                purpose
            );
        }
    }

    #[test]
    fn test_rotation_reason_serializes_correctly_succeeds() {
        for reason in [
            RotationReason::Scheduled,
            RotationReason::Compromised,
            RotationReason::PolicyChange,
            RotationReason::Expiration,
            RotationReason::Manual,
        ] {
            let json = serde_json::to_string(&reason);
            assert!(json.is_ok());
            let deserialized: Result<RotationReason, _> =
                serde_json::from_str(json.as_ref().map_or("", String::as_str));
            assert!(deserialized.is_ok());
            assert_eq!(
                deserialized.unwrap_or_else(|_| panic!("Failed to deserialize {:?}", reason)),
                reason
            );
        }
    }

    #[test]
    fn test_destruction_method_serializes_correctly_succeeds() {
        for method in [
            DestructionMethod::Zeroization,
            DestructionMethod::CryptoErase,
            DestructionMethod::Manual,
        ] {
            let json = serde_json::to_string(&method);
            assert!(json.is_ok());
            let deserialized: Result<DestructionMethod, _> =
                serde_json::from_str(json.as_ref().map_or("", String::as_str));
            assert!(deserialized.is_ok());
            assert_eq!(
                deserialized.unwrap_or_else(|_| panic!("Failed to deserialize {:?}", method)),
                method
            );
        }
    }
}