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
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
/// Query builders for fluent event querying.
use std::ops::Range;
use std::sync::Arc;

use chrono::Duration;

use crate::{EventStoreInner, TimeUnit};

/// Builder for constructing queries on a single event.
///
/// Created by `EventStore::query()`, this builder provides methods to specify
/// time ranges before executing aggregation operations.
#[must_use = "query builders do nothing unless consumed"]
pub struct Query {
    store: Arc<EventStoreInner>,
    event_id: String,
}

impl Query {
    /// Creates a new Query builder.
    ///
    /// This is typically called by EventStore, not directly by users.
    pub(crate) fn new(store: Arc<EventStoreInner>, event_id: String) -> Self {
        Self { store, event_id }
    }

    pub(crate) fn last(self, n: usize, unit: TimeUnit) -> RangeQuery {
        RangeQuery::new(self.store, self.event_id, unit, 0..n)
    }

    /// Query the last N seconds.
    pub fn last_seconds(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Seconds)
    }

    /// Query the last N minutes.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::EventStore;
    ///
    /// let store = EventStore::new();
    /// store.record("event");
    ///
    /// let count = store.query("event").last_minutes(60).sum();
    /// assert_eq!(count, Some(1));
    /// ```
    pub fn last_minutes(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Minutes)
    }

    /// Query the last N hours.
    pub fn last_hours(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Hours)
    }

    /// Query the last N days.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::EventStore;
    ///
    /// let store = EventStore::new();
    /// store.record("app_launch");
    ///
    /// let count = store.query("app_launch").last_days(7).sum();
    /// assert_eq!(count, Some(1));
    /// ```
    pub fn last_days(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Days)
    }

    /// Query the last N weeks.
    pub fn last_weeks(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Weeks)
    }

    /// Query the last N months (28-day approximation).
    pub fn last_months(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Months)
    }

    /// Query the last N years (365-day approximation).
    pub fn last_years(self, n: usize) -> RangeQuery {
        self.last(n, TimeUnit::Years)
    }

    /// Query all available data (all buckets).
    ///
    /// Uses the longest time unit configured for this event to capture
    /// the maximum available history.
    pub fn ever(self) -> RangeQuery {
        // Use TimeUnit::Ever to defer resolution until query execution
        // This avoids loading the counter twice
        self.last(usize::MAX, TimeUnit::Ever)
    }

    /// Query a specific range of days.
    pub fn days(self, range: Range<usize>) -> RangeQuery {
        RangeQuery::new(self.store, self.event_id, TimeUnit::Days, range)
    }

    /// Start building a query from an offset of days.
    ///
    /// Use with `.take(n)` to specify the range length.
    pub fn days_from(self, offset: usize) -> RangeQuery {
        RangeQuery::new(
            self.store,
            self.event_id,
            TimeUnit::Days,
            offset..usize::MAX,
        )
    }

    /// Returns the time since the event was last seen.
    ///
    /// Returns None if the event has never been recorded or doesn't exist.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::EventStore;
    /// use chrono::Duration;
    ///
    /// let store = EventStore::new();
    /// store.record("settings_visit");
    ///
    /// let time_since = store.query("settings_visit").last_seen();
    /// assert!(time_since.is_some());
    ///
    /// // Check for events never recorded
    /// let never_seen = store.query("never_happened").last_seen();
    /// assert!(never_seen.is_none());
    /// ```
    pub fn last_seen(self) -> Option<Duration> {
        let clock_now = self.store.clock_now();
        let counter_arc = self.store.get_counter_for_query(&self.event_id)?;
        let mut counter = counter_arc.lock().unwrap();

        counter.advance_if_needed(clock_now);

        // Get time units from counter and sort from smallest to largest
        let configs = self.store.config.configs();

        // Try to find the event in any time unit, starting with the finest granularity
        for interval_idx in 0..configs.len() {
            let config = &configs[interval_idx];
            let time_unit = config.time_unit();

            if let Some(bucket_idx) = counter.last_seen_in(time_unit) {
                // SAFETY: This cannot panic. We got `config` from the counter's own interval list,
                // so the time_unit MUST exist in the counter. If this panics, it's a bug in
                // tiny-counter's internal logic, not user error.
                let interval_start = counter.interval_start(time_unit).expect(
                    "BUG: Interval must exist - we just retrieved config from counter's intervals",
                );

                // If this is the smallest interval, we have the most precise answer
                if interval_idx == 0 {
                    let estimate = time_unit.bucket_midway(clock_now, interval_start, bucket_idx);
                    return Some(clock_now - estimate);
                }

                // Check for gap: event not in smaller interval but is in this larger one
                // Since we iterate smallest→largest, if we're here, smaller interval returned None
                let prev_config = &configs[interval_idx - 1];

                // Calculate where the smaller interval coverage ends
                // SAFETY: This cannot panic. prev_config came from counter's intervals (index interval_idx-1).
                // If this panics, it's a bug in tiny-counter, not user error.
                let prev_interval_start = counter.interval_start(prev_config.time_unit()).expect(
                    "BUG: Smaller interval must exist - we just retrieved prev_config from counter's intervals",
                );
                let prev_coverage_end = prev_config.first_moment_ever(prev_interval_start);

                // Which bucket in THIS interval does that coverage end fall into?
                let coverage_end_bucket = time_unit
                    .bucket_idx(interval_start, prev_coverage_end)
                    .unwrap_or_default();

                // If event is in the same bucket (or earlier) where coverage ends, it's in the gap
                if bucket_idx <= coverage_end_bucket {
                    // GAP DETECTED!
                    // Gap boundaries: between the far end of this bucket and where smaller interval coverage ends

                    // Far end of the bucket (earliest time, furthest from now)
                    // For bucket 0, this is one full bucket duration ago
                    let gap_earliest = time_unit.bucket_start(clock_now, bucket_idx);
                    // End of smaller interval coverage (latest time, closest to now within gap)
                    let gap_latest = prev_coverage_end;

                    // Calculate gap midpoint as a timestamp
                    let gap_midpoint = gap_earliest + ((gap_latest - gap_earliest) / 2);

                    // Return duration from now to gap midpoint
                    return Some(clock_now - gap_midpoint);
                }

                // Event is beyond the gap, use normal estimation
                let estimate = time_unit.bucket_midway(clock_now, interval_start, bucket_idx);
                return Some(clock_now - estimate);
            }
        }
        None
    }

    /// Returns an estimate for the time since the event was first seen.
    ///
    /// Returns None if the event has never been recorded or doesn't exist.
    /// This searches for the oldest non-zero bucket across all tracked time units.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::EventStore;
    /// use chrono::Duration;
    ///
    /// let store = EventStore::new();
    /// store.record("user_signup");
    ///
    /// let time_since = store.query("user_signup").first_seen();
    /// assert!(time_since.is_some());
    ///
    /// // Check for events never recorded
    /// let never_seen = store.query("never_happened").first_seen();
    /// assert!(never_seen.is_none());
    /// ```
    pub fn first_seen(self) -> Option<Duration> {
        let clock_now = self.store.clock_now();
        let counter_arc = self.store.get_counter_for_query(&self.event_id)?;
        let mut counter = counter_arc.lock().unwrap();
        counter.advance_if_needed(clock_now);

        // Get configs in ascending order, iterate in reverse for largest to smallest
        let configs = self.store.config.configs();

        // Iterate from largest to smallest (end to start)
        for interval_idx in (0..configs.len()).rev() {
            let config = &configs[interval_idx];
            let time_unit = config.time_unit();
            if let Some(bucket_idx) = counter.first_seen_in(time_unit) {
                // SAFETY: This cannot panic. We got `config` from the counter's own interval list,
                // so the time_unit MUST exist in the counter. If this panics, it's a bug in
                // tiny-counter's internal logic, not user error.
                let interval_start = counter.interval_start(time_unit).expect(
                    "BUG: Interval must exist - we just retrieved config from counter's intervals",
                );
                // Check if we're on the smallest interval (e.g. minutes)
                if interval_idx == 0 {
                    // Last interval - we have to accept this as our result.
                    let midway = time_unit.bucket_midway(clock_now, interval_start, bucket_idx);
                    return Some(clock_now - midway);
                }

                // Get the next smaller interval
                let next_config = &configs[interval_idx - 1];

                // Starting bucket is the bucket in larger config which an event that would
                // have been recorded in the last bucket of the smaller config.

                // SAFETY: This cannot panic. next_config came from counter's intervals (index interval_idx-1).
                // If this panics, it's a bug in tiny-counter, not user error.
                let next_interval_start = counter.interval_start(next_config.time_unit()).expect(
                    "BUG: Smaller interval must exist - we just retrieved next_config from counter's intervals",
                );

                let starting_moment = next_config.first_moment_ever(next_interval_start);
                let starting_bucket = time_unit
                    .bucket_idx(interval_start, starting_moment)
                    .unwrap_or_default()
                    + 1;

                // If the bucket where we found the earliest event doesn't correspond to
                // a bucket of smaller granularity, then we guess the midpoint of the larger bucket.
                if bucket_idx > starting_bucket {
                    // Beyond starting bucket - this is our answer
                    let midway = time_unit.bucket_midway(clock_now, interval_start, bucket_idx);
                    return Some(clock_now - midway);
                }
                // Next, we check if all the events between the starting point and now
                // are accounted for by the buckets of smaller granularity.
                let this_count = counter
                    .sum_range(time_unit, 0..starting_bucket + 1)
                    .unwrap_or(0);
                let next_count = counter
                    .sum_range(next_config.time_unit(), 0..usize::MAX)
                    .unwrap_or(0);

                // If there was an over count, then we know the first event happened somewhere
                // after the larger bucket started, but before all of the smaller buckets started.
                if this_count > next_count {
                    // So we guess at the midpoint between those two.
                    let earliest = clock_now - time_unit.bucket_end(interval_start, bucket_idx);
                    let latest = clock_now - next_config.first_moment_ever(next_interval_start);
                    return Some((earliest + latest) / 2);
                }
                // If not, then: we know that there is a more granular count available,
                // and we just go to the next time unit.
            }
        }

        None
    }

    /// Returns the time since the event was first seen in a specific time unit.
    ///
    /// Returns None if the event has never been recorded, doesn't exist,
    /// or the time unit is not tracked.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::{EventStore, TimeUnit};
    /// use chrono::Duration;
    ///
    /// let store = EventStore::new();
    /// store.record("page_view");
    ///
    /// let time_since = store.query("page_view").first_seen_in(TimeUnit::Days);
    /// assert!(time_since.is_some());
    /// ```
    pub fn first_seen_in(self, time_unit: TimeUnit) -> Option<Duration> {
        let clock_now = self.store.clock_now();
        let time_unit = self.store.config.specified_time_unit(time_unit);
        let counter_arc = self.store.get_counter_for_query(&self.event_id)?;
        let mut counter = counter_arc.lock().unwrap();
        counter.advance_if_needed(clock_now);

        if let Some(bucket_idx) = counter.first_seen_in(time_unit) {
            // Convert bucket index to duration
            let duration = time_unit.duration() * bucket_idx as i32;
            Some(duration)
        } else {
            None
        }
    }
}

/// Builder for querying a specific time range.
///
/// Provides aggregation methods like sum(), average(), and iteration over buckets.
#[must_use = "query builders do nothing unless consumed"]
pub struct RangeQuery {
    store: Arc<EventStoreInner>,
    event_id: String,
    time_unit: TimeUnit,
    range: Range<usize>,
}

impl RangeQuery {
    /// Creates a new RangeQuery.
    fn new(
        store: Arc<EventStoreInner>,
        event_id: String,
        time_unit: TimeUnit,
        range: Range<usize>,
    ) -> Self {
        Self {
            store,
            event_id,
            time_unit,
            range,
        }
    }

    /// Limit the range to at most N buckets.
    pub fn take(mut self, n: usize) -> Self {
        self.range.end = self.range.start + n;
        self
    }

    /// Sum all events in the range.
    ///
    /// Returns None if the event doesn't exist or the time unit isn't tracked.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::EventStore;
    ///
    /// let store = EventStore::new();
    /// store.record_count("clicks", 10);
    ///
    /// let total = store.query("clicks").last_days(7).sum();
    /// assert_eq!(total, Some(10));
    /// ```
    pub fn sum(self) -> Option<u32> {
        let clock_now = self.store.clock_now();
        let counter_arc = self.store.get_counter_for_query(&self.event_id)?;
        let time_unit = self.store.config.specified_time_unit(self.time_unit);
        let mut counter = counter_arc.lock().unwrap();
        counter.advance_if_needed(clock_now);
        counter.sum_range(time_unit, self.range)
    }

    /// Calculate the average count per bucket.
    ///
    /// Returns None if the event doesn't exist, the time unit isn't tracked,
    /// or there's no data in the range.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_counter::EventStore;
    ///
    /// let store = EventStore::new();
    /// store.record_count("api_calls", 100);
    ///
    /// let avg = store.query("api_calls").last_days(7).average();
    /// assert!(avg.is_some());
    /// ```
    pub fn average(self) -> Option<f64> {
        let count = (self.range.end - self.range.start) as f64;
        let sum = self.sum()?;
        match sum {
            0 => Some(0.0),
            s => {
                if count > 0.0 {
                    Some(s as f64 / count)
                } else {
                    None
                }
            }
        }
    }

    /// Calculate the average excluding zero buckets.
    ///
    /// Returns None if the event doesn't exist, the time unit isn't tracked,
    /// or there are no non-zero buckets.
    pub fn average_nonzero(self) -> Option<f64> {
        let buckets = self.into_buckets();
        if buckets.is_empty() {
            return None;
        }

        let non_zero: Vec<u32> = buckets.iter().copied().filter(|&x| x > 0).collect();
        if non_zero.is_empty() {
            return None;
        }

        let sum: u64 = non_zero
            .iter()
            .fold(0u64, |acc, &val| acc.saturating_add(val as u64));
        let avg = sum as f64 / non_zero.len() as f64;
        Some(avg)
    }

    /// Sum the number of non-zero buckets.
    ///
    /// Returns None if the event doesn't exist or the time unit isn't tracked.
    pub fn count_nonzero(self) -> Option<usize> {
        let buckets = self.into_buckets();
        if buckets.is_empty() {
            return None;
        }

        let count = buckets.iter().filter(|&&x| x > 0).count();
        Some(count)
    }

    /// Returns the bucket index of the last seen event.
    ///
    /// Returns None if the event doesn't exist, the time unit isn't tracked,
    /// or the event has never been recorded.
    pub fn last_seen(self) -> Option<usize> {
        let clock_now = self.store.clock_now();
        let time_unit = self.store.config.specified_time_unit(self.time_unit);
        let counter_arc = self.store.get_counter_for_query(&self.event_id)?;
        let mut counter = counter_arc.lock().unwrap();
        counter.advance_if_needed(clock_now);
        counter.last_seen_in(time_unit)
    }

    /// Returns the bucket index of the first seen event.
    ///
    /// Returns None if the event doesn't exist, the time unit isn't tracked,
    /// or the event has never been recorded.
    pub fn first_seen(self) -> Option<usize> {
        let clock_now = self.store.clock_now();
        let time_unit = self.store.config.specified_time_unit(self.time_unit);
        let counter_arc = self.store.get_counter_for_query(&self.event_id)?;
        let mut counter = counter_arc.lock().unwrap();
        counter.advance_if_needed(clock_now);
        counter.first_seen_in(time_unit)
    }

    /// Returns a vector of bucket counts for the range.
    pub fn into_buckets(self) -> Vec<u32> {
        let clock_now = self.store.clock_now();
        let time_unit = self.store.config.specified_time_unit(self.time_unit);

        let counter_arc = match self.store.get_counter_for_query(&self.event_id) {
            Some(arc) => arc,
            None => return Vec::new(),
        };

        let mut counter = counter_arc.lock().unwrap();
        counter.advance_if_needed(clock_now);

        let interval = match counter.interval(time_unit) {
            Some(interval) => interval,
            None => return Vec::new(),
        };

        let end = self.range.end.min(interval.bucket_count());

        (self.range.start..end)
            .filter_map(|i| interval.bucket_value(i))
            .collect()
    }
}

/// Builder for querying multiple events.
#[must_use = "query builders do nothing unless consumed"]
pub struct MultiQuery {
    store: Arc<EventStoreInner>,
    event_ids: Vec<String>,
}

impl MultiQuery {
    /// Creates a new MultiQuery builder.
    pub(crate) fn new(store: Arc<EventStoreInner>, event_ids: Vec<String>) -> Self {
        Self { store, event_ids }
    }

    pub(crate) fn last(self, n: usize, unit: TimeUnit) -> MultiRangeQuery {
        MultiRangeQuery::new(self.store, self.event_ids, unit, 0..n)
    }

    /// Query the last N seconds.
    pub fn last_seconds(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Seconds)
    }

    /// Query the last N minutes across all events.
    pub fn last_minutes(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Minutes)
    }

    /// Query the last N hours across all events.
    pub fn last_hours(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Hours)
    }

    /// Query the last N days across all events.
    pub fn last_days(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Days)
    }

    /// Query the last N weeks across all events.
    pub fn last_weeks(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Weeks)
    }

    /// Query the last N months across all events.
    pub fn last_months(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Months)
    }

    /// Query the last N years across all events.
    pub fn last_years(self, n: usize) -> MultiRangeQuery {
        self.last(n, TimeUnit::Years)
    }

    /// Query all available data across all events.
    pub fn ever(self) -> MultiRangeQuery {
        // Use TimeUnit::Ever which will be resolved per-event during query execution
        // For multi-event queries, we take the minimum across events
        self.last(usize::MAX, TimeUnit::Ever)
    }
}

/// Range query over multiple events.
#[must_use = "query builders do nothing unless consumed"]
pub struct MultiRangeQuery {
    store: Arc<EventStoreInner>,
    event_ids: Vec<String>,
    time_unit: TimeUnit,
    range: Range<usize>,
}

impl MultiRangeQuery {
    fn new(
        store: Arc<EventStoreInner>,
        event_ids: Vec<String>,
        time_unit: TimeUnit,
        range: Range<usize>,
    ) -> Self {
        Self {
            store,
            event_ids,
            time_unit,
            range,
        }
    }

    /// Sum all events across all tracked counters.
    ///
    /// Uses saturating addition - if the sum exceeds u32::MAX, it saturates.
    pub fn sum(self) -> Option<u32> {
        let clock_now = self.store.clock_now();

        let mut total = 0u32;
        let mut found_any = false;
        let time_unit = self.store.config.specified_time_unit(self.time_unit);
        for event_id in &self.event_ids {
            if let Some(counter_arc) = self.store.get_counter_for_query(event_id) {
                let mut counter = counter_arc.lock().unwrap();
                counter.advance_if_needed(clock_now);
                if let Some(sum) = counter.sum_range(time_unit, self.range.clone()) {
                    total = total.saturating_add(sum);
                    found_any = true;
                }
            }
        }

        if found_any {
            Some(total)
        } else {
            None
        }
    }

    /// Calculate average across all events.
    pub fn average(self) -> Option<f64> {
        let count = (self.range.end - self.range.start) as f64;
        let sum = self.sum();
        match sum {
            None => None,
            Some(0) => Some(0.0),
            Some(s) => {
                if count > 0.0 {
                    Some(s as f64 / count)
                } else {
                    None
                }
            }
        }
    }
}

/// Builder for calculating ratios between two events.
#[must_use = "query builders do nothing unless consumed"]
pub struct RatioQuery {
    store: Arc<EventStoreInner>,
    numerator_id: String,
    denominator_id: String,
}

impl RatioQuery {
    /// Creates a new RatioQuery builder.
    pub(crate) fn new(
        store: Arc<EventStoreInner>,
        numerator_id: String,
        denominator_id: String,
    ) -> Self {
        Self {
            store,
            numerator_id,
            denominator_id,
        }
    }

    pub(crate) fn last(self, n: usize, unit: TimeUnit) -> Option<f64> {
        self.calculate_ratio(unit, 0..n)
    }

    /// Calculate ratio over the last N seconds.
    pub fn last_seconds(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Seconds)
    }

    /// Calculate ratio over the last N minutes.
    pub fn last_minutes(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Minutes)
    }

    /// Calculate ratio over the last N hours.
    pub fn last_hours(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Hours)
    }

    /// Calculate ratio over the last N days.
    pub fn last_days(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Days)
    }

    /// Calculate ratio over the last N weeks.
    pub fn last_weeks(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Weeks)
    }

    /// Calculate ratio over the last N months.
    pub fn last_months(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Months)
    }

    /// Calculate ratio over the last N years.
    pub fn last_years(self, n: usize) -> Option<f64> {
        self.last(n, TimeUnit::Years)
    }

    /// Calculate ratio over all available data.
    pub fn ever(self) -> Option<f64> {
        // Use TimeUnit::Ever which will be resolved during query execution
        self.last(usize::MAX, TimeUnit::Ever)
    }

    fn calculate_ratio(self, time_unit: TimeUnit, range: Range<usize>) -> Option<f64> {
        let clock_now = self.store.clock_now();

        // Resolve TimeUnit::Ever from the configuration
        let time_unit = self.store.config.specified_time_unit(time_unit);

        // Get counters first
        let numerator = self.store.get_counter_for_query(&self.numerator_id)?;
        let mut numerator_counter = numerator.lock().unwrap();
        numerator_counter.advance_if_needed(clock_now);

        let denominator = self.store.get_counter_for_query(&self.denominator_id)?;
        let mut denominator_counter = denominator.lock().unwrap();
        denominator_counter.advance_if_needed(clock_now);

        let numerator_sum = numerator_counter
            .sum_range(time_unit, range.clone())
            .unwrap_or(0);
        let denominator_sum = denominator_counter
            .sum_range(time_unit, range.clone())
            .unwrap_or(0);

        if denominator_sum == 0 {
            None // Avoid division by zero
        } else {
            Some(numerator_sum as f64 / denominator_sum as f64)
        }
    }
}

/// Builder for calculating deltas (net changes) between two events.
#[must_use = "query builders do nothing unless consumed"]
pub struct DeltaQuery {
    store: Arc<EventStoreInner>,
    positive_id: String,
    negative_id: String,
}

impl DeltaQuery {
    /// Creates a new DeltaQuery builder.
    pub(crate) fn new(
        store: Arc<EventStoreInner>,
        positive_id: String,
        negative_id: String,
    ) -> Self {
        Self {
            store,
            positive_id,
            negative_id,
        }
    }

    pub(crate) fn last(self, n: usize, unit: TimeUnit) -> DeltaRangeQuery {
        DeltaRangeQuery::new(self.store, self.positive_id, self.negative_id, unit, 0..n)
    }

    /// Calculate delta over the last N seconds.
    pub fn last_seconds(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Seconds)
    }

    /// Calculate delta over the last N minutes.
    pub fn last_minutes(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Minutes)
    }

    /// Calculate delta over the last N hours.
    pub fn last_hours(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Hours)
    }

    /// Calculate delta over the last N days.
    pub fn last_days(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Days)
    }

    /// Calculate delta over the last N weeks.
    pub fn last_weeks(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Weeks)
    }

    /// Calculate delta over the last N months.
    pub fn last_months(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Months)
    }

    /// Calculate delta over the last N years.
    pub fn last_years(self, n: usize) -> DeltaRangeQuery {
        self.last(n, TimeUnit::Years)
    }

    /// Calculate delta over all available data.
    pub fn ever(self) -> DeltaRangeQuery {
        // Use TimeUnit::Ever which will be resolved during query execution
        self.last(usize::MAX, TimeUnit::Ever)
    }
}

/// Range query for delta calculations.
#[must_use = "query builders do nothing unless consumed"]
pub struct DeltaRangeQuery {
    store: Arc<EventStoreInner>,
    positive_id: String,
    negative_id: String,
    time_unit: TimeUnit,
    range: Range<usize>,
}

impl DeltaRangeQuery {
    fn new(
        store: Arc<EventStoreInner>,
        positive_id: String,
        negative_id: String,
        time_unit: TimeUnit,
        range: Range<usize>,
    ) -> Self {
        Self {
            store,
            positive_id,
            negative_id,
            time_unit,
            range,
        }
    }

    /// Calculate the net change (positive - negative).
    ///
    /// Returns 0 if both events don't exist or the time unit isn't tracked.
    /// Can return negative values if negative exceeds positive.
    pub fn sum(self) -> i64 {
        let clock_now = self.store.clock_now();

        // Get counters (if they exist)
        let positive_counter = self.store.get_counter_for_query(&self.positive_id);
        let negative_counter = self.store.get_counter_for_query(&self.negative_id);

        let time_unit = self.store.config.specified_time_unit(self.time_unit);

        let positive_sum = match positive_counter {
            Some(counter_arc) => {
                let mut counter = counter_arc.lock().unwrap();
                counter.advance_if_needed(clock_now);
                counter
                    .sum_range(time_unit, self.range.clone())
                    .unwrap_or(0) as i64
            }
            None => 0,
        };

        let negative_sum = match negative_counter {
            Some(counter_arc) => {
                let mut counter = counter_arc.lock().unwrap();
                counter.advance_if_needed(clock_now);
                counter
                    .sum_range(time_unit, self.range.clone())
                    .unwrap_or(0) as i64
            }
            None => 0,
        };

        positive_sum - negative_sum
    }

    /// Calculate the average delta per bucket.
    pub fn average(self) -> f64 {
        let count = (self.range.end - self.range.start) as f64;
        let sum = self.sum();
        if count > 0.0 {
            sum as f64 / count
        } else {
            0.0
        }
    }
}

#[cfg(test)]
mod tests {

    use std::sync::Arc;

    use chrono::{DateTime, Datelike, Duration, TimeZone, Utc};

    use crate::{Clock, EventStore, TestClock, TimeUnit};

    #[test]
    fn test_query_last_days_sum() {
        let store = EventStore::new();
        store.record_count("event", 5);
        store.record_count("event", 3);

        let sum = store.query("event").last_days(1).sum();
        assert_eq!(sum, Some(8));
    }

    #[test]
    fn test_query_nonexistent_event() {
        let store = EventStore::new();
        let sum = store.query("nonexistent").last_days(1).sum();
        assert_eq!(sum, None);
    }

    #[test]
    fn test_range_query_average() {
        let store = EventStore::new();
        store.record_count("event", 10);

        let avg = store.query("event").last_days(2).average();
        // 10 events across 2 days = 5.0 average
        assert_eq!(avg, Some(5.0));
    }

    #[test]
    fn test_range_query_take() {
        let store = EventStore::new();
        store.record_count("event", 5);

        let sum = store.query("event").days_from(0).take(1).sum();
        assert_eq!(sum, Some(5));
    }

    #[test]
    fn test_multi_query_sum() {
        let store = EventStore::new();
        store.record_count("event1", 5);
        store.record_count("event2", 3);

        let sum = store.query_many(&["event1", "event2"]).last_days(1).sum();
        assert_eq!(sum, Some(8));
    }

    #[test]
    fn test_ratio_query() {
        let store = EventStore::new();
        store.record_count("num", 6);
        store.record_count("denom", 3);

        let ratio = store.query_ratio("num", "denom").last_days(1);
        assert_eq!(ratio, Some(2.0));
    }

    #[test]
    fn test_ratio_query_division_by_zero() {
        let store = EventStore::new();
        store.record_count("num", 6);
        // denominator has 0 events

        let ratio = store.query_ratio("num", "denom").last_days(1);
        assert_eq!(ratio, None); // Should return None for division by zero
    }

    #[test]
    fn test_delta_query_positive() {
        let store = EventStore::new();
        store.record_count("pos", 10);
        store.record_count("neg", 3);

        let delta = store.query_delta("pos", "neg").last_days(1).sum();
        assert_eq!(delta, 7);
    }

    #[test]
    fn test_delta_query_negative() {
        let store = EventStore::new();
        store.record_count("pos", 3);
        store.record_count("neg", 10);

        let delta = store.query_delta("pos", "neg").last_days(1).sum();
        assert_eq!(delta, -7); // Can be negative!
    }

    #[test]
    fn test_delta_query_zero() {
        let store = EventStore::new();
        let delta = store.query_delta("pos", "neg").last_days(1).sum();
        assert_eq!(delta, 0);
    }

    #[test]
    fn test_count_nonzero() {
        let store = EventStore::new();
        store.record_count("event", 5);
        // Only 1 bucket has data

        let count = store.query("event").last_days(7).count_nonzero();
        assert_eq!(count, Some(1));
    }

    #[test]
    fn test_average_nonzero() {
        let store = EventStore::new();
        store.record_count("event", 10);

        let avg = store.query("event").last_days(7).average_nonzero();
        // Only 1 bucket has data with value 10
        assert_eq!(avg, Some(10.0));
    }

    #[test]
    fn test_ever_uses_longest_time_unit() {
        // Test that ever() uses the longest configured time unit for the event
        let store = EventStore::new();
        store.record_count("event", 100);

        // The default config includes Years as the longest time unit
        let sum = store.query("event").ever().sum();
        assert_eq!(sum, Some(100));
    }

    #[test]
    fn test_ever_with_nonexistent_event() {
        // Test that ever() handles nonexistent events gracefully
        let store = EventStore::new();

        let sum = store.query("nonexistent").ever().sum();
        assert_eq!(sum, None);
    }

    #[test]
    fn test_ever_uses_time_unit_ever_variant() {
        // Test that ever() now uses TimeUnit::Ever instead of loading counter twice
        let store = EventStore::new();
        store.record_count("event", 100);

        // Create a query with ever()
        let query = store.query("event").ever();

        // The query should have TimeUnit::Ever before execution
        // (We can't directly inspect it, but we can verify it still works)
        let sum = query.sum();
        assert_eq!(sum, Some(100));
    }

    #[test]
    fn test_multi_query_ever() {
        let store = EventStore::new();
        store.record_count("event1", 50);
        store.record_count("event2", 75);

        let sum = store.query_many(&["event1", "event2"]).ever().sum();
        assert_eq!(sum, Some(125));
    }

    #[test]
    fn test_ratio_query_ever() {
        let store = EventStore::new();
        store.record_count("num", 100);
        store.record_count("denom", 25);

        let ratio = store.query_ratio("num", "denom").ever();
        assert_eq!(ratio, Some(4.0));
    }

    #[test]
    fn test_delta_query_ever() {
        let store = EventStore::new();
        store.record_count("pos", 150);
        store.record_count("neg", 50);

        let delta = store.query_delta("pos", "neg").ever().sum();
        assert_eq!(delta, 100);
    }

    #[test]
    fn test_multi_range_query_handles_large_values() {
        let store = EventStore::new();

        // Record max u32 values
        store.record_count("event1", u32::MAX);
        store.record_count("event2", u32::MAX);
        store.record_count("event3", u32::MAX);

        let sum = store
            .query_many(&["event1", "event2", "event3"])
            .last_days(1)
            .sum();

        // Sum saturates at u32::MAX
        assert_eq!(sum, Some(u32::MAX));
    }

    #[test]
    fn test_average_nonzero_handles_large_values() {
        use crate::store::builder::EventStoreBuilder;

        let store = EventStoreBuilder::new().track_days(5).build().unwrap();

        // Record large values that will saturate at u32::MAX
        // These all go to the same bucket
        store.record_count("event", u32::MAX / 3);
        store.record_count("event", u32::MAX / 3);
        store.record_count("event", u32::MAX / 3);

        let avg = store.query("event").last_days(5).average_nonzero();

        // Should handle large values correctly
        assert!(avg.is_some());
        let avg_value = avg.unwrap();
        // Single bucket with 3×(u32::MAX/3) = u32::MAX, so average equals u32::MAX
        assert_eq!(avg_value, u32::MAX as f64);
    }

    #[test]
    fn test_first_seen_returns_oldest_event_touching_buckets() {
        use chrono::{TimeZone, Utc};
        // Use fixed time at noon to avoid midnight crossing issues
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(60)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::hours(5));
        store.record("event");

        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        assert_eq!(first, Some(Duration::hours(5) + Duration::minutes(30)));

        // last_seen should return 0 (most recent)
        assert!(last.is_some());
        assert!(last.unwrap() == Duration::minutes(0));
    }

    #[test]
    fn test_first_seen_returns_oldest_event_overlapping_buckets() {
        use chrono::{TimeZone, Utc};
        // Use fixed time at noon to avoid midnight crossing issues
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(60 * 24)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::hours(5));
        store.record("event");

        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        assert_eq!(first, Some(Duration::hours(5) + Duration::seconds(30)));

        // last_seen should return 0 (most recent)
        assert!(last.is_some());
        assert!(last.unwrap() == Duration::minutes(0));
    }

    #[test]
    fn test_first_seen_returns_oldest_event_disjoint_buckets() {
        use chrono::{TimeZone, Utc};
        // Use fixed time at noon to avoid midnight crossing issues
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_minutes(60)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::hours(5)); // now at 1700.
        store.record("event");

        // first_seen is somewhere between midnight and 1600.
        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        let expected = ago(clock.now(), 0, 8, 00);
        eprintln!("Expected at {}, {expected:?} ago", clock.now() - expected);
        eprintln!(
            "Actual   at {}, {:?} ago",
            clock.now() - first.unwrap(),
            first.unwrap()
        );
        // (Duration::days(1) + Duration::hours(1)) / 2
        assert_eq!(first, Some(expected));

        // last_seen should return 0 (most recent)
        assert!(last.is_some());
        assert!(last.unwrap() == Duration::minutes(0));
    }

    fn ago(now: DateTime<Utc>, days_ago: i64, hours: u32, minutes: u32) -> Duration {
        use chrono::{TimeZone, Utc};
        let then = Utc
            .with_ymd_and_hms(now.year(), now.month(), now.day(), hours, minutes, 0)
            .unwrap()
            - Duration::days(days_ago);
        now - then
    }

    #[test]
    fn test_first_seen_returns_oldest_event_disjoint_muilti_buckets_under() {
        use chrono::{TimeZone, Utc};
        // Use fixed time at noon to avoid midnight crossing issues
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(36)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::hours(25));
        store.record("event");

        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        assert_eq!(first, Some(Duration::hours(25) + Duration::minutes(30)));

        // last_seen should return 0 (most recent)
        assert!(last.is_some());
        assert!(last.unwrap() == Duration::minutes(0));
    }

    #[test]
    fn test_first_seen_returns_oldest_event_disjoint_muilti_buckets_over() {
        use chrono::{TimeZone, Utc};
        // Use fixed time at 1400 to avoid midnight crossing issues
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 10, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(36)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::hours(37)); // now is 10 + 37 = 47 = 23h.
        store.record("event");

        // Query time is 11pm
        // first_seen is somewhere between midnight and 11am
        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        // When query time is BEFORE midnight, so first at between end of the 36th hour bucket
        // and the end of 2nd day bucket.
        let expected = ago(clock.now(), 1, 5, 30);
        eprintln!("Expected at {}, {expected:?} ago", clock.now() - expected);
        eprintln!(
            "Actual   at {}, {:?} ago",
            clock.now() - first.unwrap(),
            first.unwrap()
        );
        assert_eq!(first, Some(expected));

        // last_seen should return 0 (most recent)
        assert_eq!(last, Some(Duration::minutes(0)));

        clock.advance(Duration::hours(2)); // 23h + 2h = 1am
        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();
        // When query time is AFTER midnight, so first at between end of the 36th hour bucket
        // and the end of 3rd day bucket.
        let expected = ago(clock.now(), 2, 6, 30);
        eprintln!("Expected at {}, {expected:?} ago", clock.now() - expected);
        eprintln!(
            "Actual   at {}, {:?} ago",
            clock.now() - first.unwrap(),
            first.unwrap()
        );
        assert_eq!(first, Some(expected));
        assert_eq!(last, Some(Duration::hours(2) + Duration::minutes(30)));
    }

    #[test]
    fn test_first_seen_with_no_events() {
        let store = EventStore::new();
        let first = store.query("nonexistent").first_seen();
        assert_eq!(first, None);
    }

    #[test]
    fn test_first_seen_in_specific_time_unit() {
        let clock = TestClock::build_for_testing();
        let store = EventStore::builder()
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        // Record first event
        store.record("event");
        // Advance clock so first event is now 5 hours old
        clock.advance(Duration::hours(5));
        // Record second event to force rotation
        store.record("event");

        let first_hours = store.query("event").first_seen_in(TimeUnit::Hours);

        // Should see the oldest event (5 hours ago)
        assert_eq!(first_hours, Some(Duration::hours(5)));
    }

    #[test]
    fn test_first_seen_with_single_event_touching_intervals() {
        let clock = TestClock::build_for_testing();
        let store = EventStore::builder()
            .with_clock(Arc::new(clock.clone()))
            .track_hours(24)
            .track_minutes(60)
            .build()
            .unwrap();

        store.record("event");

        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        // Both should be very close to 0 (current time)
        assert!(first.is_some());
        assert!(last.is_some());
        eprintln!("first = {:?}", first.unwrap());
        eprintln!("last = {:?}", last.unwrap());
        assert!(
            first.unwrap() < Duration::hours(1),
            "Expected first < 1 hour, got {:?}",
            first.unwrap()
        );
        assert!(last.unwrap() < Duration::hours(1));
    }

    #[test]
    fn test_first_seen_with_single_event_disjoint_intervals() {
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .with_clock(Arc::new(clock.clone()))
            .track_years(2)
            // 1 mo ~ 28 days, but 12 * 28 < 365. Disjoint!
            .track_months(12)
            .track_days(28)
            .track_hours(24)
            .build()
            .unwrap();

        store.record("event");

        let first = store.query("event").first_seen();
        let last = store.query("event").last_seen();

        // Event just happened at exactly 12:00 PM, query at 12:00 PM
        // Bucket 0 has elapsed time of 0, so estimate is Duration::zero()
        assert!(first.is_some());
        assert!(last.is_some());

        // Both should be very close to 0 (current time) since event just happened
        assert_eq!(first, Some(Duration::zero()));
        assert_eq!(last, Some(Duration::zero()));
    }

    #[test]
    #[cfg(not(feature = "calendar"))]
    fn test_first_seen_across_multiple_time_units() {
        let clock = TestClock::build_for_testing();
        let store = EventStore::builder()
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        // Record an event
        store.record("event");

        // Advance time by 10 days
        clock.advance(Duration::days(10));
        // Record another event to force rotation
        store.record("event");

        let first = store.query("event").first_seen();
        let expected = ago(clock.now(), 11, 12, 00);
        eprintln!("Expected at {}, {expected:?} ago", clock.now() - expected);
        eprintln!(
            "Actual   at {}, {:?} ago",
            clock.now() - first.unwrap(),
            first.unwrap()
        );
        // Should find the oldest event (10 days ago)
        assert_eq!(first, Some(expected));
    }

    #[test]
    fn test_range_query_first_seen() {
        let clock = TestClock::build_for_testing();
        let store = EventStore::builder()
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::hours(5));
        store.record("event");

        // RangeQuery first_seen returns bucket index, not Duration
        let first_bucket = store.query("event").last_hours(24).first_seen();

        // Should return the oldest bucket index (5 hours ago)
        assert_eq!(first_bucket, Some(5));
    }

    #[test]
    fn test_first_seen_consistency_with_last_seen() {
        let clock = TestClock::build_for_testing();
        let store = EventStore::builder()
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event"); // First event
        clock.advance(Duration::hours(10));
        store.record("event"); // Last event

        let first_seen = store.query("event").first_seen();
        let last_seen = store.query("event").last_seen();

        // first_seen should be larger (further back in time)
        assert!(first_seen.is_some());
        assert!(last_seen.is_some());
        assert!(first_seen.unwrap() > last_seen.unwrap());
    }

    #[test]
    fn test_ever_into_buckets_does_not_hang() {
        // This test verifies that .ever().into_buckets() doesn't hang by iterating
        // 0..usize::MAX. It should resolve to the actual bucket count.
        let store = EventStore::new();
        store.record_count("event", 100);

        // This should complete quickly, not hang for 60+ seconds
        let buckets = store.query("event").ever().into_buckets();

        // Should have a reasonable number of buckets (the longest time unit's bucket count)
        // Default config has Years as longest with some reasonable bucket count
        assert!(!buckets.is_empty());
        assert!(buckets.len() < 1000); // Sanity check - should be way less than usize::MAX
    }

    #[test]
    fn test_last_seen_returns_recent_event_touching_intervals() {
        use chrono::{TimeZone, Utc};
        // Touching intervals: 60 minutes + 24 hours (no gaps)
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(60)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        // Record old event
        store.record("event");
        // Advance 10 minutes, record recent event
        clock.advance(Duration::minutes(10));
        store.record("event");

        let last = store.query("event").last_seen();

        // Should find it in minutes bucket with good precision
        // Event is in minute bucket 0, elapsed ~0, so estimate ~Duration::zero()
        assert!(last.is_some());
        assert!(
            last.unwrap() < Duration::minutes(1),
            "Expected last < 1 minute, got {:?}",
            last.unwrap()
        );
    }

    #[test]
    fn test_last_seen_returns_recent_event_overlapping_intervals() {
        use chrono::{TimeZone, Utc};
        // Overlapping intervals: 1440 minutes (24 hours) + 24 hours
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(60 * 24)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        clock.advance(Duration::minutes(10));
        store.record("event");

        let last = store.query("event").last_seen();

        // Should find it in minutes bucket 0 with good precision
        assert!(last.is_some());
        assert!(
            last.unwrap() < Duration::minutes(1),
            "Expected last < 1 minute, got {:?}",
            last.unwrap()
        );
    }

    #[test]
    fn test_last_seen_gap_event_disjoint_intervals() {
        use chrono::{TimeZone, Utc};
        // Disjoint intervals: 45 minutes + 24 hours (gap from 45-60 minutes)
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(45)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        // Advance 50 minutes - this puts the event in the GAP
        // Minutes only cover last 45 minutes, so event not in minutes
        // But it IS in hour bucket 0
        clock.advance(Duration::minutes(50));
        // Don't record another event! We want to query the gap event

        let last = store.query("event").last_seen();

        // With gap detection: should detect gap and return ~52.5 minutes
        // (midpoint between 45 minutes ago and 60 minutes ago)
        // Gap is [45, 60), so midpoint is 52.5 minutes
        let expected = Duration::minutes(52) + Duration::seconds(30);
        assert_eq!(
            last,
            Some(expected),
            "Gap event should be estimated at gap midpoint"
        );
    }

    #[test]
    fn test_last_seen_recent_event_in_smallest_bucket() {
        use chrono::{TimeZone, Utc};
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(60)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");

        let last = store.query("event").last_seen();

        // Event just happened, should be Duration::zero()
        assert_eq!(last, Some(Duration::zero()));
    }

    #[test]
    fn test_last_seen_event_in_gap_multiple_intervals() {
        use chrono::{TimeZone, Utc};
        // Setup: 30 minutes + 24 hours (gap from 30-60 minutes)
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_days(7)
            .track_hours(24)
            .track_minutes(30)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        // Advance 40 minutes - event is in the gap (30-60 minutes)
        clock.advance(Duration::minutes(40));
        // Don't record another event! We want to query the gap event

        let last = store.query("event").last_seen();

        // Gap is [30, 60), so midpoint is 45 minutes
        let expected = Duration::minutes(45);
        assert_eq!(
            last,
            Some(expected),
            "Gap event should be estimated at gap midpoint"
        );
    }

    #[test]
    fn test_last_seen_with_bucket_midway_ago() {
        use chrono::{TimeZone, Utc};
        let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
        let clock = TestClock::build_for_testing_at(fixed_time);
        let store = EventStore::builder()
            .track_hours(24)
            .with_clock(Arc::new(clock.clone()))
            .build()
            .unwrap();

        store.record("event");
        // Advance 30 minutes within the current hour
        clock.advance(Duration::minutes(30));

        let last = store.query("event").last_seen();

        // With bucket_midway_ago, should estimate ~15 minutes ago
        // (midpoint of elapsed 30 minutes in current hour bucket)
        assert!(last.is_some());
        let duration = last.unwrap();

        // Should be around 15 minutes (half of 30 minutes elapsed)
        assert!(
            duration >= Duration::minutes(14) && duration <= Duration::minutes(16),
            "Expected ~15 minutes, got {:?}",
            duration
        );
    }
}