tiny-counter 0.1.0

Track event counts across time windows with fixed memory and fast queries
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
use chrono::{DateTime, Duration, Utc};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{Error, Result};

/// Time unit definitions for interval configuration.
///
/// Represents different time granularities for event counting.
///
/// # Calendar-Aligned Buckets vs Uniform Buckets
///
/// **Default (calendar-aligned):**
/// - Buckets snap to calendar boundaries in local time
/// - `Days` rotate at local midnight (12:00 AM)
/// - `Weeks` rotate Monday at midnight
/// - `Months` rotate on the 1st
/// - `Years` rotate January 1st
///
/// **Uniform buckets** (disable `calendar` feature):
/// - Buckets align to January 1st of the current year at 00:00 UTC
/// - `Days` = 24-hour periods from that point
/// - `Weeks` = 7-day periods
/// - `Months` = 30-day periods (not calendar months)
/// - `Years` = 365-day periods (ignores leap days)
/// - All counters of the same time unit have aligned start times
///
/// # Why Calendar-Aligned by Default?
///
/// Best for client-side and user-facing use cases:
/// - Aligns to how users talk: "today", "this week", "this month"
/// - Day boundaries at local midnight (not arbitrary 24-hour windows)
/// - Matches how users think: "I used the app 3 times today"
/// - Works with daily/weekly/monthly goals and limits
///
/// Use uniform buckets (disable `calendar` feature) when you need:
/// - Consistent bucket sizes for statistical analysis
/// - Predictable memory usage (30 days ≈ 1 month)
/// - Industry-standard "30-day rolling window" (backend analytics)
/// - Better year approximation: 12 × 30 = 360 days (1.4% error vs 365)
///
/// TimeUnits are ordered from smallest to largest:
/// Minutes < Hours < Days < Weeks < Months < Years < Ever
///
/// `Ever` is a special variant that represents "use the longest configured
/// time unit for this event." It is resolved lazily during query execution.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum TimeUnit {
    Seconds,
    Minutes,
    Hours,
    Days,   // Calendar days at local midnight (or 24-hour periods without `calendar`)
    Weeks,  // Calendar weeks on Monday (or 7-day periods without `calendar`)
    Months, // Calendar months on 1st (or 30-day periods without `calendar`)
    Years,  // Calendar years on Jan 1 (or 365-day periods without `calendar`)
    Ever,   // Special: resolved to longest configured unit during query
}

/// Represents a time window for rate limiting constraints.
///
/// This type enables flexible expression of time windows in rate limits:
/// - `TimeUnit` - defaults to 1 unit (e.g., `TimeUnit::Days` means 1 day)
/// - `(usize, TimeUnit)` - explicit count (e.g., `(7, TimeUnit::Days)` means 7 days)
/// - `Duration` - converted to best matching TimeUnit
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeWindow {
    pub count: usize,
    pub time_unit: TimeUnit,
}

impl From<TimeUnit> for TimeWindow {
    fn from(unit: TimeUnit) -> Self {
        TimeWindow {
            count: 1,
            time_unit: unit,
        }
    }
}

impl From<(usize, TimeUnit)> for TimeWindow {
    fn from(window: (usize, TimeUnit)) -> Self {
        TimeWindow {
            count: window.0,
            time_unit: window.1,
        }
    }
}

impl From<Duration> for TimeWindow {
    fn from(dur: Duration) -> Self {
        // Handle negative durations by taking absolute value
        let dur = dur.abs();

        // Pick best matching unit based on duration
        if dur.num_days() > 0 {
            TimeWindow {
                count: dur.num_days() as usize,
                time_unit: TimeUnit::Days,
            }
        } else if dur.num_hours() > 0 {
            TimeWindow {
                count: dur.num_hours() as usize,
                time_unit: TimeUnit::Hours,
            }
        } else if dur.num_minutes() > 0 {
            TimeWindow {
                count: dur.num_minutes() as usize,
                time_unit: TimeUnit::Minutes,
            }
        } else {
            TimeWindow {
                count: dur.num_seconds() as usize,
                time_unit: TimeUnit::Minutes,
            }
        }
    }
}

/// Helper functions for calendar-aligned time unit operations.
#[cfg(feature = "calendar")]
mod calendar {
    use chrono::{DateTime, Datelike, Local, NaiveDate, TimeZone, Utc};

    /// Convert a local date to UTC at midnight.
    pub(super) fn local_midnight_to_utc(date: NaiveDate) -> DateTime<Utc> {
        Local
            .from_local_datetime(&date.and_hms_opt(0, 0, 0).unwrap())
            .earliest()
            .unwrap()
            .with_timezone(&Utc)
    }

    /// Convert a local date and time to UTC.
    pub(super) fn local_time_to_utc(date: NaiveDate, hour: u32) -> DateTime<Utc> {
        Local
            .from_local_datetime(&date.and_hms_opt(hour, 0, 0).unwrap())
            .earliest()
            .unwrap()
            .with_timezone(&Utc)
    }

    /// Find Monday of the week containing the given date.
    pub(super) fn find_monday(date: NaiveDate) -> NaiveDate {
        let days_since_monday = date.weekday().num_days_from_monday();
        date - chrono::Days::new(days_since_monday as u64)
    }

    /// Add months to a (year, month) pair, handling overflow/underflow.
    ///
    /// Returns (final_year, final_month) where month is 1-based (1-12).
    pub(super) fn add_months(year: i32, month: u32, delta: i32) -> (i32, u32) {
        let total_month = month as i32 + delta;
        // Convert to 0-based months (0-11) for proper modulo arithmetic
        let month0 = total_month - 1;
        let year_offset = month0.div_euclid(12);
        let final_year = year + year_offset;
        let final_month = (month0.rem_euclid(12) + 1) as u32;
        (final_year, final_month)
    }
}

impl TimeUnit {
    /// Returns the duration represented by this time unit.
    ///
    /// Note: Months use a 30-day approximation, Years use 365 days.
    ///
    /// # Panics
    ///
    /// Panics if called on `TimeUnit::Ever`, which has no fixed duration.
    /// `Ever` must be resolved to a concrete time unit before calling this method.
    pub fn duration(&self) -> Duration {
        match self {
            Self::Seconds => Duration::seconds(1),
            Self::Minutes => Duration::minutes(1),
            Self::Hours => Duration::hours(1),
            Self::Days => Duration::days(1),
            Self::Weeks => Duration::weeks(1),
            Self::Months => Duration::days(30),
            Self::Years => Duration::days(365),
            Self::Ever => {
                panic!("TimeUnit::Ever has no fixed duration. Resolve to concrete time unit first.")
            }
        }
    }

    /// Counts bucket boundaries crossed between two times.
    ///
    /// Counts boundary crossings, not complete periods elapsed:
    /// - Days: midnight boundaries in local timezone
    /// - Weeks: Monday boundaries (ISO weeks)
    /// - Months: first-of-month boundaries
    ///
    /// Each boundary crossing rotates the ring buffer once.
    ///
    /// Returns:
    /// - Positive: `now` is after `then` (past events)
    /// - Zero: `now` and `then` are in the same bucket
    /// - Negative: `now` is before `then` (future events)
    pub(crate) fn num_rotations(&self, then: DateTime<Utc>, now: DateTime<Utc>) -> i64 {
        #[cfg(feature = "calendar")]
        {
            use chrono::{Datelike, Local};

            match self {
                TimeUnit::Days => {
                    let then_local = then.with_timezone(&Local).date_naive();
                    let now_local = now.with_timezone(&Local).date_naive();
                    return (now_local - then_local).num_days();
                }
                TimeUnit::Weeks => {
                    let then_local = then.with_timezone(&Local).date_naive();
                    let now_local = now.with_timezone(&Local).date_naive();
                    let week_diff =
                        now_local.iso_week().week() as i64 - then_local.iso_week().week() as i64;
                    // Use iso_week().year() not year() to handle weeks at year boundaries correctly
                    // e.g. Dec 31, 2024 is in ISO Week 1 of 2025
                    let year_diff = (now_local.iso_week().year() as i64
                        - then_local.iso_week().year() as i64)
                        * 52;
                    return week_diff + year_diff;
                }
                TimeUnit::Months => {
                    let then_local = then.with_timezone(&Local);
                    let now_local = now.with_timezone(&Local);
                    let then_months = then_local.year() as i64 * 12 + then_local.month() as i64;
                    let now_months = now_local.year() as i64 * 12 + now_local.month() as i64;
                    return now_months - then_months;
                }
                TimeUnit::Years => {
                    let then_local = then.with_timezone(&Local);
                    let now_local = now.with_timezone(&Local);
                    return (now_local.year() - then_local.year()) as i64;
                }
                _ => {} // Fall through to fixed-duration logic
            }
        }

        // Fixed-duration units (Seconds, Minutes, Hours) use simple arithmetic
        let duration = now.signed_duration_since(then);
        let unit_duration = self.duration();
        duration.num_seconds() / unit_duration.num_seconds()
    }

    pub(crate) fn rotate_start_interval(
        &self,
        interval_start: DateTime<Utc>,
        rotations: i64,
    ) -> DateTime<Utc> {
        #[cfg(feature = "calendar")]
        {
            use chrono::{Datelike, Local, TimeZone};

            match self {
                TimeUnit::Days => {
                    let local = interval_start.with_timezone(&Local);
                    let target_date = local.date_naive() + chrono::Days::new(rotations as u64);
                    return calendar::local_midnight_to_utc(target_date);
                }
                TimeUnit::Weeks => {
                    let local = interval_start.with_timezone(&Local);
                    let this_monday = calendar::find_monday(local.date_naive());
                    let target_monday = this_monday + chrono::Days::new((rotations * 7) as u64);
                    return calendar::local_midnight_to_utc(target_monday);
                }
                TimeUnit::Months => {
                    let local = interval_start.with_timezone(&Local);
                    let (final_year, final_month) =
                        calendar::add_months(local.year(), local.month(), rotations as i32);
                    return Local
                        .with_ymd_and_hms(final_year, final_month, 1, 0, 0, 0)
                        .earliest()
                        .unwrap()
                        .with_timezone(&Utc);
                }
                TimeUnit::Years => {
                    let local = interval_start.with_timezone(&Local);
                    let target_year = local.year() + rotations as i32;
                    return Local
                        .with_ymd_and_hms(target_year, 1, 1, 0, 0, 0)
                        .earliest()
                        .unwrap()
                        .with_timezone(&Utc);
                }
                _ => {} // Fall through to fixed-duration logic
            }
        }

        // Fixed-duration units (Seconds, Minutes, Hours) use simple arithmetic
        let duration = self.duration();
        interval_start + duration * rotations as i32
    }

    pub(crate) fn bucket_idx(
        &self,
        interval_start: DateTime<Utc>,
        time: DateTime<Utc>,
    ) -> Result<usize> {
        let rotations = self.num_rotations(time, interval_start);

        // Step 2: Bucket selection logic
        if rotations < 0 {
            // Event is in the future
            return Err(Error::FutureEvent);
        }
        Ok(if rotations == 0 {
            // Same interval as starting_instant
            if time >= interval_start {
                0 // Current interval, after instant
            } else {
                1 // Current interval, before instant
            }
        } else {
            // Past intervals - use rotations directly as bucket index
            rotations as usize
        })
    }

    /// Returns the end time of a bucket.
    ///
    /// - bucket_idx=0: returns `now` (current bucket ends at now)
    /// - bucket_idx>0: returns the end time of that historical bucket
    pub(crate) fn bucket_end(&self, now: DateTime<Utc>, bucket_idx: usize) -> DateTime<Utc> {
        if bucket_idx == 0 {
            return now;
        }

        #[cfg(feature = "calendar")]
        {
            use chrono::{Datelike, Local, TimeZone};

            match self {
                TimeUnit::Days => {
                    let now_local = now.with_timezone(&Local);
                    let target_date = now_local.date_naive() - chrono::Days::new(bucket_idx as u64);
                    return calendar::local_midnight_to_utc(target_date);
                }
                TimeUnit::Weeks => {
                    let now_local = now.with_timezone(&Local);
                    let this_monday = calendar::find_monday(now_local.date_naive());
                    let target_monday = this_monday - chrono::Days::new((bucket_idx * 7) as u64);
                    return calendar::local_midnight_to_utc(target_monday);
                }
                TimeUnit::Months => {
                    let now_local = now.with_timezone(&Local);
                    let (final_year, final_month) = calendar::add_months(
                        now_local.year(),
                        now_local.month(),
                        -(bucket_idx as i32),
                    );
                    return Local
                        .with_ymd_and_hms(final_year, final_month, 1, 0, 0, 0)
                        .earliest()
                        .unwrap()
                        .with_timezone(&Utc);
                }
                TimeUnit::Years => {
                    let now_local = now.with_timezone(&Local);
                    let target_year = now_local.year() - bucket_idx as i32;
                    return Local
                        .with_ymd_and_hms(target_year, 1, 1, 0, 0, 0)
                        .earliest()
                        .unwrap()
                        .with_timezone(&Utc);
                }
                _ => {} // Fall through to fixed-duration logic
            }
        }

        // Fixed-duration units (Seconds, Minutes, Hours) use simple arithmetic
        now - (self.duration() * bucket_idx as i32)
    }

    /// Returns the start time of a bucket.
    pub(crate) fn bucket_start(&self, now: DateTime<Utc>, bucket_idx: usize) -> DateTime<Utc> {
        self.bucket_end(now, bucket_idx + 1)
    }

    /// Returns the duration of a bucket.
    #[allow(dead_code)] // Used in calendar feature only
    pub(crate) fn bucket_duration(&self, now: DateTime<Utc>, bucket_idx: usize) -> Duration {
        let bucket_start = self.bucket_start(now, bucket_idx);
        let bucket_end = self.bucket_end(now, bucket_idx);
        bucket_end - bucket_start
    }

    /// Returns the midpoint time of a bucket.
    pub(crate) fn bucket_midway(
        &self,
        clock_now: DateTime<Utc>,
        interval_start: DateTime<Utc>,
        bucket_idx: usize,
    ) -> DateTime<Utc> {
        if bucket_idx == 0 {
            let elapsed = clock_now - interval_start;
            return interval_start + (elapsed / 2);
        }

        #[cfg(feature = "calendar")]
        {
            use chrono::Local;

            match self {
                TimeUnit::Days => {
                    let now_local = clock_now.with_timezone(&Local);
                    let target_date = now_local.date_naive() - chrono::Days::new(bucket_idx as u64);
                    return calendar::local_time_to_utc(target_date, 12);
                }
                TimeUnit::Weeks | TimeUnit::Months | TimeUnit::Years => {
                    let bucket_start = self.bucket_start(clock_now, bucket_idx);
                    let duration = self.bucket_duration(clock_now, bucket_idx);
                    return bucket_start + (duration / 2);
                }
                _ => {} // Fall through to fixed-duration logic
            }
        }

        // Fixed-duration units (Seconds, Minutes, Hours) use simple arithmetic
        let duration = self.duration();
        interval_start - (duration * bucket_idx as i32 + duration / 2)
    }

    /// Returns the earliest moment tracked by all buckets.
    pub(crate) fn first_moment_ever(
        &self,
        now: DateTime<Utc>,
        bucket_count: usize,
    ) -> DateTime<Utc> {
        #[cfg(feature = "calendar")]
        {
            use chrono::{Datelike, Local, TimeZone};

            match self {
                TimeUnit::Days => {
                    let now_local = now.with_timezone(&Local);
                    let target_date =
                        now_local.date_naive() - chrono::Days::new(bucket_count as u64);
                    return calendar::local_midnight_to_utc(target_date);
                }
                TimeUnit::Weeks => {
                    let now_local = now.with_timezone(&Local);
                    let this_monday = calendar::find_monday(now_local.date_naive());
                    let target_monday = this_monday - chrono::Days::new((bucket_count * 7) as u64);
                    return calendar::local_midnight_to_utc(target_monday);
                }
                TimeUnit::Months => {
                    let now_local = now.with_timezone(&Local);
                    let (final_year, final_month) = calendar::add_months(
                        now_local.year(),
                        now_local.month(),
                        -(bucket_count as i32),
                    );
                    return Local
                        .with_ymd_and_hms(final_year, final_month, 1, 0, 0, 0)
                        .earliest()
                        .unwrap()
                        .with_timezone(&Utc);
                }
                TimeUnit::Years => {
                    let now_local = now.with_timezone(&Local);
                    let target_year = now_local.year() - bucket_count as i32;
                    return Local
                        .with_ymd_and_hms(target_year, 1, 1, 0, 0, 0)
                        .earliest()
                        .unwrap()
                        .with_timezone(&Utc);
                }
                _ => {} // Fall through to fixed-duration logic
            }
        }

        // Fixed-duration units (Seconds, Minutes, Hours) use simple arithmetic
        now - (self.duration() * bucket_count as i32)
    }

    /// Returns a representative time within a bucket (used for conversion).
    ///
    /// This is similar to bucket_midway but with different arithmetic for historical buckets.
    pub(crate) fn bucket_time(
        &self,
        clock_now: DateTime<Utc>,
        interval_start: DateTime<Utc>,
        bucket_idx: usize,
    ) -> DateTime<Utc> {
        if bucket_idx == 0 {
            let elapsed = clock_now - interval_start;
            return interval_start + (elapsed / 2);
        }

        #[cfg(feature = "calendar")]
        {
            use chrono::Local;

            match self {
                TimeUnit::Days => {
                    let now_local = clock_now.with_timezone(&Local);
                    let target_date = now_local.date_naive() - chrono::Days::new(bucket_idx as u64);
                    return calendar::local_time_to_utc(target_date, 12);
                }
                TimeUnit::Weeks | TimeUnit::Months | TimeUnit::Years => {
                    let bucket_start = self.bucket_start(clock_now, bucket_idx);
                    let duration = self.bucket_duration(clock_now, bucket_idx);
                    return bucket_start + (duration / 2);
                }
                _ => {} // Fall through to fixed-duration logic
            }
        }

        // Fixed-duration units (Seconds, Minutes, Hours) use simple arithmetic
        let duration = self.duration();
        interval_start - (duration * bucket_idx as i32) + duration / 2
    }
}

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

    #[cfg(feature = "calendar")]
    mod calendar_helpers {
        use super::*;
        use chrono::Local;

        /// Calculate how many calendar days are crossed between two UTC times
        /// in the local timezone.
        pub fn calendar_days_between(then: DateTime<Utc>, now: DateTime<Utc>) -> i64 {
            // Convert to local dates
            let then_local = then.with_timezone(&Local).date_naive();
            let now_local = now.with_timezone(&Local).date_naive();

            // Count calendar day boundaries crossed
            (now_local - then_local).num_days()
        }
    }

    #[test]
    fn test_duration_minutes() {
        assert_eq!(TimeUnit::Minutes.duration(), Duration::minutes(1));
    }

    #[test]
    fn test_duration_hours() {
        assert_eq!(TimeUnit::Hours.duration(), Duration::hours(1));
    }

    #[test]
    fn test_duration_days() {
        // Note: In calendar mode, Days don't have fixed duration (23-25 hours due to DST)
        // but duration() still returns 24 hours for fallback/non-calendar units
        assert_eq!(TimeUnit::Days.duration(), Duration::days(1));
    }

    #[test]
    fn test_duration_weeks() {
        assert_eq!(TimeUnit::Weeks.duration(), Duration::weeks(1));
    }

    #[test]
    fn test_duration_months() {
        // Note: In calendar mode, Months don't have fixed duration (28-31 days)
        // but duration() still returns 30 days for fallback/non-calendar units
        assert_eq!(TimeUnit::Months.duration(), Duration::days(30));
    }

    #[test]
    fn test_duration_years() {
        // Years are approximated as 365 days
        assert_eq!(TimeUnit::Years.duration(), Duration::days(365));
    }

    #[test]
    fn test_num_rotations_same_time() {
        let time = Utc::now();
        assert_eq!(TimeUnit::Days.num_rotations(time, time), 0);
    }

    #[test]
    fn test_num_rotations_past_time() {
        let now = Utc.with_ymd_and_hms(2025, 1, 10, 12, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 5, 12, 0, 0).unwrap();

        // 5 days have passed
        assert_eq!(TimeUnit::Days.num_rotations(then, now), 5);
    }

    #[test]
    fn test_num_rotations_future_time() {
        let now = Utc.with_ymd_and_hms(2025, 1, 5, 12, 0, 0).unwrap();
        let future = Utc.with_ymd_and_hms(2025, 1, 10, 12, 0, 0).unwrap();

        // Event is 5 days in the future (negative)
        assert_eq!(TimeUnit::Days.num_rotations(future, now), -5);
    }

    #[test]
    fn test_num_rotations_hours() {
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 15, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();

        // 5 hours have passed
        assert_eq!(TimeUnit::Hours.num_rotations(then, now), 5);
    }

    #[test]
    fn test_num_rotations_seconds() {
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 45).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();

        // 45 seconds have passed
        assert_eq!(TimeUnit::Seconds.num_rotations(then, now), 45);
    }

    #[test]
    fn test_num_rotations_minutes() {
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 10, 30, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();

        // 30 minutes have passed
        assert_eq!(TimeUnit::Minutes.num_rotations(then, now), 30);
    }

    #[test]
    fn test_num_rotations_weeks() {
        let now = Utc.with_ymd_and_hms(2025, 1, 22, 0, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // 3 weeks have passed (21 days)
        assert_eq!(TimeUnit::Weeks.num_rotations(then, now), 3);
    }

    #[test]
    #[cfg(not(feature = "calendar"))]
    fn test_num_rotations_months() {
        let now = Utc.with_ymd_and_hms(2025, 4, 1, 0, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // 90 days = 3 complete 30-day months (fixed-duration mode)
        let days_diff = (now - then).num_days();
        assert_eq!(days_diff, 90);
        assert_eq!(TimeUnit::Months.num_rotations(then, now), 3);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_months_calendar_year_boundary() {
        // Test that months calculation handles year boundaries correctly
        // Dec 31, 2024 → March 1, 2025
        let then = Utc.with_ymd_and_hms(2024, 12, 31, 12, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 3, 1, 12, 0, 0).unwrap();

        let rotations = TimeUnit::Months.num_rotations(then, now);

        // Calculation:
        //   then_months = 2024 * 12 + 12 = 24300
        //   now_months = 2025 * 12 + 3 = 24303
        //   diff = 3 months
        // Counts month number difference: December (12) → March (3) = 3 months
        assert_eq!(
            rotations, 3,
            "Should be 3 months from Dec 31, 2024 to March 1, 2025"
        );
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_months_calendar_multi_year_span() {
        // Test spanning multiple years with same month
        // Dec 15, 2023 → Dec 1, 2025 should be 24 months
        let then = Utc.with_ymd_and_hms(2023, 12, 15, 0, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 12, 1, 0, 0, 0).unwrap();

        let rotations = TimeUnit::Months.num_rotations(then, now);

        // Calculation:
        //   then_months = 2023 * 12 + 12 = 24288
        //   now_months = 2025 * 12 + 12 = 24312
        //   diff = 24 months
        assert_eq!(
            rotations, 24,
            "Should be 24 months from Dec 2023 to Dec 2025"
        );
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_months_calendar() {
        let now = Utc.with_ymd_and_hms(2025, 4, 1, 0, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // Jan 1 to Apr 1 = 3 calendar months (Jan→Feb→Mar→Apr)
        assert_eq!(TimeUnit::Months.num_rotations(then, now), 3);

        // Test non-boundary dates
        let now = Utc.with_ymd_and_hms(2025, 4, 15, 12, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 15, 12, 0, 0).unwrap();

        // Jan 15 to Apr 15 = still 3 calendar months
        assert_eq!(TimeUnit::Months.num_rotations(then, now), 3);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_weeks_calendar_year_boundary() {
        use chrono::Datelike;

        // Critical edge case: Dec 31, 2024 is in ISO Week 1 of 2025
        // Dec 31, 2024 is a Tuesday
        // The week containing it: Mon Dec 30, 2024 → Sun Jan 5, 2025
        // This week contains the first Thursday of 2025 (Jan 2), so it's ISO Week 1 of 2025
        let then = Utc.with_ymd_and_hms(2024, 12, 31, 12, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 3, 1, 12, 0, 0).unwrap();

        // Verify ISO week properties
        use chrono::Local;
        let then_local = then.with_timezone(&Local).date_naive();
        let now_local = now.with_timezone(&Local).date_naive();

        // Dec 31, 2024: calendar year = 2024, ISO week year = 2025, ISO week = 1
        assert_eq!(
            then_local.iso_week().year(),
            2025,
            "Dec 31, 2024 should be in ISO week year 2025"
        );
        assert_eq!(
            then_local.iso_week().week(),
            1,
            "Dec 31, 2024 should be in ISO week 1"
        );

        // March 1, 2025: ISO week = 9
        assert_eq!(
            now_local.iso_week().week(),
            9,
            "March 1, 2025 should be in ISO week 9"
        );

        let rotations = TimeUnit::Weeks.num_rotations(then, now);

        // Should be 8 weeks (not 60 weeks!)
        // If we incorrectly used calendar year instead of ISO week year:
        //   year_diff = (2025 - 2024) * 52 = 52
        //   week_diff = 9 - 1 = 8
        //   WRONG total = 60 weeks
        //
        // Correct calculation using ISO week year:
        //   year_diff = (2025 - 2025) * 52 = 0
        //   week_diff = 9 - 1 = 8
        //   CORRECT total = 8 weeks
        assert_eq!(
            rotations, 8,
            "Should be 8 ISO weeks from Dec 31, 2024 to March 1, 2025"
        );
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_weeks_calendar_multi_year_span() {
        use chrono::Datelike;

        // Test case that would fail with "anniversary" approach but passes with ISO week year
        // Dec 30, 2024 is a Monday (ISO Week 1 of 2025)
        // Dec 29, 2025 is a Monday (ISO Week 1 of 2026)
        // From Dec 30 to Dec 29 next year = 364 days = 52 weeks
        let then = Utc.with_ymd_and_hms(2024, 12, 30, 0, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 12, 29, 0, 0, 0).unwrap();

        use chrono::Local;
        let then_local = then.with_timezone(&Local).date_naive();
        let now_local = now.with_timezone(&Local).date_naive();

        // Verify ISO week properties
        assert_eq!(
            then_local.iso_week().year(),
            2025,
            "Dec 30, 2024 should be in ISO week year 2025"
        );
        assert_eq!(
            then_local.iso_week().week(),
            1,
            "Dec 30, 2024 should be in ISO week 1"
        );

        assert_eq!(
            now_local.iso_week().year(),
            2026,
            "Dec 29, 2025 should be in ISO week year 2026"
        );
        assert_eq!(
            now_local.iso_week().week(),
            1,
            "Dec 29, 2025 should be in ISO week 1"
        );

        let rotations = TimeUnit::Weeks.num_rotations(then, now);

        // ISO week year approach (CORRECT):
        //   year_diff = (2026 - 2025) * 52 = 52
        //   week_diff = 1 - 1 = 0
        //   total = 52 weeks ✓
        //
        // Alternative "anniversary" approach (WRONG):
        //   year_diff = (2025 - 2024) = 1
        //   Since now (Dec 29) < then (Dec 30), decrement: year_diff = 0
        //   week_diff = 1 - 1 = 0
        //   WRONG total = 0 weeks (should be 52!)
        assert_eq!(
            rotations, 52,
            "Should be 52 ISO weeks from Dec 30, 2024 to Dec 29, 2025"
        );
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_days_calendar() {
        use calendar_helpers::calendar_days_between;

        // Test that Days counts calendar day boundaries (local midnight), not 24-hour periods
        // then: Jan 1, 2025, 23:00 UTC (11 PM)
        // now:  Jan 5, 2025, 01:00 UTC (1 AM)
        // UTC elapsed: 3 days, 2 hours
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 23, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 1, 5, 1, 0, 0).unwrap();

        // Calculate expected calendar days in local timezone
        let expected_days = calendar_days_between(then, now);

        let rotations = TimeUnit::Days.num_rotations(then, now);

        // Should match exact calendar days crossed in local timezone
        assert_eq!(
            rotations, expected_days,
            "Expected {} calendar days (local timezone), got {}",
            expected_days, rotations
        );
    }

    #[test]
    fn test_num_rotations_years() {
        let now = Utc.with_ymd_and_hms(2027, 1, 1, 0, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // 730 days = 2 years (365 days each)
        assert_eq!(TimeUnit::Years.num_rotations(then, now), 2);
    }

    #[test]
    fn test_num_rotations_partial_unit() {
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 12, 30, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2025, 1, 1, 12, 0, 0).unwrap();

        // 30 minutes = 0 complete hours
        assert_eq!(TimeUnit::Hours.num_rotations(then, now), 0);
    }

    // Property test: num_rotations is transitive
    #[test]
    fn test_num_rotations_transitive() {
        let a = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let b = Utc.with_ymd_and_hms(2025, 1, 5, 0, 0, 0).unwrap();
        let c = Utc.with_ymd_and_hms(2025, 1, 10, 0, 0, 0).unwrap();

        let ab = TimeUnit::Days.num_rotations(a, b);
        let bc = TimeUnit::Days.num_rotations(b, c);
        let ac = TimeUnit::Days.num_rotations(a, c);

        assert_eq!(ab + bc, ac);
    }

    #[test]
    fn test_time_unit_is_copy() {
        let unit = TimeUnit::Days;
        let _unit2 = unit; // Should compile (Copy)
        let _unit3 = unit; // Should still work
    }

    #[test]
    fn test_time_unit_is_eq() {
        assert_eq!(TimeUnit::Days, TimeUnit::Days);
        assert_ne!(TimeUnit::Days, TimeUnit::Hours);
    }

    #[test]
    fn test_time_unit_is_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(TimeUnit::Days);
        assert!(set.contains(&TimeUnit::Days));
    }

    #[test]
    fn test_large_time_jump() {
        let now = Utc.with_ymd_and_hms(2025, 12, 31, 0, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap();

        // Many days have passed
        let rotations = TimeUnit::Days.num_rotations(then, now);
        assert!(rotations > 2000); // At least 5+ years worth of days
    }

    // TimeWindow conversion tests
    #[test]
    fn test_time_window_from_time_unit() {
        let window: TimeWindow = TimeUnit::Days.into();
        assert_eq!(window.count, 1);
        assert_eq!(window.time_unit, TimeUnit::Days);
    }

    #[test]
    fn test_time_window_from_tuple() {
        let window: TimeWindow = (7, TimeUnit::Days).into();
        assert_eq!(window.count, 7);
        assert_eq!(window.time_unit, TimeUnit::Days);
    }

    #[test]
    fn test_time_window_from_duration_days() {
        let window: TimeWindow = Duration::days(7).into();
        assert_eq!(window.count, 7);
        assert_eq!(window.time_unit, TimeUnit::Days);
    }

    #[test]
    fn test_time_window_from_duration_hours() {
        let window: TimeWindow = Duration::hours(12).into();
        assert_eq!(window.count, 12);
        assert_eq!(window.time_unit, TimeUnit::Hours);
    }

    #[test]
    fn test_time_window_from_duration_minutes() {
        let window: TimeWindow = Duration::minutes(30).into();
        assert_eq!(window.count, 30);
        assert_eq!(window.time_unit, TimeUnit::Minutes);
    }

    #[test]
    fn test_time_window_from_duration_seconds() {
        let window: TimeWindow = Duration::seconds(45).into();
        // Seconds are converted to minutes (0 minutes)
        assert_eq!(window.count, 45);
        assert_eq!(window.time_unit, TimeUnit::Minutes);
    }

    // Ord implementation tests
    #[test]
    fn test_time_unit_ord() {
        assert!(TimeUnit::Minutes < TimeUnit::Hours);
        assert!(TimeUnit::Hours < TimeUnit::Days);
        assert!(TimeUnit::Days < TimeUnit::Weeks);
        assert!(TimeUnit::Weeks < TimeUnit::Months);
        assert!(TimeUnit::Months < TimeUnit::Years);
    }

    #[test]
    fn test_time_unit_ord_transitive() {
        assert!(TimeUnit::Minutes < TimeUnit::Days);
        assert!(TimeUnit::Hours < TimeUnit::Weeks);
        assert!(TimeUnit::Days < TimeUnit::Years);
    }

    #[test]
    fn test_time_unit_ord_reflexive() {
        assert!(TimeUnit::Minutes <= TimeUnit::Minutes);
        assert!(TimeUnit::Hours >= TimeUnit::Hours);
    }

    #[test]
    fn test_time_unit_ever_is_largest() {
        assert!(TimeUnit::Years < TimeUnit::Ever);
        assert!(TimeUnit::Minutes < TimeUnit::Ever);
        assert!(TimeUnit::Days < TimeUnit::Ever);
    }

    #[test]
    #[should_panic(expected = "TimeUnit::Ever has no fixed duration")]
    fn test_time_unit_ever_duration_panics() {
        TimeUnit::Ever.duration();
    }

    #[test]
    fn test_time_window_from_negative_duration_days() {
        let window: TimeWindow = Duration::days(-7).into();
        // Should convert absolute value
        assert_eq!(window.count, 7);
        assert_eq!(window.time_unit, TimeUnit::Days);
    }

    #[test]
    fn test_time_window_from_negative_duration_hours() {
        let window: TimeWindow = Duration::hours(-12).into();
        assert_eq!(window.count, 12);
        assert_eq!(window.time_unit, TimeUnit::Hours);
    }

    #[test]
    fn test_time_window_from_negative_duration_minutes() {
        let window: TimeWindow = Duration::minutes(-30).into();
        assert_eq!(window.count, 30);
        assert_eq!(window.time_unit, TimeUnit::Minutes);
    }

    #[test]
    fn test_time_window_from_negative_duration_seconds() {
        let window: TimeWindow = Duration::seconds(-45).into();
        assert_eq!(window.count, 45);
        assert_eq!(window.time_unit, TimeUnit::Minutes);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_end_days_calendar() {
        use chrono::{Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 1, 5, 14, 30, 0).unwrap();

        // bucket_idx=0 should return now
        assert_eq!(TimeUnit::Days.bucket_end(now, 0), now);

        // bucket_idx=1 should return local midnight of yesterday
        let bucket_end = TimeUnit::Days.bucket_end(now, 1);
        let local_bucket = bucket_end.with_timezone(&Local);

        // Should be at midnight
        assert_eq!(local_bucket.hour(), 0);
        assert_eq!(local_bucket.minute(), 0);
        assert_eq!(local_bucket.second(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_end_months_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 4, 15, 14, 30, 0).unwrap();

        // bucket_idx=0 should return now
        assert_eq!(TimeUnit::Months.bucket_end(now, 0), now);

        // bucket_idx=1 should return local midnight of 1st of March
        let bucket_end = TimeUnit::Months.bucket_end(now, 1);
        let local_bucket = bucket_end.with_timezone(&Local);

        // Should be March 1st at midnight
        assert_eq!(local_bucket.month(), 3);
        assert_eq!(local_bucket.day(), 1);
        assert_eq!(local_bucket.hour(), 0);
        assert_eq!(local_bucket.minute(), 0);
        assert_eq!(local_bucket.second(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_start_calendar() {
        let now = Utc.with_ymd_and_hms(2025, 4, 15, 14, 30, 0).unwrap();

        // bucket_start should be bucket_end of next bucket
        let bucket_0_start = TimeUnit::Months.bucket_start(now, 0);
        let bucket_1_end = TimeUnit::Months.bucket_end(now, 1);

        assert_eq!(bucket_0_start, bucket_1_end);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_start_months_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 4, 15, 14, 30, 0).unwrap();

        // Bucket 1 start should be bucket 2 end (Feb 1 at midnight)
        let bucket_1_start = TimeUnit::Months.bucket_start(now, 1);
        let local_start = bucket_1_start.with_timezone(&Local);

        // Should be Feb 1 at midnight
        assert_eq!(local_start.month(), 2);
        assert_eq!(local_start.day(), 1);
        assert_eq!(local_start.hour(), 0);
        assert_eq!(local_start.minute(), 0);
        assert_eq!(local_start.second(), 0);

        // Verify relationship: bucket_start(n) == bucket_end(n+1)
        let bucket_2_end = TimeUnit::Months.bucket_end(now, 2);
        assert_eq!(bucket_1_start, bucket_2_end);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_rotate_start_interval_days_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // Rotate forward 3 days
        let rotated = TimeUnit::Days.rotate_start_interval(start, 3);
        let local_rotated = rotated.with_timezone(&Local);

        // Should be Jan 4 at local midnight
        assert_eq!(local_rotated.day(), 4);
        assert_eq!(local_rotated.hour(), 0);
        assert_eq!(local_rotated.minute(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_rotate_start_interval_months_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // Rotate forward 3 months
        let rotated = TimeUnit::Months.rotate_start_interval(start, 3);
        let local_rotated = rotated.with_timezone(&Local);

        // Should be April 1 at local midnight
        assert_eq!(local_rotated.month(), 4);
        assert_eq!(local_rotated.day(), 1);
        assert_eq!(local_rotated.hour(), 0);
        assert_eq!(local_rotated.minute(), 0);

        // Test with year boundary
        let start = Utc.with_ymd_and_hms(2025, 11, 1, 0, 0, 0).unwrap();
        let rotated = TimeUnit::Months.rotate_start_interval(start, 3);
        let local_rotated = rotated.with_timezone(&Local);

        // Should be Feb 1, 2026 at local midnight
        assert_eq!(local_rotated.year(), 2026);
        assert_eq!(local_rotated.month(), 2);
        assert_eq!(local_rotated.day(), 1);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_midway_days_calendar() {
        use chrono::{Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 1, 5, 14, 30, 0).unwrap();
        let interval_start = Utc.with_ymd_and_hms(2025, 1, 5, 0, 0, 0).unwrap();

        // Bucket 0 (current): midpoint between interval_start and now
        let midway_0 = TimeUnit::Days.bucket_midway(now, interval_start, 0);
        let expected_0 = interval_start + (now - interval_start) / 2;
        assert_eq!(midway_0, expected_0);

        // Bucket 1 (yesterday): should be noon of yesterday
        let midway_1 = TimeUnit::Days.bucket_midway(now, interval_start, 1);
        let local_midway = midway_1.with_timezone(&Local);

        // Should be at noon (12:00)
        assert_eq!(local_midway.hour(), 12);
        assert_eq!(local_midway.minute(), 0);
        assert_eq!(local_midway.second(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_midway_months_calendar() {
        let now = Utc.with_ymd_and_hms(2025, 4, 15, 14, 30, 0).unwrap();
        let interval_start = Utc.with_ymd_and_hms(2025, 4, 1, 0, 0, 0).unwrap();

        // Bucket 1 (last month): midpoint should be in middle of March
        let midway_1 = TimeUnit::Months.bucket_midway(now, interval_start, 1);

        // Get bucket boundaries
        let bucket_start = TimeUnit::Months.bucket_start(now, 1);
        let bucket_end = TimeUnit::Months.bucket_end(now, 1);
        let expected = bucket_start + (bucket_end - bucket_start) / 2;

        assert_eq!(midway_1, expected);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_first_moment_ever_days_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 1, 10, 14, 30, 0).unwrap();

        // 5 buckets means 5 days back
        let first = TimeUnit::Days.first_moment_ever(now, 5);
        let local_first = first.with_timezone(&Local);

        // Should be 5 days ago at local midnight
        let now_local = now.with_timezone(&Local);
        assert_eq!(local_first.day(), now_local.day() - 5);
        assert_eq!(local_first.hour(), 0);
        assert_eq!(local_first.minute(), 0);
        assert_eq!(local_first.second(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_first_moment_ever_months_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 4, 15, 14, 30, 0).unwrap();

        // 3 buckets means 3 months back
        let first = TimeUnit::Months.first_moment_ever(now, 3);
        let local_first = first.with_timezone(&Local);

        // Should be January 1 at local midnight
        assert_eq!(local_first.month(), 1);
        assert_eq!(local_first.day(), 1);
        assert_eq!(local_first.hour(), 0);
        assert_eq!(local_first.minute(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_time_days_calendar() {
        use chrono::{Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 1, 5, 14, 30, 0).unwrap();
        let interval_start = Utc.with_ymd_and_hms(2025, 1, 5, 0, 0, 0).unwrap();

        // Bucket 1 (yesterday): representative time should be noon
        let bucket_time_1 = TimeUnit::Days.bucket_time(now, interval_start, 1);
        let local_time = bucket_time_1.with_timezone(&Local);

        // Should be at noon (12:00)
        assert_eq!(local_time.hour(), 12);
        assert_eq!(local_time.minute(), 0);
        assert_eq!(local_time.second(), 0);
    }

    // ========================================================================
    // Comprehensive Week Tests
    // ========================================================================

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_end_weeks_calendar() {
        use chrono::{Datelike, Local, Timelike, Weekday};

        // Jan 15, 2025 is a Wednesday
        let now = Utc.with_ymd_and_hms(2025, 1, 15, 14, 30, 0).unwrap();

        // bucket_idx=0 should return now
        assert_eq!(TimeUnit::Weeks.bucket_end(now, 0), now);

        // bucket_idx=1 should return local midnight of Monday of last week
        let bucket_end = TimeUnit::Weeks.bucket_end(now, 1);
        let local_bucket = bucket_end.with_timezone(&Local);

        // Should be Monday at midnight
        assert_eq!(local_bucket.weekday(), Weekday::Mon);
        assert_eq!(local_bucket.hour(), 0);
        assert_eq!(local_bucket.minute(), 0);
        assert_eq!(local_bucket.second(), 0);

        // Should be Monday Jan 13 minus 7 days = Monday Jan 6
        let now_local = now.with_timezone(&Local);
        let this_monday = calendar::find_monday(now_local.date_naive());
        let expected_monday = this_monday - chrono::Days::new(7);

        assert_eq!(local_bucket.date_naive(), expected_monday);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_midway_weeks_calendar() {
        // Jan 15, 2025 is a Wednesday
        let now = Utc.with_ymd_and_hms(2025, 1, 15, 14, 30, 0).unwrap();
        let interval_start = Utc.with_ymd_and_hms(2025, 1, 13, 0, 0, 0).unwrap(); // Monday

        // Bucket 1 (last week): midpoint should be Thursday noon
        let midway_1 = TimeUnit::Weeks.bucket_midway(now, interval_start, 1);

        // Calculate expected: bucket_start + duration/2
        let bucket_start = TimeUnit::Weeks.bucket_start(now, 1);
        let bucket_end = TimeUnit::Weeks.bucket_end(now, 1);
        let expected = bucket_start + (bucket_end - bucket_start) / 2;

        assert_eq!(
            midway_1, expected,
            "Week midpoint should be bucket_start + duration/2"
        );
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_rotate_start_interval_weeks_calendar() {
        use chrono::{Datelike, Local, Timelike, Weekday};

        // Start at Monday Jan 6, 2025 at midnight
        let start = Utc.with_ymd_and_hms(2025, 1, 6, 0, 0, 0).unwrap();

        // Rotate forward 2 weeks
        let rotated = TimeUnit::Weeks.rotate_start_interval(start, 2);
        let local_rotated = rotated.with_timezone(&Local);

        // Should be Monday Jan 20 at local midnight
        assert_eq!(local_rotated.weekday(), Weekday::Mon);
        assert_eq!(local_rotated.day(), 20);
        assert_eq!(local_rotated.hour(), 0);
        assert_eq!(local_rotated.minute(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_first_moment_ever_weeks_calendar() {
        use chrono::{Datelike, Local, Timelike, Weekday};

        let now = Utc.with_ymd_and_hms(2025, 1, 15, 14, 30, 0).unwrap();

        // 3 buckets means 3 weeks back from this Monday
        let first = TimeUnit::Weeks.first_moment_ever(now, 3);
        let local_first = first.with_timezone(&Local);

        // Should be Monday 3 weeks ago at local midnight
        assert_eq!(local_first.weekday(), Weekday::Mon);
        assert_eq!(local_first.hour(), 0);
        assert_eq!(local_first.minute(), 0);

        // Calculate expected Monday
        let now_local = now.with_timezone(&Local);
        let this_monday = calendar::find_monday(now_local.date_naive());
        let expected_monday = this_monday - chrono::Days::new(3 * 7);

        assert_eq!(local_first.date_naive(), expected_monday);
    }

    // ========================================================================
    // Comprehensive Years Tests
    // ========================================================================

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_end_years_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 4, 15, 14, 30, 0).unwrap();

        // bucket_idx=0 should return now
        assert_eq!(TimeUnit::Years.bucket_end(now, 0), now);

        // bucket_idx=1 should return local midnight of Jan 1, 2024
        let bucket_end = TimeUnit::Years.bucket_end(now, 1);
        let local_bucket = bucket_end.with_timezone(&Local);

        // Should be Jan 1, 2024 at midnight
        assert_eq!(local_bucket.year(), 2024);
        assert_eq!(local_bucket.month(), 1);
        assert_eq!(local_bucket.day(), 1);
        assert_eq!(local_bucket.hour(), 0);
        assert_eq!(local_bucket.minute(), 0);
        assert_eq!(local_bucket.second(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_bucket_midway_years_calendar() {
        let now = Utc.with_ymd_and_hms(2025, 6, 15, 14, 30, 0).unwrap();
        let interval_start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        // Bucket 1 (last year): midpoint should be middle of 2024
        let midway_1 = TimeUnit::Years.bucket_midway(now, interval_start, 1);

        // Calculate expected: bucket_start + duration/2
        let bucket_start = TimeUnit::Years.bucket_start(now, 1);
        let bucket_end = TimeUnit::Years.bucket_end(now, 1);
        let expected = bucket_start + (bucket_end - bucket_start) / 2;

        assert_eq!(
            midway_1, expected,
            "Year midpoint should be bucket_start + duration/2"
        );
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_rotate_start_interval_years_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();

        // Rotate forward 2 years
        let rotated = TimeUnit::Years.rotate_start_interval(start, 2);
        let local_rotated = rotated.with_timezone(&Local);

        // Should be Jan 1, 2025 at local midnight
        assert_eq!(local_rotated.year(), 2025);
        assert_eq!(local_rotated.month(), 1);
        assert_eq!(local_rotated.day(), 1);
        assert_eq!(local_rotated.hour(), 0);
        assert_eq!(local_rotated.minute(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_first_moment_ever_years_calendar() {
        use chrono::{Datelike, Local, Timelike};

        let now = Utc.with_ymd_and_hms(2025, 6, 15, 14, 30, 0).unwrap();

        // 3 buckets means 3 years back
        let first = TimeUnit::Years.first_moment_ever(now, 3);
        let local_first = first.with_timezone(&Local);

        // Should be January 1, 2022 at local midnight
        assert_eq!(local_first.year(), 2022);
        assert_eq!(local_first.month(), 1);
        assert_eq!(local_first.day(), 1);
        assert_eq!(local_first.hour(), 0);
        assert_eq!(local_first.minute(), 0);
    }

    // ========================================================================
    // Year Rollover Tests
    // ========================================================================

    #[test]
    #[cfg(feature = "calendar")]
    fn test_week_spanning_year_boundary() {
        use chrono::{Datelike, Local, Timelike, Weekday};

        // Dec 30, 2024 is a Monday, Jan 6, 2025 is also a Monday
        let now = Utc.with_ymd_and_hms(2025, 1, 3, 10, 0, 0).unwrap(); // Friday, Jan 3

        // bucket_idx=1 should return last week's Monday (Dec 23, 2024)
        let bucket_end = TimeUnit::Weeks.bucket_end(now, 1);
        let local_bucket = bucket_end.with_timezone(&Local);

        assert_eq!(local_bucket.year(), 2024);
        assert_eq!(local_bucket.month(), 12);
        assert_eq!(local_bucket.day(), 23);
        assert_eq!(local_bucket.weekday(), Weekday::Mon);
        assert_eq!(local_bucket.hour(), 0);
        assert_eq!(local_bucket.minute(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_month_bucket_end_crossing_year_backward() {
        use chrono::{Datelike, Local, Timelike};

        // Start in January 2025
        let now = Utc.with_ymd_and_hms(2025, 1, 15, 10, 0, 0).unwrap();

        // bucket_idx=2 should return Nov 1, 2024 at midnight
        let bucket_end = TimeUnit::Months.bucket_end(now, 2);
        let local_bucket = bucket_end.with_timezone(&Local);

        assert_eq!(local_bucket.year(), 2024);
        assert_eq!(local_bucket.month(), 11);
        assert_eq!(local_bucket.day(), 1);
        assert_eq!(local_bucket.hour(), 0);
        assert_eq!(local_bucket.minute(), 0);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_days_crossing_year() {
        // From Dec 28, 2024 to Jan 5, 2025 (8 calendar days)
        let then = Utc.with_ymd_and_hms(2024, 12, 28, 12, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 1, 5, 12, 0, 0).unwrap();

        let rotations = TimeUnit::Days.num_rotations(then, now);

        // Calculate expected in local timezone
        use chrono::Local;
        let then_local = then.with_timezone(&Local).date_naive();
        let now_local = now.with_timezone(&Local).date_naive();
        let expected = (now_local - then_local).num_days();

        assert_eq!(rotations, expected);
        // Should be 8 days (but verify with actual local calculation)
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_months_crossing_year() {
        // From Oct 2024 to Feb 2025 (4 months)
        let then = Utc.with_ymd_and_hms(2024, 10, 15, 12, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 2, 15, 12, 0, 0).unwrap();

        let rotations = TimeUnit::Months.num_rotations(then, now);

        // Oct → Nov → Dec → Jan → Feb = 4 month boundaries crossed
        assert_eq!(rotations, 4);
    }

    #[test]
    #[cfg(feature = "calendar")]
    fn test_num_rotations_years_multiple() {
        // From 2020 to 2025 (5 years)
        let then = Utc.with_ymd_and_hms(2020, 6, 15, 12, 0, 0).unwrap();
        let now = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();

        let rotations = TimeUnit::Years.num_rotations(then, now);

        // 2020 → 2021 → 2022 → 2023 → 2024 → 2025 = 5 year boundaries
        assert_eq!(rotations, 5);
    }
}