toolkit-zero 5.11.0

A feature-selective Rust utility crate — a modular collection of opt-in utilities spanning encryption, HTTP networking, geolocation, and build-time fingerprinting. Enable only the features your project requires.
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
//! Time-locked key derivation.
//!
//! Derives a deterministic 32-byte key from a **time value** through a
//! three-pass heterogeneous KDF chain:
//!
//! | Pass | Algorithm | Role |
//! |------|-----------|------|
//! | 1 | **Argon2id** | PHC winner; sequential- and random-access memory-hard; GPU/ASIC-resistant |
//! | 2 | **scrypt**   | Independently designed memory-hard function (ROMix); orthogonal to Argon2id |
//! | 3 | **Argon2id** | Extends the chain depth with fresh parameters and a distinct salt |
//!
//! Using two *independently designed* memory-hard functions ensures the chain
//! remains strong even if a weakness is discovered in either algorithm.
//! Every intermediate KDF output is zeroized from memory before the subsequent
//! pass begins.
//!
//! # Two entry points
//!
//! | `params` argument                   | Path                | Intended use                                                         |
//! |-------------------------------------|---------------------|----------------------------------------------------------------------|
//! | `params: None` (+ all other `Some`) | `_at` — encryption  | Caller supplies cadence, time, precision, format, salts, and KDF parameters |
//! | `params: Some(p)` (rest `None`)     | `_now` — decryption | All settings are read from [`TimeLockParams`]; no additional input required |
//!
//! Async counterparts ([`timelock_async`]) are provided under the
//! `enc-timelock-async-keygen-now` and `enc-timelock-async-keygen-input` features;
//! they offload blocking KDF work to a dedicated thread, ensuring the calling
//! executor is never stalled.
//!
//! # Time input
//!
//! The KDF input is a short ASCII string derived from the time value at one
//! of three selectable precision levels.
//!
//! | [`TimePrecision`] | [`TimeFormat`] | Example string | Window   | Candidates/day |
//! |-------------------|----------------|----------------|----------|----------------|
//! | `Hour`    | `Hour24` | `"14"`        | 60 min   | 24             |
//! | `Hour`    | `Hour12` | `"02PM"`      | 60 min   | 12 unique × 2  |
//! | `Quarter` | `Hour24` | `"14:30"`     | 15 min   | 96             |
//! | `Quarter` | `Hour12` | `"02:30PM"`   | 15 min   | 48 unique × 2  |
//! | `Minute`  | `Hour24` | `"14:37"`     | 1 min    | 1440           |
//! | `Minute`  | `Hour12` | `"02:37PM"`   | 1 min    | 720 unique × 2 |
//!
//! > **`Hour12` note**: the same time slot recurs twice daily (AM + PM),
//! > making the derived key valid twice per day.  Use `Hour24` for a key
//! > that is uniquely valid once per day.
//!
//! > **Clock skew (`Minute` precision):** if both parties' clocks may diverge
//! > by up to one minute, derive keys for `now() − 1 min`, `now()`, and
//! > `now() + 1 min` and try each in turn. The additional cost is negligible
//! > relative to a single full KDF pass.
//!
//! # Salts
//!
//! [`TimeLockSalts`] holds three independent 32-byte random values — one per
//! KDF pass — generated at encryption time via [`TimeLockSalts::generate`].
//! Salts are **not secret**; they prevent precomputation attacks and must be
//! stored in plaintext alongside the ciphertext header. The identical salts
//! must be provided to the decryption call.
//!
//! # Memory safety
//!
//! All intermediate KDF outputs are wrapped in [`Zeroizing`] and overwritten
//! upon being dropped. [`TimeLockKey`] implements [`ZeroizeOnDrop`]; the final
//! 32-byte key material is scrubbed from memory the moment it goes out of scope.
//!
//! # Quick start
//!
//! The recommended entry point is the fluent [`TimelockBuilder`], which is
//! easier to read and less error-prone than the raw 7-argument [`timelock`] function:
//!
//! ```no_run
//! use toolkit_zero::encryption::timelock::*;
//!
//! // ── Encryption side (TimelockBuilder) ─────────────────────────────────
//! let salts = TimeLockSalts::generate();
//! let kdf   = KdfPreset::Balanced.params();
//!
//! let enc_key = TimelockBuilder::encrypt()
//!     .time(TimeLockTime::new(14, 37).unwrap())
//!     .salts(salts.clone())
//!     .kdf(kdf)
//!     .derive()
//!     .unwrap();
//!
//! let header = pack(TimePrecision::Minute, TimeFormat::Hour24,
//!                   &TimeLockCadence::None, salts, kdf);
//!
//! // ── Decryption side ───────────────────────────────────────────────────
//! let dec_key = TimelockBuilder::decrypt(header).derive().unwrap();
//! // enc_key.as_bytes() == dec_key.as_bytes() when called at 14:37 local time
//! ```
//!
//! The lower-level [`timelock`] and [`timelock_async`] functions accept the same
//! parameters positionally and remain available for advanced use cases.

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input"))]
mod helper;

#[cfg(feature = "backend-deps")]
pub mod backend_deps;

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
pub mod utility;
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
pub use utility::{TimeLockParams, pack, unpack};

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
use zeroize::{Zeroize, ZeroizeOnDrop};

// ─── time precision / format ──────────────────────────────────────────────────

/// The granularity at which the time value is quantised when constructing the
/// KDF input string.
///
/// Coarser precision yields a longer validity window, making it easier for a
/// legitimate user to produce the correct key; finer precision increases the
/// cost of time-sweeping attacks.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimePrecision {
    /// Quantise to the current **hour**.
    ///
    /// Input example: `"14"` (24-hour) | `"02PM"` (12-hour).  
    /// The derived key is valid for the entire 60-minute block.
    Hour,

    /// Quantise to the current **15-minute block** (minute snapped to
    /// 00, 15, 30, or 45).
    ///
    /// Input example: `"14:30"` (24-hour) | `"02:30PM"` (12-hour).  
    /// The derived key is valid for the 15-minute interval enclosing the
    /// chosen minute.
    Quarter,

    /// Quantise to the current **minute** (1-minute validity window).
    ///
    /// Input example: `"14:37"` (24-hour) | `"02:37PM"` (12-hour).  
    /// The strongest temporal constraint available — both parties' clocks must
    /// be NTP-synchronised to within ±30 seconds.
    Minute,
}

/// Clock representation used when formatting the time input string.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeFormat {
    /// 24-hour clock (`00`–`23`). Every time slot is unique within a day.
    Hour24,

    /// 12-hour clock (`01`–`12`) with an `AM`/`PM` suffix.
    /// Each time slot recurs **twice daily**.
    Hour12,
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Default for TimeFormat {
    /// Default clock representation is 24-hour (`Hour24`).
    fn default() -> Self { Self::Hour24 }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Default for TimePrecision {
    /// Default precision is per-minute (`Minute`).
    fn default() -> Self { Self::Minute }
}

// ─── schedule cadence ────────────────────────────────────────────────────────

/// Day of the week, Monday-indexed (Mon = 0 … Sun = 6).
///
/// Used as a cadence component in [`TimeLockCadence`] to constrain key
/// derivation to a specific weekday.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Weekday {
    /// The full English name of this weekday (e.g. `"Tuesday"`).
    pub fn name(self) -> &'static str {
        match self {
            Self::Monday    => "Monday",
            Self::Tuesday   => "Tuesday",
            Self::Wednesday => "Wednesday",
            Self::Thursday  => "Thursday",
            Self::Friday    => "Friday",
            Self::Saturday  => "Saturday",
            Self::Sunday    => "Sunday",
        }
    }

    /// Zero-based weekday number (Monday = 0, …, Sunday = 6).
    pub fn number(self) -> u8 {
        match self {
            Self::Monday    => 0,
            Self::Tuesday   => 1,
            Self::Wednesday => 2,
            Self::Thursday  => 3,
            Self::Friday    => 4,
            Self::Saturday  => 5,
            Self::Sunday    => 6,
        }
    }

    /// Convert from a `chrono::Weekday` value (used by the `_now` derivation path).
    #[cfg(feature = "enc-timelock-keygen-now")]
    pub(crate) fn from_chrono(w: chrono::Weekday) -> Self {
        match w {
            chrono::Weekday::Mon => Self::Monday,
            chrono::Weekday::Tue => Self::Tuesday,
            chrono::Weekday::Wed => Self::Wednesday,
            chrono::Weekday::Thu => Self::Thursday,
            chrono::Weekday::Fri => Self::Friday,
            chrono::Weekday::Sat => Self::Saturday,
            chrono::Weekday::Sun => Self::Sunday,
        }
    }
}

/// Calendar month (January = 1 … December = 12).
///
/// Used as a cadence component in [`TimeLockCadence`] to constrain key
/// derivation to a specific month of the year.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Month {
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December,
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Month {
    /// The full English name of this month (e.g. `"February"`).
    pub fn name(self) -> &'static str {
        match self {
            Self::January   => "January",
            Self::February  => "February",
            Self::March     => "March",
            Self::April     => "April",
            Self::May       => "May",
            Self::June      => "June",
            Self::July      => "July",
            Self::August    => "August",
            Self::September => "September",
            Self::October   => "October",
            Self::November  => "November",
            Self::December  => "December",
        }
    }

    /// 1-based month number (January = 1, …, December = 12).
    pub fn number(self) -> u8 {
        match self {
            Self::January   => 1,
            Self::February  => 2,
            Self::March     => 3,
            Self::April     => 4,
            Self::May       => 5,
            Self::June      => 6,
            Self::July      => 7,
            Self::August    => 8,
            Self::September => 9,
            Self::October   => 10,
            Self::November  => 11,
            Self::December  => 12,
        }
    }

    /// Maximum day count for this month.
    ///
    /// February is defined as 28 days; leap years are intentionally not
    /// accounted for to keep the cadence policy stable across years.
    pub fn max_days(self) -> u8 {
        match self {
            Self::February => 28,
            Self::April | Self::June | Self::September | Self::November => 30,
            _ => 31,
        }
    }

    /// Construct from a 1-based month number (1 = January … 12 = December).
    ///
    /// # Panics
    ///
    /// Panics if `n` is outside 1–12.
    #[cfg(feature = "enc-timelock-keygen-now")]
    pub(crate) fn from_number(n: u8) -> Self {
        match n {
            1  => Self::January,
            2  => Self::February,
            3  => Self::March,
            4  => Self::April,
            5  => Self::May,
            6  => Self::June,
            7  => Self::July,
            8  => Self::August,
            9  => Self::September,
            10 => Self::October,
            11 => Self::November,
            12 => Self::December,
            _  => panic!("Month::from_number: invalid month number {}", n),
        }
    }
}

/// Calendar cadence for a scheduled time-lock — constrains key derivation to
/// a recurring calendar pattern **in addition to** the time-of-day window.
///
/// Combine with a [`TimeLockTime`] on the encryption path to express policies
/// such as:
///
/// - *"valid only on Tuesdays at 18:00"* — `DayOfWeek(Weekday::Tuesday)` + 18 h
/// - *"valid only on the 1st of each month at 00:00"* — `DayOfMonth(1)` + 0 h
/// - *"valid only on Tuesdays in February at 06:00"* — `DayOfWeekInMonth(Weekday::Tuesday, Month::February)` + 6 h
///
/// On the decryption side, pass the cadence to [`pack`] (along with precision
/// and format) to obtain a [`TimeLockParams`] for storage in the ciphertext
/// header.
///
/// `TimeLockCadence::None` is equivalent to a call without any calendar
/// constraint — no calendar dimension is incorporated into the KDF input.
///
/// # Panics
///
/// Constructing [`DayOfMonthInMonth`](TimeLockCadence::DayOfMonthInMonth) is
/// always valid, but **key derivation panics** if the stored day exceeds the
/// month's maximum (for example, day 29 for February or day 31 for April).
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeLockCadence {
    /// No calendar constraint — behaves like a plain time-lock.
    ///
    /// Compact discriminant: `0`.
    None,

    /// Valid only on the specified weekday.
    ///
    /// Compact discriminant: `1`.
    DayOfWeek(Weekday),

    /// Valid only on the specified day of any month (1–31).
    ///
    /// Days 29–31 simply never match in shorter months.
    ///
    /// Compact discriminant: `2`.
    DayOfMonth(u8),

    /// Valid only during the specified month of any year.
    ///
    /// Compact discriminant: `3`.
    MonthOfYear(Month),

    /// Valid only on the specified weekday **and** during the specified month.
    ///
    /// Compact discriminant: `4`.
    DayOfWeekInMonth(Weekday, Month),

    /// Valid only on the specified day of the specified month.
    ///
    /// Returns [`TimeLockError::ForbiddenAction`] if the day is out of range for the month.
    ///
    /// Compact discriminant: `5`.
    DayOfMonthInMonth(u8, Month),

    /// Valid only on the specified weekday **and** the specified day of month.
    ///
    /// Days 29–31 do not match in shorter months.
    ///
    /// Compact discriminant: `6`.
    DayOfWeekAndDayOfMonth(Weekday, u8),
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Default for TimeLockCadence {
    /// Default cadence is `None` (no calendar constraint).
    fn default() -> Self { Self::None }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl TimeLockCadence {
    /// Returns the compact variant discriminant stored in
    /// [`TimeLockParams::cadence_variant`].
    pub fn variant_id(self) -> u8 {
        match self {
            Self::None                         => 0,
            Self::DayOfWeek(_)                 => 1,
            Self::DayOfMonth(_)                => 2,
            Self::MonthOfYear(_)               => 3,
            Self::DayOfWeekInMonth(_, _)       => 4,
            Self::DayOfMonthInMonth(_, _)      => 5,
            Self::DayOfWeekAndDayOfMonth(_, _) => 6,
        }
    }

    /// Produces the cadence prefix baked into the KDF input during the
    /// encryption (`_at`) path.
    ///
    /// The prefix is empty for `None`; otherwise it is `"<component>|"` or
    /// `"<a>+<b>|"` for composite variants.
    ///
    /// # Errors
    ///
    /// Returns [`TimeLockError::ForbiddenAction`] if `DayOfMonthInMonth(day, month)`
    /// has `day < 1` or `day > month.max_days()`.
    pub(crate) fn bake_string(self) -> Result<String, TimeLockError> {
        match self {
            Self::None                          => Ok(String::new()),
            Self::DayOfWeek(w)                  => Ok(format!("{}|", w.name())),
            Self::DayOfMonth(d)                 => Ok(format!("{}|", d)),
            Self::MonthOfYear(m)                => Ok(format!("{}|", m.name())),
            Self::DayOfWeekInMonth(w, m)        => Ok(format!("{}+{}|", w.name(), m.name())),
            Self::DayOfMonthInMonth(d, m)       => {
                let max = m.max_days();
                if d < 1 || d > max {
                    return Err(TimeLockError::ForbiddenAction(
                        "DayOfMonthInMonth: day is out of range for the specified month",
                    ));
                }
                Ok(format!("{}+{}|", d, m.name()))
            }
            Self::DayOfWeekAndDayOfMonth(w, d)  => Ok(format!("{}+{}|", w.name(), d)),
        }
    }
}

// ─── explicit time input ──────────────────────────────────────────────────────

/// An explicit time value supplied by the caller for encryption-time key
/// derivation.
///
/// `hour` is always expressed in **24-hour notation** (0–23) regardless of
/// the [`TimeFormat`] chosen for the KDF string — the format flag only
/// controls how the string is rendered, not how you supply the input.
///
/// # Example
///
/// ```
/// use toolkit_zero::encryption::timelock::TimeLockTime;
///
/// let t = TimeLockTime::new(14, 37).unwrap(); // 14:37 local (2:37 PM)
/// ```
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeLockTime {
    hour:   u32,  // 0–23
    minute: u32,  // 0–59
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl TimeLockTime {
    /// Construct a `TimeLockTime` from a 24-hour `hour` (0–23) and `minute`
    /// (0–59).
    ///
    /// Returns `None` if either value is out of range.
    pub fn new(hour: u32, minute: u32) -> Option<Self> {
        if hour > 23 || minute > 59 {
            return None;
        }
        Some(Self { hour, minute })
    }

    /// The hour component (0–23).
    #[inline]
    pub fn hour(self) -> u32 { self.hour }

    /// The minute component (0–59).
    #[inline]
    pub fn minute(self) -> u32 { self.minute }
}

// ─── KDF parameters ───────────────────────────────────────────────────────────

/// Argon2id parameters for one pass of the KDF chain.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Argon2PassParams {
    /// Memory usage in **KiB** (e.g. `131_072` = 128 MiB).
    pub m_cost: u32,
    /// Number of passes over memory (time cost).
    pub t_cost: u32,
    /// Degree of parallelism (lanes). Keep at `1` for single-threaded use.
    pub p_cost: u32,
}

/// scrypt parameters for the second pass of the KDF chain.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScryptPassParams {
    /// CPU/memory cost exponent: `N = 2^log_n`. Each increment doubles memory.
    pub log_n: u8,
    /// Block size (`r`). Standard value is `8`.
    pub r: u32,
    /// Parallelization factor (`p`). Keep at `1` for sequential derivation.
    pub p: u32,
}

/// Combined parameters for the full three-pass
/// Argon2id → scrypt → Argon2id KDF chain.
///
/// Prefer constructing via [`KdfPreset::params`] unless you have specific
/// tuning requirements.  All fields implement `Copy`, so this struct can be
/// stored inline in [`KdfPreset::Custom`].
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KdfParams {
    /// First  pass: Argon2id.
    pub pass1: Argon2PassParams,
    /// Second pass: scrypt.
    pub pass2: ScryptPassParams,
    /// Third  pass: Argon2id (different parameters and a distinct salt).
    pub pass3: Argon2PassParams,
}

// ─── presets ──────────────────────────────────────────────────────────────────

/// Pre-tuned [`KdfParams`] sets.
///
/// Pick the variant that matches your **target platform** and security goal.
/// Use [`Custom`](KdfPreset::Custom) to supply entirely your own parameters.
///
/// > **Why device-specific presets?**  Apple Silicon has exceptional memory
/// > bandwidth (unified memory, ~400 GB/s on M2).  The same parameters that
/// > take 2 seconds on an M2 may take 15+ seconds on a typical x86-64 server.
/// > Device-specific variants let you choose a cost that is _consistent_ across
/// > the hardware you actually deploy on.
///
/// ## Generic (cross-platform)
///
/// Suitable for any platform.  Use these when you don't know or don't control
/// the target hardware.
///
/// | Preset     | Peak RAM  | Est. Mac M2 | Est. x86-64  |
/// |------------|-----------|-------------|--------------|
/// | `Fast`     | ~128 MiB  | ~500 ms     | ~1.5 s       |
/// | `Balanced` | ~512 MiB  | ~2 s        | ~8–15 s      |
/// | `Paranoid` | ~768 MiB  | ~4–6 s      | ~20–30 s     |
///
/// ## Apple Silicon (`*Mac`)
///
/// Harder parameters calibrated for Apple Silicon's superior memory bandwidth.
/// All three tiers assume at least 8 GiB unified memory (all M-series chips).
///
/// | Preset        | Peak RAM | Est. Mac M2  | Est. Mac M3/M4 |
/// |---------------|----------|--------------|----------------|
/// | `FastMac`     | ~512 MiB | ~2 s         | faster         |
/// | `BalancedMac` | ~1 GiB   | ~5–12 s      | faster         |
/// | `ParanoidMac` | ~3 GiB   | ~30–60 s     | faster         |
///
/// ## x86-64 (`*X86`)
///
/// Equivalent to Generic; provided as explicit named variants so code
/// documents intent clearly.
///
/// | Preset        | Peak RAM  | Est. x86-64  |
/// |---------------|-----------|------------------|
/// | `FastX86`     | ~128 MiB  | ~1.5 s           |
/// | `BalancedX86` | ~512 MiB  | ~8–15 s          |
/// | `ParanoidX86` | ~768 MiB  | ~20–30 s         |
///
/// ## Linux ARM64 (`*Arm`)
///
/// Tuned for AWS Graviton3 / similar high-end ARM servers.  Raspberry Pi and
/// lower-end ARM boards will be slower.
///
/// | Preset        | Peak RAM  | Est. Graviton3 |
/// |---------------|-----------|----------------|
/// | `FastArm`     | ~256 MiB  | ~3 s           |
/// | `BalancedArm` | ~512 MiB  | ~10–20 s       |
/// | `ParanoidArm` | ~768 MiB  | ~30–50 s       |
///
/// ## Custom
///
/// `Custom(KdfParams)` lets you supply exactly the parameters you measured
/// and tuned for your own hardware.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KdfPreset {
    // ── generic (cross-platform) ─────────────────────────────────────────────

    /// ~128 MiB · scrypt 2¹⁶ · ~64 MiB, 3 iters each.
    Fast,
    /// ~512 MiB · scrypt 2¹⁷ · ~256 MiB, 4 iters each.
    Balanced,
    /// ~768 MiB · scrypt 2¹⁸ · ~512 MiB, 5 iters each.
    Paranoid,

    // ── Apple Silicon ─────────────────────────────────────────────────────────

    /// Dev / CI on macOS.  ~512 MiB · scrypt 2¹⁷ · ~256 MiB, 4 iters each.
    FastMac,
    /// Production on macOS (Apple Silicon).  ~1 GiB · scrypt 2¹⁸ · ~512 MiB, 4 iters each.
    BalancedMac,
    /// Maximum security on macOS.  ~3 GiB · scrypt 2²⁰ · ~1 GiB, 4 iters each.
    /// Assumes 8+ GiB unified memory (all M-series chips).
    ParanoidMac,

    // ── x86-64 ───────────────────────────────────────────────────────────────

    /// Dev / CI on x86-64.  Same params as `Fast`.
    FastX86,
    /// Production on x86-64.  Same params as `Balanced`.
    BalancedX86,
    /// Maximum security on x86-64.  Same params as `Paranoid`.
    ParanoidX86,

    // ── Linux ARM64 ──────────────────────────────────────────────────────────

    /// Dev / CI on Linux ARM64.  ~256 MiB · scrypt 2¹⁶ · ~128 MiB, 3 iters each.
    FastArm,
    /// Production on Linux ARM64.  ~512 MiB · scrypt 2¹⁷ · ~256 MiB, 5 iters each.
    BalancedArm,
    /// Maximum security on Linux ARM64.  ~768 MiB · scrypt 2¹⁸ · ~512 MiB, 5 iters each.
    ParanoidArm,

    // ── custom ────────────────────────────────────────────────────────────────

    /// Fully user-defined parameters.  Use when you have measured and tuned
    /// KDF cost on your own hardware.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # #[cfg(feature = "enc-timelock-keygen-input")]
    /// # {
    /// use toolkit_zero::encryption::timelock::*;
    /// let p = KdfPreset::Custom(KdfParams {
    ///     pass1: Argon2PassParams { m_cost: 262_144, t_cost: 3, p_cost: 1 },
    ///     pass2: ScryptPassParams { log_n: 16, r: 8, p: 1 },
    ///     pass3: Argon2PassParams { m_cost: 131_072, t_cost: 3, p_cost: 1 },
    /// });
    /// # }
    /// ```
    Custom(KdfParams),
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl KdfPreset {
    /// Return the [`KdfParams`] for this preset.
    pub fn params(self) -> KdfParams {
        // Fast = ~128 MiB · scrypt 2¹⁶ · ~64 MiB
        let fast = KdfParams {
            pass1: Argon2PassParams { m_cost:  131_072, t_cost: 3, p_cost: 1 },
            pass2: ScryptPassParams { log_n: 16, r: 8, p: 1 },
            pass3: Argon2PassParams { m_cost:   65_536, t_cost: 3, p_cost: 1 },
        };
        // Balanced = ~512 MiB · scrypt 2¹⁷ · ~256 MiB
        let balanced = KdfParams {
            pass1: Argon2PassParams { m_cost:  524_288, t_cost: 4, p_cost: 1 },
            pass2: ScryptPassParams { log_n: 17, r: 8, p: 1 },
            pass3: Argon2PassParams { m_cost:  262_144, t_cost: 4, p_cost: 1 },
        };
        // Paranoid = ~768 MiB · scrypt 2¹⁸ · ~512 MiB
        let paranoid = KdfParams {
            pass1: Argon2PassParams { m_cost:  786_432, t_cost: 5, p_cost: 1 },
            pass2: ScryptPassParams { log_n: 18, r: 8, p: 1 },
            pass3: Argon2PassParams { m_cost:  524_288, t_cost: 5, p_cost: 1 },
        };

        match self {
            // Generic / x86-64 (identical params, named for code clarity)
            KdfPreset::Fast    | KdfPreset::FastX86    => fast,
            KdfPreset::Balanced | KdfPreset::BalancedX86 => balanced,
            KdfPreset::Paranoid | KdfPreset::ParanoidX86 => paranoid,
            // Apple Silicon — calibrated for M-series memory bandwidth
            KdfPreset::FastMac    => balanced, // ~512 MiB
            KdfPreset::BalancedMac => KdfParams {
                pass1: Argon2PassParams { m_cost: 1_048_576, t_cost: 4, p_cost: 1 }, // 1 GiB
                pass2: ScryptPassParams { log_n: 18, r: 8, p: 1 },
                pass3: Argon2PassParams { m_cost:   524_288, t_cost: 4, p_cost: 1 },
            },
            KdfPreset::ParanoidMac => KdfParams {
                pass1: Argon2PassParams { m_cost: 3_145_728, t_cost: 4, p_cost: 1 }, // 3 GiB
                pass2: ScryptPassParams { log_n: 20, r: 8, p: 1 },
                pass3: Argon2PassParams { m_cost: 1_048_576, t_cost: 4, p_cost: 1 }, // 1 GiB
            },
            // Linux ARM64
            KdfPreset::FastArm => KdfParams {
                pass1: Argon2PassParams { m_cost:  262_144, t_cost: 3, p_cost: 1 }, // 256 MiB
                pass2: ScryptPassParams { log_n: 16, r: 8, p: 1 },
                pass3: Argon2PassParams { m_cost:  131_072, t_cost: 3, p_cost: 1 },
            },
            KdfPreset::BalancedArm => KdfParams {
                pass1: Argon2PassParams { m_cost:  524_288, t_cost: 5, p_cost: 1 }, // 512 MiB
                pass2: ScryptPassParams { log_n: 17, r: 8, p: 1 },
                pass3: Argon2PassParams { m_cost:  262_144, t_cost: 5, p_cost: 1 },
            },
            KdfPreset::ParanoidArm => KdfParams {
                pass1: Argon2PassParams { m_cost:  786_432, t_cost: 5, p_cost: 1 }, // 768 MiB
                pass2: ScryptPassParams { log_n: 18, r: 8, p: 1 },
                pass3: Argon2PassParams { m_cost:  524_288, t_cost: 5, p_cost: 1 },
            },
            // Custom
            KdfPreset::Custom(p) => p,
        }
    }
}

// ─── salts ────────────────────────────────────────────────────────────────────

/// Three independent 32-byte random salts — one per KDF pass.
///
/// Generate once at **encryption time** via [`TimeLockSalts::generate`] and
/// store 96 bytes in the ciphertext header.  The same `TimeLockSalts` **must**
/// be supplied to [`derive_key_now`] / [`derive_key_at`] at decryption time.
///
/// Salts are **not secret** — they only prevent precomputation attacks.
/// All three fields are zeroized when this value is dropped.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug, Clone)]
pub struct TimeLockSalts {
    /// Salt for the first Argon2id pass.
    pub s1: [u8; 32],
    /// Salt for the scrypt pass.
    pub s2: [u8; 32],
    /// Salt for the final Argon2id pass.
    pub s3: [u8; 32],
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl TimeLockSalts {
    /// Generate three independent 32-byte salts from the OS CSPRNG.
    pub fn generate() -> Self {
        use rand::RngCore as _;
        let mut rng = rand::rng();
        let mut s = Self { s1: [0u8; 32], s2: [0u8; 32], s3: [0u8; 32] };
        rng.fill_bytes(&mut s.s1);
        rng.fill_bytes(&mut s.s2);
        rng.fill_bytes(&mut s.s3);
        s
    }

    /// Construct from raw bytes (e.g. when loading from a ciphertext header).
    pub fn from_bytes(s1: [u8; 32], s2: [u8; 32], s3: [u8; 32]) -> Self {
        Self { s1, s2, s3 }
    }

    /// Serialize to 96 contiguous bytes (`s1 ∥ s2 ∥ s3`) for header storage.
    pub fn to_bytes(&self) -> [u8; 96] {
        let mut out = [0u8; 96];
        out[..32].copy_from_slice(&self.s1);
        out[32..64].copy_from_slice(&self.s2);
        out[64..].copy_from_slice(&self.s3);
        out
    }

    /// Deserialize from 96 contiguous bytes produced by [`to_bytes`].
    pub fn from_slice(b: &[u8; 96]) -> Self {
        let mut s1 = [0u8; 32]; s1.copy_from_slice(&b[..32]);
        let mut s2 = [0u8; 32]; s2.copy_from_slice(&b[32..64]);
        let mut s3 = [0u8; 32]; s3.copy_from_slice(&b[64..]);
        Self { s1, s2, s3 }
    }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Zeroize for TimeLockSalts {
    fn zeroize(&mut self) {
        self.s1.zeroize();
        self.s2.zeroize();
        self.s3.zeroize();
    }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Drop for TimeLockSalts {
    fn drop(&mut self) { self.zeroize(); }
}

// ─── output ───────────────────────────────────────────────────────────────────

/// A derived 32-byte time-locked key.
///
/// The inner bytes are **automatically overwritten** (`ZeroizeOnDrop`) the
/// moment this value is dropped.  Access the key via [`as_bytes`](Self::as_bytes).
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
pub struct TimeLockKey([u8; 32]);

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl TimeLockKey {
    /// Borrow the raw 32-byte key.
    ///
    /// The reference is valid only while this `TimeLockKey` is alive.  If you
    /// must copy the bytes into another buffer, protect it with [`Zeroize`] too.
    #[inline]
    pub fn as_bytes(&self) -> &[u8; 32] { &self.0 }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Zeroize for TimeLockKey {
    #[inline]
    fn zeroize(&mut self) { self.0.zeroize(); }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl ZeroizeOnDrop for TimeLockKey {}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl Drop for TimeLockKey {
    fn drop(&mut self) { self.zeroize(); }
}

// ─── error ────────────────────────────────────────────────────────────────────

/// Errors returned by the `derive_key_*` functions.
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
#[derive(Debug)]
#[non_exhaustive]
pub enum TimeLockError {
    /// An Argon2id pass failed (invalid parameters or internal error).
    Argon2(String),
    /// The scrypt pass failed (invalid parameters or output length).
    Scrypt(String),
    /// The OS clock returned an unusable value.
    #[cfg(feature = "enc-timelock-keygen-now")]
    ClockUnavailable,
    /// A [`TimeLockTime`] field was out of range.
    #[cfg(feature = "enc-timelock-keygen-input")]
    InvalidTime(String),
    /// The async task panicked inside `spawn_blocking`.
    #[cfg(any(feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
    TaskPanic(String),
    /// The caller passed `Some(time)` but `enc-timelock-keygen-input` is not
    /// active, or passed `None` but `enc-timelock-keygen-now` is not active.
    ForbiddenAction(&'static str),
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl std::fmt::Display for TimeLockError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Argon2(s)         => write!(f, "Argon2id error: {s}"),
            Self::Scrypt(s)         => write!(f, "scrypt error: {s}"),
            #[cfg(feature = "enc-timelock-keygen-now")]
            Self::ClockUnavailable  => write!(f, "system clock unavailable"),
            #[cfg(feature = "enc-timelock-keygen-input")]
            Self::InvalidTime(s)    => write!(f, "invalid time input: {s}"),
            #[cfg(any(feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
            Self::TaskPanic(s)      => write!(f, "KDF task panicked: {s}"),
            Self::ForbiddenAction(s) => write!(f, "action not permitted: {s}"),
        }
    }
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl std::error::Error for TimeLockError {}

// ─── internal sync API ───────────────────────────────────────────────────────

/// Derive a 32-byte key from the **current system time** (decryption path).
///
/// The OS wall clock is read inside this call — the caller supplies no time
/// value.  Use this on the **decryption side** so the user never needs to
/// re-enter the unlock time.
///
/// The `precision`, `format`, and `salts` must match exactly what was used
/// during [`derive_key_at`] at encryption time (store them in the header).
///
/// # Errors
///
/// Returns [`TimeLockError`] if the system clock is unavailable or any KDF
/// pass fails.
///
/// # Example
///
/// ```ignore
/// # use toolkit_zero::encryption::timelock::*;
/// let salts = TimeLockSalts::generate();
/// let key = timelock(
///     TimeLockCadence::None,
///     None,
///     TimePrecision::Minute,
///     TimeFormat::Hour24,
///     &salts,
///     &KdfPreset::Balanced.params(),
/// ).unwrap();
/// ```
#[allow(dead_code)]
#[cfg(feature = "enc-timelock-keygen-now")]
fn derive_key_now(
    precision: TimePrecision,
    format:    TimeFormat,
    salts:     &TimeLockSalts,
    params:    &KdfParams,
) -> Result<TimeLockKey, TimeLockError> {
    let time_str = helper::format_time_now(precision, format)?;
    helper::run_kdf_chain(time_str.into_bytes(), salts, params)
}

/// Derive a 32-byte key from an **explicit [`TimeLockTime`]** (encryption path).
///
/// The caller supplies the time at which decryption should be permitted.
/// Use this on the **encryption side** — the user chooses `(hour, minute)` and
/// the result is the key that will only be reproducible by [`derive_key_now`]
/// called within the matching time window.
///
/// # Errors
///
/// Returns [`TimeLockError`] if the time value is invalid or any KDF pass
/// fails.
///
/// # Example
///
/// ```ignore
/// # use toolkit_zero::encryption::timelock::*;
/// let salts = TimeLockSalts::generate();
/// let at = TimeLockTime::new(14, 37).unwrap();
/// let key = timelock(
///     TimeLockCadence::None,
///     Some(at),
///     TimePrecision::Minute,
///     TimeFormat::Hour24,
///     &salts,
///     &KdfPreset::Balanced.params(),
/// ).unwrap();
/// ```
#[allow(dead_code)]
#[cfg(feature = "enc-timelock-keygen-input")]
fn derive_key_at(
    time:      TimeLockTime,
    precision: TimePrecision,
    format:    TimeFormat,
    salts:     &TimeLockSalts,
    params:    &KdfParams,
) -> Result<TimeLockKey, TimeLockError> {
    let time_str = helper::format_time_at(time, precision, format)?;
    helper::run_kdf_chain(time_str.into_bytes(), salts, params)
}

// ─── internal async API ──────────────────────────────────────────────────────

/// Async variant of [`derive_key_now`].
///
/// Offloads the blocking Argon2id + scrypt work to a Tokio blocking thread
/// so the calling future's executor is never stalled during derivation.
///
/// Takes `salts` and `params` by **value** (required for `'static` move into
/// `spawn_blocking`); both are zeroized before the async task exits.
///
/// Requires the `enc-timelock-async` feature.
///
/// # Errors
///
/// Returns [`TimeLockError`] if the system clock is unavailable, any KDF
/// pass fails, or the spawned task panics.
#[allow(dead_code)]
#[cfg(feature = "enc-timelock-async-keygen-now")]
async fn derive_key_now_async(
    precision: TimePrecision,
    format:    TimeFormat,
    salts:     TimeLockSalts,
    params:    KdfParams,
) -> Result<TimeLockKey, TimeLockError> {
    tokio::task::spawn_blocking(move || derive_key_now(precision, format, &salts, &params))
        .await
        .map_err(|e| TimeLockError::TaskPanic(e.to_string()))?
}

/// Async variant of [`derive_key_at`].
///
/// Offloads the blocking Argon2id + scrypt work to a Tokio blocking thread.
/// Takes `salts` and `params` by **value**; both are zeroized on drop.
///
/// Requires the `enc-timelock-async-keygen-input` feature.
#[allow(dead_code)]
#[cfg(feature = "enc-timelock-async-keygen-input")]
async fn derive_key_at_async(
    time:      TimeLockTime,
    precision: TimePrecision,
    format:    TimeFormat,
    salts:     TimeLockSalts,
    params:    KdfParams,
) -> Result<TimeLockKey, TimeLockError> {
    tokio::task::spawn_blocking(move || derive_key_at(time, precision, format, &salts, &params))
        .await
        .map_err(|e| TimeLockError::TaskPanic(e.to_string()))?
}

// ─── internal scheduled sync API ─────────────────────────────────────────────

/// Derive a 32-byte key from a [`TimeLockCadence`] anchor plus an **explicit
/// [`TimeLockTime`]** (encryption path).
///
/// Extends [`derive_key_at`] with a calendar constraint.  The KDF input
/// is `"<cadence_prefix><time_string>"`.  For [`TimeLockCadence::None`] the
/// prefix is empty, producing a result identical to [`derive_key_at`].
///
/// Store [`pack`]ed settings alongside the salts in the ciphertext header so
/// the decryption side can reconstruct the correct KDF input via
/// [`derive_key_scheduled_now`].
///
/// # Panics
///
/// Panics if `cadence` is [`TimeLockCadence::DayOfMonthInMonth`] with a day
/// that exceeds the month's maximum (e.g. day 29 for February).
///
/// # Errors
///
/// Returns [`TimeLockError`] if the time value is out of range or any KDF
/// pass fails.
///
/// # Example
///
/// ```ignore
/// # use toolkit_zero::encryption::timelock::*;
/// let salts = TimeLockSalts::generate();
/// let kdf   = KdfPreset::Balanced.params();
/// let t     = TimeLockTime::new(18, 0).unwrap();
/// // Use the public timelock() entry point (params = None → _at path):
/// let key = timelock(
///     Some(TimeLockCadence::DayOfWeek(Weekday::Tuesday)),
///     Some(t),
///     Some(TimePrecision::Hour),
///     Some(TimeFormat::Hour24),
///     Some(salts),
///     Some(kdf),
///     None,
/// ).unwrap();
/// // key is valid only at 18:xx on any Tuesday
/// ```
#[cfg(feature = "enc-timelock-keygen-input")]
fn derive_key_scheduled_at(
    cadence:   TimeLockCadence,
    time:      TimeLockTime,
    precision: TimePrecision,
    format:    TimeFormat,
    salts:     &TimeLockSalts,
    params:    &KdfParams,
) -> Result<TimeLockKey, TimeLockError> {
    let cadence_part = cadence.bake_string()?;
    let time_part    = helper::format_time_at(time, precision, format)?;
    let full         = format!("{}{}", cadence_part, time_part);
    helper::run_kdf_chain(full.into_bytes(), salts, params)
}

/// Derive a 32-byte key from the **current system time and calendar state**
/// using the settings stored in a [`TimeLockParams`] (decryption path).
///
/// Extends [`derive_key_now`] with calendar awareness.  The `cadence_variant`
/// field in `timelock_params` determines which calendar dimension(s) are read
/// from the live clock, making the KDF input identical to what
/// [`derive_key_scheduled_at`] produced on the matching slot.
///
/// # Errors
///
/// Returns [`TimeLockError`] if the system clock is unavailable or any KDF
/// pass fails.
///
/// # Example
///
/// ```ignore
/// # use toolkit_zero::encryption::timelock::*;
/// // Load header from ciphertext then call with params = Some(header):
/// let dec_key = timelock(
///     None, None, None, None, None, None,
///     Some(header),  // header: TimeLockParams loaded from ciphertext
/// ).unwrap();
/// ```
#[cfg(feature = "enc-timelock-keygen-now")]
fn derive_key_scheduled_now(
    timelock_params: &TimeLockParams,
) -> Result<TimeLockKey, TimeLockError> {
    let (precision, format, cadence_variant) = utility::unpack(timelock_params);
    let cadence_part = helper::bake_cadence_now(cadence_variant)?;
    let time_part    = helper::format_time_now(precision, format)?;
    let full         = format!("{}{}", cadence_part, time_part);
    helper::run_kdf_chain(full.into_bytes(), &timelock_params.salts, &timelock_params.kdf_params)
}

// ─── internal scheduled async API ───────────────────────────────────────────

/// Async variant of [`derive_key_scheduled_at`].
///
/// Offloads the blocking KDF work to a Tokio blocking thread.  Takes `salts`
/// and `params` by **value** (required for `'static` move into
/// `spawn_blocking`); both are zeroized on drop.  `cadence` and `time` are
/// `Copy`.
///
/// Requires the `enc-timelock-async-keygen-input` feature.
#[cfg(feature = "enc-timelock-async-keygen-input")]
async fn derive_key_scheduled_at_async(
    cadence:   TimeLockCadence,
    time:      TimeLockTime,
    precision: TimePrecision,
    format:    TimeFormat,
    salts:     TimeLockSalts,
    params:    KdfParams,
) -> Result<TimeLockKey, TimeLockError> {
    tokio::task::spawn_blocking(move || {
        derive_key_scheduled_at(cadence, time, precision, format, &salts, &params)
    })
    .await
    .map_err(|e| TimeLockError::TaskPanic(e.to_string()))?
}

/// Async variant of [`derive_key_scheduled_now`].
///
/// Offloads the blocking KDF work to a Tokio blocking thread.  Takes
/// `timelock_params` by **value**; the [`TimeLockSalts`] inside are
/// zeroized on drop.
///
/// Requires the `enc-timelock-async-keygen-now` feature.
#[cfg(feature = "enc-timelock-async-keygen-now")]
async fn derive_key_scheduled_now_async(
    timelock_params: TimeLockParams,
) -> Result<TimeLockKey, TimeLockError> {
    tokio::task::spawn_blocking(move || {
        derive_key_scheduled_now(&timelock_params)
    })
    .await
    .map_err(|e| TimeLockError::TaskPanic(e.to_string()))?
}

// ─── public API ───────────────────────────────────────────────────────────────

/// Derive a 32-byte time-locked key — unified sync entry point.
///
/// ## Encryption path (`params = None`)
///
/// Set `params` to `None` and supply all of `cadence`, `time`, `precision`,
/// `format`, `salts`, and `kdf` as `Some(...)`.  Requires the
/// `enc-timelock-keygen-input` feature.  After calling, use [`pack`] with the
/// same arguments to produce a [`TimeLockParams`] header for the ciphertext.
///
/// ## Decryption path (`params = Some(p)`)
///
/// Set `params` to `Some(header)` where `header` is the [`TimeLockParams`]
/// read from the ciphertext.  All other arguments are ignored and may be
/// `None`.  Requires the `enc-timelock-keygen-now` feature.
///
/// # Errors
///
/// - [`TimeLockError::ForbiddenAction`] if the required feature is not active,
///   or if the `_at` path is taken but any required `Option` argument is `None`.
/// - [`TimeLockError::Argon2`] / [`TimeLockError::Scrypt`] on KDF failure.
/// - [`TimeLockError::ClockUnavailable`] if the OS clock is unusable (`_now` path).
///
/// # Example
///
/// ```no_run
/// # use toolkit_zero::encryption::timelock::*;
/// let salts = TimeLockSalts::generate();
/// let kdf   = KdfPreset::BalancedMac.params();
///
/// // Encryption side — lock to every Tuesday at 18:00
/// let enc_key = timelock(
///     Some(TimeLockCadence::DayOfWeek(Weekday::Tuesday)),
///     Some(TimeLockTime::new(18, 0).unwrap()),
///     Some(TimePrecision::Hour),
///     Some(TimeFormat::Hour24),
///     Some(salts.clone()),
///     Some(kdf),
///     None,
/// ).unwrap();
///
/// // Pack settings + salts + kdf into header; store in ciphertext.
/// let header = pack(TimePrecision::Hour, TimeFormat::Hour24,
///                   &TimeLockCadence::DayOfWeek(Weekday::Tuesday), salts, kdf);
///
/// // Decryption side — call on a Tuesday at 18:xx:
/// let dec_key = timelock(
///     None, None, None, None, None, None,
///     Some(header),
/// ).unwrap();
/// // enc_key.as_bytes() == dec_key.as_bytes() when called at the right time
/// ```
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input"))]
pub fn timelock(
    cadence:   Option<TimeLockCadence>,
    time:      Option<TimeLockTime>,
    precision: Option<TimePrecision>,
    format:    Option<TimeFormat>,
    salts:     Option<TimeLockSalts>,
    kdf:       Option<KdfParams>,
    params:    Option<TimeLockParams>,
) -> Result<TimeLockKey, TimeLockError> {
    if let Some(p) = params {
        // _now (decryption) path: all settings come from TimeLockParams.
        let _ = (cadence, time, precision, format, salts, kdf);  // unused on this path
        #[cfg(not(feature = "enc-timelock-keygen-now"))]
        return Err(TimeLockError::ForbiddenAction(
            "enc-timelock-keygen-now feature is required for the _now (decryption) path"
        ));
        #[cfg(feature = "enc-timelock-keygen-now")]
        return derive_key_scheduled_now(&p);
    } else {
        // _at (encryption) path: caller must supply all other arguments.
        #[cfg(not(feature = "enc-timelock-keygen-input"))]
        return Err(TimeLockError::ForbiddenAction(
            "enc-timelock-keygen-input feature is required for the _at (encryption) path; \
             pass Some(TimeLockParams) for the decryption path (requires enc-timelock-keygen-now)"
        ));
        #[cfg(feature = "enc-timelock-keygen-input")]
        {
            let c  = cadence.ok_or(TimeLockError::ForbiddenAction("_at path: cadence must be Some"))?;
            let t  = time.ok_or(TimeLockError::ForbiddenAction("_at path: time must be Some"))?;
            let pr = precision.ok_or(TimeLockError::ForbiddenAction("_at path: precision must be Some"))?;
            let fm = format.ok_or(TimeLockError::ForbiddenAction("_at path: format must be Some"))?;
            let sl = salts.ok_or(TimeLockError::ForbiddenAction("_at path: salts must be Some"))?;
            let kd = kdf.ok_or(TimeLockError::ForbiddenAction("_at path: kdf must be Some"))?;
            return derive_key_scheduled_at(c, t, pr, fm, &sl, &kd);
        }
    }
}

/// Derive a 32-byte time-locked key — unified async entry point.
///
/// Async counterpart of [`timelock`].  Same `params`-based routing: set
/// `params = Some(header)` for the **decryption** path, or `params = None`
/// with all other arguments as `Some(...)` for the **encryption** path.
/// All arguments are taken by value; the blocking KDF work is offloaded to a
/// Tokio blocking thread.
///
/// # Errors
///
/// Same as [`timelock`], plus [`TimeLockError::TaskPanic`] if the spawned
/// task panics.
#[cfg(any(feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
pub async fn timelock_async(
    cadence:   Option<TimeLockCadence>,
    time:      Option<TimeLockTime>,
    precision: Option<TimePrecision>,
    format:    Option<TimeFormat>,
    salts:     Option<TimeLockSalts>,
    kdf:       Option<KdfParams>,
    params:    Option<TimeLockParams>,
) -> Result<TimeLockKey, TimeLockError> {
    if let Some(p) = params {
        let _ = (cadence, time, precision, format, salts, kdf);
        #[cfg(not(feature = "enc-timelock-async-keygen-now"))]
        return Err(TimeLockError::ForbiddenAction(
            "enc-timelock-async-keygen-now feature is required for the async _now (decryption) path"
        ));
        #[cfg(feature = "enc-timelock-async-keygen-now")]
        return derive_key_scheduled_now_async(p).await;
    } else {
        #[cfg(not(feature = "enc-timelock-async-keygen-input"))]
        return Err(TimeLockError::ForbiddenAction(
            "enc-timelock-async-keygen-input feature is required for the async _at (encryption) path"
        ));
        #[cfg(feature = "enc-timelock-async-keygen-input")]
        {
            let c  = cadence.ok_or(TimeLockError::ForbiddenAction("_at path: cadence must be Some"))?;
            let t  = time.ok_or(TimeLockError::ForbiddenAction("_at path: time must be Some"))?;
            let pr = precision.ok_or(TimeLockError::ForbiddenAction("_at path: precision must be Some"))?;
            let fm = format.ok_or(TimeLockError::ForbiddenAction("_at path: format must be Some"))?;
            let sl = salts.ok_or(TimeLockError::ForbiddenAction("_at path: salts must be Some"))?;
            let kd = kdf.ok_or(TimeLockError::ForbiddenAction("_at path: kdf must be Some"))?;
            return derive_key_scheduled_at_async(c, t, pr, fm, sl, kd).await;
        }
    }
}

// ─── builder ─────────────────────────────────────────────────────────────────

/// Fluent builder for [`timelock`] / [`timelock_async`] key derivation.
///
/// Provides a readable alternative to the 7-positional-argument `timelock()` function.
/// Create a builder via [`TimelockBuilder::encrypt`] (encryption path, `_at`) or
/// [`TimelockBuilder::decrypt`] (decryption path, `_now`), optionally configure
/// it with setter methods, then call [`derive`](Self::derive) or
/// [`derive_async`](Self::derive_async).
///
/// ## Encryption (key-at path)
///
/// All of `time`, `salts`, and `kdf` are **required**.  `cadence`, `precision`, and
/// `format` are optional and fall back to sensible defaults:
/// * `cadence` → [`TimeLockCadence::None`] (no calendar constraint)
/// * `precision` → [`TimePrecision::Minute`]
/// * `format` → [`TimeFormat::Hour24`]
///
/// ```no_run
/// # use toolkit_zero::encryption::timelock::*;
/// let salts = TimeLockSalts::generate();
/// let kdf   = KdfPreset::Balanced.params();
///
/// let key = TimelockBuilder::encrypt()
///     .time(TimeLockTime::new(14, 37).unwrap())
///     .salts(salts)
///     .kdf(kdf)
///     .derive()
///     .unwrap();
/// ```
///
/// ## Decryption (key-now path)
///
/// Pass the [`TimeLockParams`] header stored in the ciphertext.  No other
/// configuration is required; all settings are read from `params`.
///
/// ```no_run
/// # use toolkit_zero::encryption::timelock::*;
/// # let header: TimeLockParams = todo!();
/// let key = TimelockBuilder::decrypt(header).derive().unwrap();
/// ```
#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
pub struct TimelockBuilder {
    cadence:   Option<TimeLockCadence>,
    time:      Option<TimeLockTime>,
    precision: Option<TimePrecision>,
    format:    Option<TimeFormat>,
    salts:     Option<TimeLockSalts>,
    kdf:       Option<KdfParams>,
    params:    Option<TimeLockParams>,
}

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
impl TimelockBuilder {
    /// Begin configuring an **encryption** (key-at) derivation.
    ///
    /// Requires `enc-timelock-keygen-input` (or async variant) to call
    /// [`derive`](Self::derive) / [`derive_async`](Self::derive_async).
    #[cfg(any(feature = "enc-timelock-keygen-input", feature = "enc-timelock-async-keygen-input"))]
    pub fn encrypt() -> Self {
        Self {
            cadence:   Some(TimeLockCadence::None),
            time:      None,
            precision: Some(TimePrecision::Minute),
            format:    Some(TimeFormat::Hour24),
            salts:     None,
            kdf:       None,
            params:    None,
        }
    }

    /// Begin configuring a **decryption** (key-now) derivation from a stored header.
    ///
    /// Requires `enc-timelock-keygen-now` (or async variant) to call
    /// [`derive`](Self::derive) / [`derive_async`](Self::derive_async).
    #[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-async-keygen-now"))]
    pub fn decrypt(params: TimeLockParams) -> Self {
        Self {
            cadence:   None,
            time:      None,
            precision: None,
            format:    None,
            salts:     None,
            kdf:       None,
            params:    Some(params),
        }
    }

    /// Set the calendar cadence (default: `TimeLockCadence::None`).
    pub fn cadence(mut self, cadence: TimeLockCadence) -> Self {
        self.cadence = Some(cadence);
        self
    }

    /// Set the explicit lock time (required for the encryption path).
    pub fn time(mut self, time: TimeLockTime) -> Self {
        self.time = Some(time);
        self
    }

    /// Set the time precision (default: `TimePrecision::Minute`).
    pub fn precision(mut self, precision: TimePrecision) -> Self {
        self.precision = Some(precision);
        self
    }

    /// Set the clock format (default: `TimeFormat::Hour24`).
    pub fn format(mut self, format: TimeFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Set the KDF salts (required for the encryption path).
    pub fn salts(mut self, salts: TimeLockSalts) -> Self {
        self.salts = Some(salts);
        self
    }

    /// Set the KDF parameters (required for the encryption path).
    pub fn kdf(mut self, kdf: KdfParams) -> Self {
        self.kdf = Some(kdf);
        self
    }

    /// Derive the key synchronously.
    ///
    /// Delegates directly to [`timelock`].
    #[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input"))]
    pub fn derive(self) -> Result<TimeLockKey, TimeLockError> {
        timelock(
            self.cadence,
            self.time,
            self.precision,
            self.format,
            self.salts,
            self.kdf,
            self.params,
        )
    }

    /// Derive the key asynchronously.
    ///
    /// Delegates directly to [`timelock_async`]. The blocking KDF work is
    /// offloaded to a Tokio blocking thread.
    #[cfg(any(feature = "enc-timelock-async-keygen-now", feature = "enc-timelock-async-keygen-input"))]
    pub async fn derive_async(self) -> Result<TimeLockKey, TimeLockError> {
        timelock_async(
            self.cadence,
            self.time,
            self.precision,
            self.format,
            self.salts,
            self.kdf,
            self.params,
        ).await
    }
}

// ─── tests ────────────────────────────────────────────────────────────────────

#[cfg(any(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input"))]
#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(all(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input"))]
    use chrono::Timelike as _;

    fn fast() -> KdfParams {
        // Minimal params for fast test execution — not a real security preset.
        KdfParams {
            pass1: Argon2PassParams { m_cost: 32_768, t_cost: 1, p_cost: 1 },
            pass2: ScryptPassParams { log_n: 13, r: 8, p: 1 },
            pass3: Argon2PassParams { m_cost: 16_384, t_cost: 1, p_cost: 1 },
        }
    }
    fn salts() -> TimeLockSalts   { TimeLockSalts::generate() }

    // ── TimeLockTime construction ─────────────────────────────────────────

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn timelocktime_valid_range() {
        assert!(TimeLockTime::new(0,  0).is_some());
        assert!(TimeLockTime::new(23, 59).is_some());
        assert!(TimeLockTime::new(14, 37).is_some());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn timelocktime_invalid_range() {
        assert!(TimeLockTime::new(24,  0).is_none(), "hour=24 should fail");
        assert!(TimeLockTime::new( 0, 60).is_none(), "minute=60 should fail");
        assert!(TimeLockTime::new(99, 99).is_none());
    }

    // ── format_components ────────────────────────────────────────────────

    #[test]
    fn format_hour_24h() {
        let s = helper::format_components(14, 37, TimePrecision::Hour, TimeFormat::Hour24);
        assert_eq!(s, "14");
    }

    #[test]
    fn format_hour_12h() {
        let s_pm = helper::format_components(14,  0, TimePrecision::Hour, TimeFormat::Hour12);
        let s_am = helper::format_components( 2,  0, TimePrecision::Hour, TimeFormat::Hour12);
        assert_eq!(s_pm, "02PM");
        assert_eq!(s_am, "02AM");
    }

    #[test]
    fn format_quarter_snaps_correctly() {
        // 37 should snap to 30; 15 → 15; 0 → 0; 59 → 45
        assert_eq!(helper::format_components(14, 37, TimePrecision::Quarter, TimeFormat::Hour24), "14:30");
        assert_eq!(helper::format_components(14, 15, TimePrecision::Quarter, TimeFormat::Hour24), "14:15");
        assert_eq!(helper::format_components(14,  0, TimePrecision::Quarter, TimeFormat::Hour24), "14:00");
        assert_eq!(helper::format_components(14, 59, TimePrecision::Quarter, TimeFormat::Hour24), "14:45");
    }

    #[test]
    fn format_minute_exact() {
        let s = helper::format_components(9, 5, TimePrecision::Minute, TimeFormat::Hour24);
        assert_eq!(s, "09:05");
    }

    // ── derive_key_at: determinism ────────────────────────────────────────

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn at_same_inputs_same_key() {
        let s = salts();
        let t = TimeLockTime::new(14, 37).unwrap();
        let k1 = derive_key_at(t, TimePrecision::Minute, TimeFormat::Hour24, &s, &fast()).unwrap();
        // Regenerate salts from their raw bytes to prove serialization round-trip too.
        let s2 = TimeLockSalts::from_slice(&s.to_bytes());
        let k2 = derive_key_at(t, TimePrecision::Minute, TimeFormat::Hour24, &s2, &fast()).unwrap();
        assert_eq!(k1.as_bytes(), k2.as_bytes());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn at_different_salts_different_key() {
        let t = TimeLockTime::new(14, 37).unwrap();
        let k1 = derive_key_at(t, TimePrecision::Minute, TimeFormat::Hour24, &salts(), &fast()).unwrap();
        let k2 = derive_key_at(t, TimePrecision::Minute, TimeFormat::Hour24, &salts(), &fast()).unwrap();
        assert_ne!(k1.as_bytes(), k2.as_bytes());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn at_different_time_different_key() {
        let s = salts();
        let t1 = TimeLockTime::new(14, 37).unwrap();
        let t2 = TimeLockTime::new(14, 38).unwrap();
        let k1 = derive_key_at(t1, TimePrecision::Minute, TimeFormat::Hour24, &s, &fast()).unwrap();
        let k2 = derive_key_at(t2, TimePrecision::Minute, TimeFormat::Hour24, &s, &fast()).unwrap();
        assert_ne!(k1.as_bytes(), k2.as_bytes());
    }

    // ── derive_key_now: liveness ──────────────────────────────────────────

    #[cfg(feature = "enc-timelock-keygen-now")]
    #[test]
    fn now_returns_nonzero_key() {
        let k = derive_key_now(TimePrecision::Hour, TimeFormat::Hour24, &salts(), &fast()).unwrap();
        assert_ne!(k.as_bytes(), &[0u8; 32]);
    }

    #[cfg(all(feature = "enc-timelock-keygen-now", feature = "enc-timelock-keygen-input"))]
    #[test]
    fn now_and_at_same_minute_match() {
        // Build a TimeLockTime from the current clock and confirm it produces
        // the same key as derive_key_now with Minute precision.
        let now = chrono::Local::now();
        let t = TimeLockTime::new(now.hour(), now.minute()).unwrap();
        let s = salts();
        let kn = derive_key_now(TimePrecision::Minute, TimeFormat::Hour24, &s, &fast()).unwrap();
        let ka = derive_key_at(t, TimePrecision::Minute, TimeFormat::Hour24, &s, &fast()).unwrap();
        assert_eq!(
            kn.as_bytes(), ka.as_bytes(),
            "now and explicit current time must produce the same key"
        );
    }

    // ── salt serialization round-trip ─────────────────────────────────────

    #[test]
    fn salt_round_trip() {
        let s = salts();
        let b = s.to_bytes();
        let s2 = TimeLockSalts::from_slice(&b);
        assert_eq!(s.s1, s2.s1);
        assert_eq!(s.s2, s2.s2);
        assert_eq!(s.s3, s2.s3);
    }

    // ── Custom variant ───────────────────────────────────────────────────

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn custom_params_works() {
        // Verify Custom(KdfParams) goes through the code path without failing.
        let preset = KdfPreset::Custom(KdfPreset::Fast.params());
        let t = TimeLockTime::new(10, 0).unwrap();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &preset.params())
            .expect("Custom params should succeed");
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn custom_params_roundtrip_eq() {
        let p = KdfPreset::Fast.params();
        assert_eq!(KdfPreset::Custom(p).params(), p);
    }

    // ── Generic preset smoke tests (slow) ────────────────────────────────

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    #[ignore = "slow (~400–600 ms) — run with `cargo test -- --ignored`"]
    fn balanced_preset_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::Balanced.params())
            .expect("Balanced should succeed");
        println!("Balanced (generic): {:?}", start.elapsed());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    #[ignore = "slow (~2 s on Mac, ~8–15 s on x86) — run with `cargo test -- --ignored`"]
    fn paranoid_preset_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::Paranoid.params())
            .expect("Paranoid should succeed");
        println!("Paranoid (generic): {:?}", start.elapsed());
    }

    // ── Mac preset smoke tests ───────────────────────────────────────────

    #[cfg(all(feature = "enc-timelock-keygen-input", target_os = "macos"))]
    #[test]
    #[ignore = "slow (~2 s on M2) — run with `cargo test -- --ignored`"]
    fn balanced_mac_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::BalancedMac.params())
            .expect("BalancedMac should succeed");
        println!("BalancedMac: {:?}", start.elapsed());
    }

    #[cfg(all(feature = "enc-timelock-keygen-input", target_os = "macos"))]
    #[test]
    #[ignore = "slow (~5–12 s on M2, faster on M3/M4) — run with `cargo test -- --ignored`"]
    fn paranoid_mac_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::ParanoidMac.params())
            .expect("ParanoidMac should succeed");
        println!("ParanoidMac: {:?}", start.elapsed());
    }

    // ── x86-64 preset smoke tests ────────────────────────────────────────

    #[cfg(all(feature = "enc-timelock-keygen-input", target_arch = "x86_64"))]
    #[test]
    #[ignore = "slow (~1.5 s on typical x86-64) — run with `cargo test -- --ignored`"]
    fn balanced_x86_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::BalancedX86.params())
            .expect("BalancedX86 should succeed");
        println!("BalancedX86: {:?}", start.elapsed());
    }

    #[cfg(all(feature = "enc-timelock-keygen-input", target_arch = "x86_64"))]
    #[test]
    #[ignore = "slow (~8–15 s on typical x86-64) — run with `cargo test -- --ignored`"]
    fn paranoid_x86_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::ParanoidX86.params())
            .expect("ParanoidX86 should succeed");
        println!("ParanoidX86: {:?}", start.elapsed());
    }

    // ── Linux ARM64 preset smoke tests ───────────────────────────────────

    #[cfg(all(feature = "enc-timelock-keygen-input", target_arch = "aarch64", not(target_os = "macos")))]
    #[test]
    #[ignore = "slow (~3 s on Graviton3) — run with `cargo test -- --ignored`"]
    fn balanced_arm_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::BalancedArm.params())
            .expect("BalancedArm should succeed");
        println!("BalancedArm: {:?}", start.elapsed());
    }

    #[cfg(all(feature = "enc-timelock-keygen-input", target_arch = "aarch64", not(target_os = "macos")))]
    #[test]
    #[ignore = "slow (~10–20 s on Graviton3) — run with `cargo test -- --ignored`"]
    fn paranoid_arm_completes() {
        let t = TimeLockTime::new(10, 0).unwrap();
        let start = std::time::Instant::now();
        derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &salts(), &KdfPreset::ParanoidArm.params())
            .expect("ParanoidArm should succeed");
        println!("ParanoidArm: {:?}", start.elapsed());
    }

    // ── Scheduled key derivation ─────────────────────────────────────────────

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn scheduled_none_same_as_regular_at() {
        // cadence=None adds no prefix — result must equal derive_key_at
        let s = salts();
        let t = TimeLockTime::new(14, 0).unwrap();
        let regular   = derive_key_at(t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast()).unwrap();
        let scheduled = derive_key_scheduled_at(
            TimeLockCadence::None, t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast(),
        ).unwrap();
        assert_eq!(regular.as_bytes(), scheduled.as_bytes());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn scheduled_different_weekdays_different_keys() {
        let s = salts();
        let t = TimeLockTime::new(18, 0).unwrap();
        let k_mon = derive_key_scheduled_at(
            TimeLockCadence::DayOfWeek(Weekday::Monday),
            t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast(),
        ).unwrap();
        let k_tue = derive_key_scheduled_at(
            TimeLockCadence::DayOfWeek(Weekday::Tuesday),
            t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast(),
        ).unwrap();
        assert_ne!(k_mon.as_bytes(), k_tue.as_bytes());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn scheduled_different_months_different_keys() {
        let s = salts();
        let t = TimeLockTime::new(0, 0).unwrap();
        let k_jan = derive_key_scheduled_at(
            TimeLockCadence::MonthOfYear(Month::January),
            t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast(),
        ).unwrap();
        let k_feb = derive_key_scheduled_at(
            TimeLockCadence::MonthOfYear(Month::February),
            t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast(),
        ).unwrap();
        assert_ne!(k_jan.as_bytes(), k_feb.as_bytes());
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    fn scheduled_at_deterministic() {
        // Same inputs must always produce the same key
        let s  = salts();
        let t  = TimeLockTime::new(6, 0).unwrap();
        let c  = TimeLockCadence::DayOfWeekInMonth(Weekday::Friday, Month::March);
        let k1 = derive_key_scheduled_at(c, t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast()).unwrap();
        let s2 = TimeLockSalts::from_slice(&s.to_bytes());
        let k2 = derive_key_scheduled_at(c, t, TimePrecision::Hour, TimeFormat::Hour24, &s2, &fast()).unwrap();
        assert_eq!(k1.as_bytes(), k2.as_bytes());
    }

    #[cfg(feature = "enc-timelock-keygen-now")]
    #[test]
    fn scheduled_now_none_matches_derive_now() {
        // cadence_variant=0 (None) + Hour + Hour24 must match derive_key_now exactly.
        // TimeLockParams now carries salts+kdf; build via pack() and clone salts.
        let s = salts();
        let f = fast();
        let stored = pack(
            TimePrecision::Hour, TimeFormat::Hour24,
            &TimeLockCadence::None,
            s.clone(),
            f,
        );
        let k1 = derive_key_now(TimePrecision::Hour, TimeFormat::Hour24, &s, &f).unwrap();
        let k2 = derive_key_scheduled_now(&stored).unwrap();
        assert_eq!(k1.as_bytes(), k2.as_bytes());
    }

    #[cfg(any(feature = "enc-timelock-keygen-input", feature = "enc-timelock-keygen-now"))]
    #[test]
    fn pack_unpack_roundtrip() {
        let params = pack(
            TimePrecision::Minute,
            TimeFormat::Hour24,
            &TimeLockCadence::DayOfWeekInMonth(Weekday::Tuesday, Month::February),
            salts(),
            fast(),
        );
        assert_eq!(params.time_precision, 2);  // Minute
        assert_eq!(params.time_format, 1);      // Hour24
        assert_eq!(params.cadence_variant, 4);  // DayOfWeekInMonth
        let (p, f, v) = unpack(&params);
        assert!(matches!(p, TimePrecision::Minute));
        assert!(matches!(f, TimeFormat::Hour24));
        assert_eq!(v, 4);
    }

    #[cfg(feature = "enc-timelock-keygen-input")]
    #[test]
    #[should_panic(expected = "DayOfMonthInMonth")]
    fn day_of_month_in_month_panics_on_invalid_day() {
        // February can have at most 28 days; day 29 must panic
        let s = salts();
        let t = TimeLockTime::new(0, 0).unwrap();
        let _ = derive_key_scheduled_at(
            TimeLockCadence::DayOfMonthInMonth(29, Month::February),
            t, TimePrecision::Hour, TimeFormat::Hour24, &s, &fast(),
        );
    }
}

// ─── attribute macro re-export ────────────────────────────────────────────────

/// Concise attribute macro for deriving a time-locked key inline.
///
/// Replaces the decorated `fn` with a call to [`timelock`] (sync) or
/// [`timelock_async`] (async, add the `async` flag). See
/// [`toolkit_zero_macros::timelock`] for the full argument reference.
///
/// # Examples
///
/// ```rust,ignore
/// use toolkit_zero::encryption::timelock::*;
///
/// // Encryption — derive for 14:37 with Minute precision.
/// fn encrypt_key() -> Result<TimeLockKey, TimeLockError> {
///     let salts = TimeLockSalts::generate();
///     let kdf   = KdfPreset::Balanced.params();
///     #[timelock(precision = Minute, format = Hour24, time(14, 37), salts = salts, kdf = kdf)]
///     fn key() {}
///     Ok(key)
/// }
///
/// // Decryption — re-derive from a stored header.
/// fn decrypt_key(header: TimeLockParams) -> Result<TimeLockKey, TimeLockError> {
///     #[timelock(params = header)]
///     fn key() {}
///     Ok(key)
/// }
/// ```
#[cfg(any(
    feature = "enc-timelock-keygen-now",
    feature = "enc-timelock-keygen-input",
    feature = "enc-timelock-async-keygen-now",
    feature = "enc-timelock-async-keygen-input",
))]
pub use toolkit_zero_macros::timelock;