aprender-present-terminal 0.31.2

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

/// Exponential Moving Average tracker for O(1) smoothing (trueno-viz pattern)
///
/// Provides real-time smoothed values without storing history.
/// Commonly used for FPS counters, load averages, and trend detection.
#[derive(Debug, Clone)]
pub struct EmaTracker {
    /// Current smoothed value
    value: f64,
    /// Smoothing factor (0.0-1.0, higher = more responsive)
    alpha: f64,
    /// Whether we've received the first sample
    initialized: bool,
}

impl Default for EmaTracker {
    fn default() -> Self {
        Self::new(0.1) // Default 10% weight for new samples
    }
}

impl EmaTracker {
    /// Create a new EMA tracker with given smoothing factor
    ///
    /// Alpha should be between 0.0 and 1.0:
    /// - Higher alpha (e.g., 0.5) = more responsive, less smooth
    /// - Lower alpha (e.g., 0.05) = less responsive, more smooth
    #[must_use]
    pub fn new(alpha: f64) -> Self {
        Self {
            value: 0.0,
            alpha: alpha.clamp(0.0, 1.0),
            initialized: false,
        }
    }

    /// Create tracker optimized for FPS counting (fast response)
    #[must_use]
    pub fn for_fps() -> Self {
        Self::new(0.3)
    }

    /// Create tracker optimized for load average (slow response)
    #[must_use]
    pub fn for_load() -> Self {
        Self::new(0.05)
    }

    /// Update with a new sample (O(1))
    pub fn update(&mut self, sample: f64) {
        if self.initialized {
            self.value = self.alpha * sample + (1.0 - self.alpha) * self.value;
        } else {
            self.value = sample;
            self.initialized = true;
        }
    }

    /// Get current smoothed value (O(1))
    #[must_use]
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Check if tracker has been initialized
    #[must_use]
    pub fn is_initialized(&self) -> bool {
        self.initialized
    }

    /// Get the alpha (smoothing factor)
    #[must_use]
    pub fn alpha(&self) -> f64 {
        self.alpha
    }

    /// Reset tracker to uninitialized state
    pub fn reset(&mut self) {
        self.value = 0.0;
        self.initialized = false;
    }

    /// Set a new alpha value
    pub fn set_alpha(&mut self, alpha: f64) {
        self.alpha = alpha.clamp(0.0, 1.0);
    }
}

// =============================================================================
// RATE LIMITER (trueno-viz O(1) throttling pattern)
// =============================================================================

/// Token bucket rate limiter for O(1) throttling (trueno-viz pattern)
///
/// Used to limit update frequency without blocking.
#[derive(Debug, Clone)]
pub struct RateLimiter {
    /// Last allowed time in microseconds
    last_allowed_us: u64,
    /// Minimum interval between allows in microseconds
    interval_us: u64,
}

impl Default for RateLimiter {
    fn default() -> Self {
        Self::new_hz(60) // Default 60 Hz
    }
}

impl RateLimiter {
    /// Create rate limiter with interval in microseconds
    #[must_use]
    pub fn new(interval_us: u64) -> Self {
        Self {
            last_allowed_us: 0,
            interval_us,
        }
    }

    /// Create rate limiter for given frequency (Hz)
    #[must_use]
    pub fn new_hz(hz: u32) -> Self {
        let interval_us = if hz == 0 {
            1_000_000
        } else {
            1_000_000 / hz as u64
        };
        Self::new(interval_us)
    }

    /// Create rate limiter for given millisecond interval
    #[must_use]
    pub fn new_ms(ms: u64) -> Self {
        Self::new(ms * 1000)
    }

    /// Check if action is allowed now (O(1))
    ///
    /// Returns true and updates timestamp if allowed, false otherwise.
    pub fn check(&mut self) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        if now >= self.last_allowed_us + self.interval_us {
            self.last_allowed_us = now;
            true
        } else {
            false
        }
    }

    /// Check without updating (peek)
    #[must_use]
    pub fn would_allow(&self) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        now >= self.last_allowed_us + self.interval_us
    }

    /// Get interval in microseconds
    #[must_use]
    pub fn interval_us(&self) -> u64 {
        self.interval_us
    }

    /// Get interval in Hz
    #[must_use]
    pub fn hz(&self) -> f64 {
        if self.interval_us == 0 {
            0.0
        } else {
            1_000_000.0 / self.interval_us as f64
        }
    }

    /// Reset the limiter
    pub fn reset(&mut self) {
        self.last_allowed_us = 0;
    }
}

// =============================================================================
// THRESHOLD DETECTOR (trueno-viz O(1) level detection pattern)
// =============================================================================

/// Threshold-based level detector for O(1) state transitions (trueno-viz pattern)
///
/// Provides hysteresis to prevent rapid toggling at threshold boundaries.
/// Common use: CPU/memory warning levels, alert thresholds.
#[derive(Debug, Clone)]
pub struct ThresholdDetector {
    /// Low threshold (transition from High to Low when below this)
    low: f64,
    /// High threshold (transition from Low to High when above this)
    high: f64,
    /// Current state (true = high/alert, false = low/normal)
    is_high: bool,
}

impl ThresholdDetector {
    /// Create a new threshold detector with hysteresis
    ///
    /// # Arguments
    /// * `low` - Threshold to transition to normal state
    /// * `high` - Threshold to transition to alert state
    ///
    /// Hysteresis: low < high prevents rapid toggling
    #[must_use]
    pub fn new(low: f64, high: f64) -> Self {
        Self {
            low,
            high: high.max(low), // Ensure high >= low
            is_high: false,
        }
    }

    /// Create detector for percentage thresholds (0-100)
    #[must_use]
    pub fn percent(low: f64, high: f64) -> Self {
        Self::new(low.clamp(0.0, 100.0), high.clamp(0.0, 100.0))
    }

    /// Create detector for CPU/memory warnings (70/90)
    #[must_use]
    pub fn for_resource() -> Self {
        Self::new(70.0, 90.0)
    }

    /// Create detector for temperature warnings (60/80)
    #[must_use]
    pub fn for_temperature() -> Self {
        Self::new(60.0, 80.0)
    }

    /// Update with new value and return whether state changed (O(1))
    pub fn update(&mut self, value: f64) -> bool {
        let was_high = self.is_high;

        if self.is_high && value < self.low {
            self.is_high = false;
        } else if !self.is_high && value > self.high {
            self.is_high = true;
        }

        was_high != self.is_high
    }

    /// Check if currently in high/alert state
    #[must_use]
    pub fn is_high(&self) -> bool {
        self.is_high
    }

    /// Check if currently in low/normal state
    #[must_use]
    pub fn is_low(&self) -> bool {
        !self.is_high
    }

    /// Get the low threshold
    #[must_use]
    pub fn low_threshold(&self) -> f64 {
        self.low
    }

    /// Get the high threshold
    #[must_use]
    pub fn high_threshold(&self) -> f64 {
        self.high
    }

    /// Reset to low/normal state
    pub fn reset(&mut self) {
        self.is_high = false;
    }

    /// Force to high/alert state
    pub fn set_high(&mut self) {
        self.is_high = true;
    }
}

// =============================================================================
// SAMPLE COUNTER (trueno-viz O(1) counting pattern)
// =============================================================================

/// Sample counter with windowed rate calculation (trueno-viz pattern)
///
/// Tracks count and provides rate per second calculation.
#[derive(Debug, Clone)]
pub struct SampleCounter {
    /// Total count
    count: u64,
    /// Count at last rate calculation
    last_count: u64,
    /// Time of last rate calculation in microseconds
    last_time_us: u64,
    /// Calculated rate (samples per second)
    rate: f64,
}

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

impl SampleCounter {
    /// Create a new counter
    #[must_use]
    pub fn new() -> Self {
        Self {
            count: 0,
            last_count: 0,
            last_time_us: 0,
            rate: 0.0,
        }
    }

    /// Increment count by 1 (O(1))
    pub fn increment(&mut self) {
        self.count += 1;
    }

    /// Increment count by n (O(1))
    pub fn add(&mut self, n: u64) {
        self.count += n;
    }

    /// Get current count
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Calculate and get rate (samples per second)
    ///
    /// Should be called periodically (e.g., once per second)
    pub fn calculate_rate(&mut self) -> f64 {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        if self.last_time_us > 0 {
            let elapsed_us = now.saturating_sub(self.last_time_us);
            if elapsed_us > 0 {
                let delta = self.count.saturating_sub(self.last_count);
                self.rate = (delta as f64 * 1_000_000.0) / elapsed_us as f64;
            }
        }

        self.last_count = self.count;
        self.last_time_us = now;
        self.rate
    }

    /// Get last calculated rate without recalculating
    #[must_use]
    pub fn rate(&self) -> f64 {
        self.rate
    }

    /// Reset counter
    pub fn reset(&mut self) {
        self.count = 0;
        self.last_count = 0;
        self.last_time_us = 0;
        self.rate = 0.0;
    }
}

// =============================================================================
// BUDGET TRACKER (trueno-viz O(1) budget monitoring pattern)
// =============================================================================

/// Budget tracker for monitoring time/resource consumption (trueno-viz pattern)
///
/// Tracks usage against a budget and calculates utilization percentage.
#[derive(Debug, Clone)]
pub struct BudgetTracker {
    /// Budget limit
    budget: f64,
    /// Current usage
    usage: f64,
    /// Peak usage
    peak: f64,
}

impl BudgetTracker {
    /// Create a new budget tracker
    #[must_use]
    pub fn new(budget: f64) -> Self {
        Self {
            budget: budget.max(0.0),
            usage: 0.0,
            peak: 0.0,
        }
    }

    /// Create for 16ms render budget (60fps)
    #[must_use]
    pub fn for_render() -> Self {
        contract_pre_render!();
        Self::new(16_000.0) // 16ms in microseconds
    }

    /// Create for 1ms compute budget
    #[must_use]
    pub fn for_compute() -> Self {
        Self::new(1_000.0) // 1ms in microseconds
    }

    /// Record usage (O(1))
    pub fn record(&mut self, usage: f64) {
        self.usage = usage;
        self.peak = self.peak.max(usage);
    }

    /// Get current usage
    #[must_use]
    pub fn usage(&self) -> f64 {
        self.usage
    }

    /// Get peak usage
    #[must_use]
    pub fn peak(&self) -> f64 {
        self.peak
    }

    /// Get budget
    #[must_use]
    pub fn budget(&self) -> f64 {
        self.budget
    }

    /// Get utilization percentage (O(1))
    #[must_use]
    pub fn utilization(&self) -> f64 {
        if self.budget <= 0.0 {
            0.0
        } else {
            (self.usage / self.budget) * 100.0
        }
    }

    /// Get peak utilization percentage (O(1))
    #[must_use]
    pub fn peak_utilization(&self) -> f64 {
        if self.budget <= 0.0 {
            0.0
        } else {
            (self.peak / self.budget) * 100.0
        }
    }

    /// Check if over budget
    #[must_use]
    pub fn is_over_budget(&self) -> bool {
        self.usage > self.budget
    }

    /// Get remaining budget
    #[must_use]
    pub fn remaining(&self) -> f64 {
        (self.budget - self.usage).max(0.0)
    }

    /// Reset usage and peak
    pub fn reset(&mut self) {
        self.usage = 0.0;
        self.peak = 0.0;
    }

    /// Set new budget
    pub fn set_budget(&mut self, budget: f64) {
        self.budget = budget.max(0.0);
    }
}

// =============================================================================
// MIN/MAX TRACKER (trueno-viz O(1) extrema tracking pattern)
// =============================================================================

/// Min/Max value tracker with timestamps (trueno-viz pattern)
///
/// Tracks minimum and maximum values along with when they occurred.
/// Useful for monitoring extreme values in metrics over time.
#[derive(Debug, Clone)]
pub struct MinMaxTracker {
    /// Minimum value seen
    min: f64,
    /// Maximum value seen
    max: f64,
    /// Time of minimum (microseconds since epoch)
    min_time_us: u64,
    /// Time of maximum (microseconds since epoch)
    max_time_us: u64,
    /// Sample count
    count: u64,
}

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

impl MinMaxTracker {
    /// Create a new min/max tracker
    #[must_use]
    pub fn new() -> Self {
        Self {
            min: f64::MAX,
            max: f64::MIN,
            min_time_us: 0,
            max_time_us: 0,
            count: 0,
        }
    }

    /// Record a value (O(1))
    pub fn record(&mut self, value: f64) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        if value < self.min {
            self.min = value;
            self.min_time_us = now;
        }
        if value > self.max {
            self.max = value;
            self.max_time_us = now;
        }
        self.count += 1;
    }

    /// Get minimum value (O(1))
    #[must_use]
    pub fn min(&self) -> Option<f64> {
        if self.count > 0 {
            Some(self.min)
        } else {
            None
        }
    }

    /// Get maximum value (O(1))
    #[must_use]
    pub fn max(&self) -> Option<f64> {
        if self.count > 0 {
            Some(self.max)
        } else {
            None
        }
    }

    /// Get range (max - min) (O(1))
    #[must_use]
    pub fn range(&self) -> Option<f64> {
        if self.count > 0 {
            Some(self.max - self.min)
        } else {
            None
        }
    }

    /// Get sample count
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Get time since minimum in microseconds
    #[must_use]
    pub fn time_since_min_us(&self) -> u64 {
        if self.min_time_us == 0 {
            return 0;
        }
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;
        now.saturating_sub(self.min_time_us)
    }

    /// Get time since maximum in microseconds
    #[must_use]
    pub fn time_since_max_us(&self) -> u64 {
        if self.max_time_us == 0 {
            return 0;
        }
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;
        now.saturating_sub(self.max_time_us)
    }

    /// Reset tracker
    pub fn reset(&mut self) {
        self.min = f64::MAX;
        self.max = f64::MIN;
        self.min_time_us = 0;
        self.max_time_us = 0;
        self.count = 0;
    }
}

// =============================================================================
// MOVING WINDOW (trueno-viz O(1) time-windowed aggregation pattern)
// =============================================================================

/// Time-windowed aggregation tracker (trueno-viz pattern)
///
/// Tracks sum/count over a sliding time window for rate calculations.
/// Window expiration is O(1) using bucket rotation.
#[derive(Debug, Clone)]
pub struct MovingWindow {
    /// Current bucket sum
    current_sum: f64,
    /// Current bucket count
    current_count: u64,
    /// Previous bucket sum
    prev_sum: f64,
    /// Previous bucket count
    prev_count: u64,
    /// Window duration in microseconds
    window_us: u64,
    /// Current bucket start time
    bucket_start_us: u64,
}

impl MovingWindow {
    /// Create a new moving window
    #[must_use]
    pub fn new(window_ms: u64) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        Self {
            current_sum: 0.0,
            current_count: 0,
            prev_sum: 0.0,
            prev_count: 0,
            window_us: window_ms * 1000,
            bucket_start_us: now,
        }
    }

    /// Create 1-second window
    #[must_use]
    pub fn one_second() -> Self {
        Self::new(1000)
    }

    /// Create 1-minute window
    #[must_use]
    pub fn one_minute() -> Self {
        Self::new(60_000)
    }

    /// Record a value (O(1) with potential bucket rotation)
    pub fn record(&mut self, value: f64) {
        self.maybe_rotate();
        self.current_sum += value;
        self.current_count += 1;
    }

    /// Increment count by 1 (O(1))
    pub fn increment(&mut self) {
        self.record(1.0);
    }

    /// Check and rotate buckets if needed (O(1))
    fn maybe_rotate(&mut self) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        let elapsed = now.saturating_sub(self.bucket_start_us);

        if elapsed >= self.window_us {
            // Rotate: current becomes previous
            self.prev_sum = self.current_sum;
            self.prev_count = self.current_count;
            self.current_sum = 0.0;
            self.current_count = 0;
            self.bucket_start_us = now;
        }
    }

    /// Get sum over window (O(1))
    #[must_use]
    pub fn sum(&mut self) -> f64 {
        self.maybe_rotate();
        self.current_sum + self.prev_sum
    }

    /// Get count over window (O(1))
    #[must_use]
    pub fn count(&mut self) -> u64 {
        self.maybe_rotate();
        self.current_count + self.prev_count
    }

    /// Get rate per second (O(1))
    #[must_use]
    pub fn rate_per_second(&mut self) -> f64 {
        self.maybe_rotate();
        let total = self.current_sum + self.prev_sum;
        let window_secs = (self.window_us as f64) / 1_000_000.0;
        if window_secs > 0.0 {
            total / window_secs
        } else {
            0.0
        }
    }

    /// Get count rate per second (O(1))
    #[must_use]
    pub fn count_rate(&mut self) -> f64 {
        self.maybe_rotate();
        let total = self.current_count + self.prev_count;
        let window_secs = (self.window_us as f64) / 1_000_000.0;
        if window_secs > 0.0 {
            total as f64 / window_secs
        } else {
            0.0
        }
    }

    /// Reset window
    pub fn reset(&mut self) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        self.current_sum = 0.0;
        self.current_count = 0;
        self.prev_sum = 0.0;
        self.prev_count = 0;
        self.bucket_start_us = now;
    }
}

// =============================================================================
// PERCENTILE TRACKER (trueno-viz O(1) approximate percentile pattern)
// =============================================================================

/// Approximate percentile tracker using fixed buckets (trueno-viz pattern)
///
/// Provides O(1) approximate percentiles using histogram-based estimation.
/// Buckets: [0-1, 1-5, 5-10, 10-25, 25-50, 50-100, 100-250, 250-500, 500-1000, 1000+] ms
#[derive(Debug, Clone)]
pub struct PercentileTracker {
    /// Bucket counts
    buckets: [u64; 10],
    /// Total count
    count: u64,
    /// Bucket boundaries in microseconds
    boundaries: [u64; 10],
}

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

impl PercentileTracker {
    /// Create a new percentile tracker with default latency buckets
    #[must_use]
    pub fn new() -> Self {
        Self {
            buckets: [0; 10],
            count: 0,
            // Boundaries in microseconds: 1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1000ms, infinity
            boundaries: [
                1_000,     // 0-1ms
                5_000,     // 1-5ms
                10_000,    // 5-10ms
                25_000,    // 10-25ms
                50_000,    // 25-50ms
                100_000,   // 50-100ms
                250_000,   // 100-250ms
                500_000,   // 250-500ms
                1_000_000, // 500-1000ms
                u64::MAX,  // 1000ms+
            ],
        }
    }

    /// Create with custom bucket boundaries (in microseconds)
    #[must_use]
    pub fn with_boundaries(boundaries: [u64; 10]) -> Self {
        Self {
            buckets: [0; 10],
            count: 0,
            boundaries,
        }
    }

    /// Record a value in microseconds (O(1))
    pub fn record_us(&mut self, value_us: u64) {
        for (i, &boundary) in self.boundaries.iter().enumerate() {
            if value_us < boundary {
                self.buckets[i] += 1;
                self.count += 1;
                return;
            }
        }
        // Shouldn't reach here due to u64::MAX boundary
        self.buckets[9] += 1;
        self.count += 1;
    }

    /// Record a value in milliseconds (O(1))
    pub fn record_ms(&mut self, value_ms: f64) {
        self.record_us((value_ms * 1000.0) as u64);
    }

    /// Get approximate percentile value in microseconds (O(1))
    #[must_use]
    pub fn percentile_us(&self, pct: f64) -> u64 {
        if self.count == 0 {
            return 0;
        }

        let target = ((pct / 100.0) * self.count as f64) as u64;
        let mut cumulative = 0u64;

        for (i, &bucket_count) in self.buckets.iter().enumerate() {
            cumulative += bucket_count;
            if cumulative >= target {
                // Return midpoint of bucket
                let lower = if i == 0 { 0 } else { self.boundaries[i - 1] };
                let upper = self.boundaries[i];
                if upper == u64::MAX {
                    return lower + 500_000; // Estimate for last bucket
                }
                return (lower + upper) / 2;
            }
        }

        self.boundaries[8] // Return 1s as fallback
    }

    /// Get approximate percentile value in milliseconds (O(1))
    #[must_use]
    pub fn percentile_ms(&self, pct: f64) -> f64 {
        self.percentile_us(pct) as f64 / 1000.0
    }

    /// Get p50 (median) in milliseconds
    #[must_use]
    pub fn p50_ms(&self) -> f64 {
        self.percentile_ms(50.0)
    }

    /// Get p90 in milliseconds
    #[must_use]
    pub fn p90_ms(&self) -> f64 {
        self.percentile_ms(90.0)
    }

    /// Get p99 in milliseconds
    #[must_use]
    pub fn p99_ms(&self) -> f64 {
        self.percentile_ms(99.0)
    }

    /// Get total count
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Reset tracker
    pub fn reset(&mut self) {
        self.buckets = [0; 10];
        self.count = 0;
    }
}

// =============================================================================
// STATE TRACKER (trueno-viz O(1) state machine pattern)
// =============================================================================

/// State transition tracker with history (trueno-viz pattern)
///
/// Tracks state transitions and time spent in each state.
/// Useful for monitoring component lifecycle or connection states.
#[derive(Debug, Clone)]
pub struct StateTracker<const N: usize> {
    /// Current state index (0..N-1)
    current: usize,
    /// Time entered current state (microseconds since epoch)
    entered_us: u64,
    /// Total time spent in each state (microseconds)
    durations: [u64; N],
    /// Transition count for each state
    transitions: [u64; N],
}

impl<const N: usize> Default for StateTracker<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> StateTracker<N> {
    /// Create a new state tracker starting in state 0
    #[must_use]
    pub fn new() -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        let mut transitions = [0u64; N];
        if N > 0 {
            transitions[0] = 1; // Initial transition to state 0
        }

        Self {
            current: 0,
            entered_us: now,
            durations: [0u64; N],
            transitions,
        }
    }

    /// Transition to a new state (O(1))
    pub fn transition(&mut self, new_state: usize) {
        if new_state >= N {
            return; // Invalid state
        }

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        // Record time in previous state
        let elapsed = now.saturating_sub(self.entered_us);
        self.durations[self.current] += elapsed;

        // Transition to new state
        self.current = new_state;
        self.entered_us = now;
        self.transitions[new_state] += 1;
    }

    /// Get current state (O(1))
    #[must_use]
    pub fn current(&self) -> usize {
        self.current
    }

    /// Get time in current state in microseconds (O(1))
    #[must_use]
    pub fn time_in_current_us(&self) -> u64 {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;
        now.saturating_sub(self.entered_us)
    }

    /// Get total time in state in microseconds (O(1))
    #[must_use]
    pub fn total_time_in_state_us(&self, state: usize) -> u64 {
        if state >= N {
            return 0;
        }
        if state == self.current {
            self.durations[state] + self.time_in_current_us()
        } else {
            self.durations[state]
        }
    }

    /// Get transition count for state (O(1))
    #[must_use]
    pub fn transition_count(&self, state: usize) -> u64 {
        if state >= N {
            0
        } else {
            self.transitions[state]
        }
    }

    /// Get total transitions (O(N))
    #[must_use]
    pub fn total_transitions(&self) -> u64 {
        self.transitions.iter().sum()
    }

    /// Reset tracker
    pub fn reset(&mut self) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        self.current = 0;
        self.entered_us = now;
        self.durations = [0u64; N];
        self.transitions = [0u64; N];
        if N > 0 {
            self.transitions[0] = 1;
        }
    }
}

// =============================================================================
// CHANGE DETECTOR (trueno-viz O(1) significant change detection)
// =============================================================================

/// Significant change detector (trueno-viz pattern)
///
/// Detects when a value has changed significantly from a baseline.
/// Uses both absolute and relative thresholds.
#[derive(Debug, Clone)]
pub struct ChangeDetector {
    /// Baseline value
    baseline: f64,
    /// Absolute change threshold
    abs_threshold: f64,
    /// Relative change threshold (percentage)
    rel_threshold: f64,
    /// Last reported value
    last_value: f64,
    /// Number of changes detected
    change_count: u64,
}

impl Default for ChangeDetector {
    fn default() -> Self {
        Self::new(0.0, 1.0, 5.0)
    }
}

impl ChangeDetector {
    /// Create a new change detector
    ///
    /// # Arguments
    /// * `baseline` - Initial baseline value
    /// * `abs_threshold` - Absolute change required to trigger
    /// * `rel_threshold` - Relative change (%) required to trigger
    #[must_use]
    pub fn new(baseline: f64, abs_threshold: f64, rel_threshold: f64) -> Self {
        Self {
            baseline,
            abs_threshold: abs_threshold.abs(),
            rel_threshold: rel_threshold.abs(),
            last_value: baseline,
            change_count: 0,
        }
    }

    /// Create for percentage monitoring (1% absolute, 5% relative)
    #[must_use]
    pub fn for_percentage() -> Self {
        Self::new(0.0, 1.0, 5.0)
    }

    /// Create for latency monitoring (1ms absolute, 10% relative)
    #[must_use]
    pub fn for_latency() -> Self {
        Self::new(0.0, 1000.0, 10.0)
    }

    /// Check if value has changed significantly (O(1))
    #[must_use]
    pub fn has_changed(&self, value: f64) -> bool {
        let abs_diff = (value - self.last_value).abs();

        // Check absolute threshold
        if abs_diff >= self.abs_threshold {
            return true;
        }

        // Check relative threshold
        if self.last_value.abs() > f64::EPSILON {
            let rel_diff = (abs_diff / self.last_value.abs()) * 100.0;
            if rel_diff >= self.rel_threshold {
                return true;
            }
        }

        false
    }

    /// Update with new value and return whether it changed significantly (O(1))
    pub fn update(&mut self, value: f64) -> bool {
        let changed = self.has_changed(value);
        if changed {
            self.change_count += 1;
        }
        self.last_value = value;
        changed
    }

    /// Update baseline to current value (O(1))
    pub fn update_baseline(&mut self) {
        self.baseline = self.last_value;
    }

    /// Set baseline to specific value (O(1))
    pub fn set_baseline(&mut self, baseline: f64) {
        self.baseline = baseline;
    }

    /// Get current baseline
    #[must_use]
    pub fn baseline(&self) -> f64 {
        self.baseline
    }

    /// Get last value
    #[must_use]
    pub fn last_value(&self) -> f64 {
        self.last_value
    }

    /// Get change count
    #[must_use]
    pub fn change_count(&self) -> u64 {
        self.change_count
    }

    /// Get change from baseline
    #[must_use]
    pub fn change_from_baseline(&self) -> f64 {
        self.last_value - self.baseline
    }

    /// Get relative change from baseline (percentage)
    #[must_use]
    pub fn relative_change(&self) -> f64 {
        if self.baseline.abs() > f64::EPSILON {
            ((self.last_value - self.baseline) / self.baseline.abs()) * 100.0
        } else {
            0.0
        }
    }

    /// Reset detector
    pub fn reset(&mut self) {
        self.last_value = self.baseline;
        self.change_count = 0;
    }
}

// =============================================================================
// ACCUMULATOR (trueno-viz O(1) overflow-safe accumulation)
// =============================================================================

/// Overflow-safe accumulator (trueno-viz pattern)
///
/// Accumulates values with automatic overflow detection and handling.
/// Useful for counters that may wrap (network bytes, disk I/O).
#[derive(Debug, Clone)]
pub struct Accumulator {
    /// Current accumulated value
    value: u64,
    /// Previous raw value (for delta calculation)
    prev_raw: u64,
    /// Whether we've seen the first value
    initialized: bool,
    /// Overflow count
    overflows: u64,
}

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

impl Accumulator {
    /// Create a new accumulator
    #[must_use]
    pub fn new() -> Self {
        Self {
            value: 0,
            prev_raw: 0,
            initialized: false,
            overflows: 0,
        }
    }

    /// Update with a raw counter value (O(1))
    ///
    /// Handles counter wraps/overflows automatically.
    pub fn update(&mut self, raw: u64) {
        if !self.initialized {
            self.prev_raw = raw;
            self.initialized = true;
            return;
        }

        // Calculate delta, handling overflow
        let delta = if raw >= self.prev_raw {
            raw - self.prev_raw
        } else {
            // Counter wrapped
            self.overflows += 1;
            // Assume wrap to 0 from max
            (u64::MAX - self.prev_raw) + raw + 1
        };

        self.value += delta;
        self.prev_raw = raw;
    }

    /// Add a delta value directly (O(1))
    pub fn add(&mut self, delta: u64) {
        self.value += delta;
        self.initialized = true;
    }

    /// Get accumulated value (O(1))
    #[must_use]
    pub fn value(&self) -> u64 {
        self.value
    }

    /// Get overflow count (O(1))
    #[must_use]
    pub fn overflows(&self) -> u64 {
        self.overflows
    }

    /// Check if initialized
    #[must_use]
    pub fn is_initialized(&self) -> bool {
        self.initialized
    }

    /// Get last raw value
    #[must_use]
    pub fn last_raw(&self) -> u64 {
        self.prev_raw
    }

    /// Reset accumulator
    pub fn reset(&mut self) {
        self.value = 0;
        self.prev_raw = 0;
        self.initialized = false;
        self.overflows = 0;
    }
}

// =============================================================================
// EVENT COUNTER (trueno-viz O(1) categorized event counting)
// =============================================================================

/// Categorized event counter (trueno-viz pattern)
///
/// Counts events by category with O(1) increment and lookup.
/// Useful for error categorization, request types, etc.
#[derive(Debug, Clone)]
pub struct EventCounter<const N: usize> {
    /// Counts per category
    counts: [u64; N],
    /// Total count
    total: u64,
}

impl<const N: usize> Default for EventCounter<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> EventCounter<N> {
    /// Create a new event counter
    #[must_use]
    pub fn new() -> Self {
        Self {
            counts: [0u64; N],
            total: 0,
        }
    }

    /// Increment category count (O(1))
    pub fn increment(&mut self, category: usize) {
        if category < N {
            self.counts[category] += 1;
            self.total += 1;
        }
    }

    /// Add to category count (O(1))
    pub fn add(&mut self, category: usize, count: u64) {
        if category < N {
            self.counts[category] += count;
            self.total += count;
        }
    }

    /// Get category count (O(1))
    #[must_use]
    pub fn count(&self, category: usize) -> u64 {
        if category < N {
            self.counts[category]
        } else {
            0
        }
    }

    /// Get total count (O(1))
    #[must_use]
    pub fn total(&self) -> u64 {
        self.total
    }

    /// Get category percentage (O(1))
    #[must_use]
    pub fn percentage(&self, category: usize) -> f64 {
        if self.total == 0 || category >= N {
            0.0
        } else {
            (self.counts[category] as f64 / self.total as f64) * 100.0
        }
    }

    /// Get dominant category (O(N))
    #[must_use]
    pub fn dominant(&self) -> Option<usize> {
        if self.total == 0 {
            return None;
        }
        self.counts
            .iter()
            .enumerate()
            .max_by_key(|(_, &count)| count)
            .map(|(idx, _)| idx)
    }

    /// Reset all counts
    pub fn reset(&mut self) {
        self.counts = [0u64; N];
        self.total = 0;
    }
}

// =============================================================================
// TREND DETECTOR (trueno-viz O(1) trend analysis pattern)
// =============================================================================

/// Trend detection using linear regression slope (trueno-viz pattern)
///
/// Detects upward/downward/flat trends using a sliding window approach.
/// Uses simplified slope calculation for O(1) updates.
#[derive(Debug, Clone)]
pub struct TrendDetector {
    /// Sum of values
    sum: f64,
    /// Sum of index * value (for slope)
    sum_xy: f64,
    /// Current index
    index: u64,
    /// Number of samples
    count: u64,
    /// Threshold for trend detection (slope magnitude)
    threshold: f64,
}

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

/// Trend direction
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Trend {
    /// Values increasing
    Up,
    /// Values decreasing
    Down,
    /// Values stable
    Flat,
    /// Not enough data
    Unknown,
}

impl TrendDetector {
    /// Create a new trend detector
    ///
    /// # Arguments
    /// * `threshold` - Minimum slope magnitude to detect trend
    #[must_use]
    pub fn new(threshold: f64) -> Self {
        Self {
            sum: 0.0,
            sum_xy: 0.0,
            index: 0,
            count: 0,
            threshold: threshold.abs(),
        }
    }

    /// Create for percentage changes (0.5% threshold)
    #[must_use]
    pub fn for_percentage() -> Self {
        Self::new(0.5)
    }

    /// Create for latency changes (1ms threshold)
    #[must_use]
    pub fn for_latency() -> Self {
        Self::new(1.0)
    }

    /// Update with a new value (O(1))
    pub fn update(&mut self, value: f64) {
        self.sum += value;
        self.sum_xy += (self.index as f64) * value;
        self.index += 1;
        self.count += 1;
    }

    /// Calculate slope (O(1))
    ///
    /// Uses least squares linear regression formula:
    /// slope = (n * Σxy - Σx * Σy) / (n * Σx² - (Σx)²)
    #[must_use]
    pub fn slope(&self) -> f64 {
        if self.count < 2 {
            return 0.0;
        }

        let n = self.count as f64;
        let sum_x = (self.count * (self.count - 1)) as f64 / 2.0; // Sum of 0..n-1
        let sum_x2 = (self.count * (self.count - 1) * (2 * self.count - 1)) as f64 / 6.0;

        // Linear regression denominator: n * Σx² - (Σx)²
        let sum_x_squared = sum_x.powi(2);
        let denominator = n * sum_x2 - sum_x_squared;
        if denominator.abs() < f64::EPSILON {
            return 0.0;
        }

        (n * self.sum_xy - sum_x * self.sum) / denominator
    }

    /// Get current trend (O(1))
    #[must_use]
    pub fn trend(&self) -> Trend {
        if self.count < 3 {
            return Trend::Unknown;
        }

        let slope = self.slope();
        if slope > self.threshold {
            Trend::Up
        } else if slope < -self.threshold {
            Trend::Down
        } else {
            Trend::Flat
        }
    }

    /// Check if trending up
    #[must_use]
    pub fn is_trending_up(&self) -> bool {
        self.trend() == Trend::Up
    }

    /// Check if trending down
    #[must_use]
    pub fn is_trending_down(&self) -> bool {
        self.trend() == Trend::Down
    }

    /// Get sample count
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Reset detector
    pub fn reset(&mut self) {
        self.sum = 0.0;
        self.sum_xy = 0.0;
        self.index = 0;
        self.count = 0;
    }
}

// =============================================================================
// ANOMALY DETECTOR (trueno-viz O(1) z-score anomaly detection)
// =============================================================================

/// Z-score based anomaly detector (trueno-viz pattern)
///
/// Detects anomalies using running mean/variance and z-score threshold.
/// Useful for alerting on unusual values.
#[derive(Debug, Clone)]
pub struct AnomalyDetector {
    /// Running mean
    mean: f64,
    /// Running M2 (sum of squared differences)
    m2: f64,
    /// Sample count
    count: u64,
    /// Z-score threshold for anomaly
    threshold: f64,
    /// Last value
    last_value: f64,
    /// Anomaly count
    anomaly_count: u64,
}

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

impl AnomalyDetector {
    /// Create a new anomaly detector
    ///
    /// # Arguments
    /// * `threshold` - Z-score threshold (typically 2.0-3.0)
    #[must_use]
    pub fn new(threshold: f64) -> Self {
        Self {
            mean: 0.0,
            m2: 0.0,
            count: 0,
            threshold: threshold.abs(),
            last_value: 0.0,
            anomaly_count: 0,
        }
    }

    /// Create with 2-sigma threshold (95% confidence)
    #[must_use]
    pub fn two_sigma() -> Self {
        Self::new(2.0)
    }

    /// Create with 3-sigma threshold (99.7% confidence)
    #[must_use]
    pub fn three_sigma() -> Self {
        Self::new(3.0)
    }

    /// Update with a new value and return whether it's an anomaly (O(1))
    ///
    /// Uses Welford's online algorithm for running variance.
    pub fn update(&mut self, value: f64) -> bool {
        self.last_value = value;
        self.count += 1;

        // First value can't be an anomaly
        if self.count == 1 {
            self.mean = value;
            return false;
        }

        // Calculate z-score before updating stats
        let is_anomaly = self.is_anomaly(value);
        if is_anomaly {
            self.anomaly_count += 1;
        }

        // Update running stats (Welford's algorithm)
        let delta = value - self.mean;
        self.mean += delta / self.count as f64;
        let delta2 = value - self.mean;
        self.m2 += delta * delta2;

        is_anomaly
    }

    /// Check if a value would be an anomaly (O(1))
    #[must_use]
    pub fn is_anomaly(&self, value: f64) -> bool {
        if self.count < 10 {
            return false; // Need enough samples
        }

        let z = self.z_score(value);
        z.abs() > self.threshold
    }

    /// Calculate z-score for a value (O(1))
    #[must_use]
    pub fn z_score(&self, value: f64) -> f64 {
        let std_dev = self.std_dev();
        if std_dev < f64::EPSILON {
            return 0.0;
        }
        (value - self.mean) / std_dev
    }

    /// Get running mean (O(1))
    #[must_use]
    pub fn mean(&self) -> f64 {
        self.mean
    }

    /// Get running variance (O(1))
    #[must_use]
    pub fn variance(&self) -> f64 {
        if self.count < 2 {
            0.0
        } else {
            self.m2 / (self.count - 1) as f64
        }
    }

    /// Get running standard deviation (O(1))
    #[must_use]
    pub fn std_dev(&self) -> f64 {
        self.variance().sqrt()
    }

    /// Get sample count
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Get anomaly count
    #[must_use]
    pub fn anomaly_count(&self) -> u64 {
        self.anomaly_count
    }

    /// Get anomaly rate (percentage)
    #[must_use]
    pub fn anomaly_rate(&self) -> f64 {
        if self.count == 0 {
            0.0
        } else {
            (self.anomaly_count as f64 / self.count as f64) * 100.0
        }
    }

    /// Get threshold
    #[must_use]
    pub fn threshold(&self) -> f64 {
        self.threshold
    }

    /// Reset detector
    pub fn reset(&mut self) {
        self.mean = 0.0;
        self.m2 = 0.0;
        self.count = 0;
        self.last_value = 0.0;
        self.anomaly_count = 0;
    }
}