ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
//! Predictive Maintenance Alerts
//!
//! Analyzes hardware metric trends to predict potential failures before they
//! occur. Uses linear regression, moving averages, and degradation rate
//! analysis to generate maintenance alerts.
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::predictive::{MaintenanceEngine, PredictionConfig};
//!
//! let mut engine = MaintenanceEngine::new(PredictionConfig::default());
//!
//! // Feed historical data
//! for temp in [65.0, 66.0, 67.5, 68.0, 70.0, 72.0, 74.0, 76.0] {
//!     engine.record_gpu_temp(0, temp);
//! }
//! engine.record_disk_health(0, 95.0); // 95% SMART health
//! engine.record_fan_rpm(0, 1200.0);
//!
//! // Get predictions
//! let report = engine.predict();
//! for alert in &report.alerts {
//!     println!("[{}] {}: {}", alert.urgency, alert.component, alert.message);
//!     if let Some(eta) = alert.eta_samples {
//!         println!("  Estimated samples until issue: {:.0}", eta);
//!     }
//! }
//! // Checks that could not run are not "no alerts".
//! for gap in &report.not_checked {
//!     println!("{gap}");
//! }
//! ```

use crate::anomaly::{sample_gap, verdict_for, CheckGap, NotChecked, Verdict};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Configuration for predictive maintenance analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictionConfig {
    /// Minimum data points for trend analysis
    pub min_data_points: usize,
    /// GPU temperature threshold for thermal alert (°C)
    pub gpu_thermal_limit: f64,
    /// Disk health warning threshold (%)
    pub disk_health_warning: f64,
    /// Fan RPM minimum before failure prediction
    pub fan_min_rpm: f64,
    /// Fan degradation rate threshold (RPM/hour decline)
    pub fan_degradation_rate: f64,
    /// Memory error rate threshold (errors/hour)
    pub memory_error_threshold: f64,
    /// GPU clock degradation threshold (MHz decline over window)
    pub clock_degradation_mhz: f64,
    /// Number of samples in sliding window
    pub window_size: usize,
}

impl Default for PredictionConfig {
    fn default() -> Self {
        Self {
            min_data_points: 10,
            gpu_thermal_limit: 95.0,
            disk_health_warning: 80.0,
            fan_min_rpm: 500.0,
            fan_degradation_rate: 50.0,
            memory_error_threshold: 1.0,
            clock_degradation_mhz: 100.0,
            window_size: 100,
        }
    }
}

/// Urgency level for maintenance alerts
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Urgency {
    /// Informational — no action needed yet
    Low,
    /// Plan maintenance within weeks
    Medium,
    /// Schedule maintenance within days
    High,
    /// Immediate attention required
    Critical,
}

impl std::fmt::Display for Urgency {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Low => write!(f, "LOW"),
            Self::Medium => write!(f, "MEDIUM"),
            Self::High => write!(f, "HIGH"),
            Self::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Fixed confidence for a disk SMART-health alert. A rule constant, not a probability.
const CONFIDENCE_DISK_HEALTH_THRESHOLD: f64 = 0.9;
/// Fixed confidence for a memory-error alert. A rule constant, not a probability.
const CONFIDENCE_MEMORY_ERROR_THRESHOLD: f64 = 0.8;

/// A predictive maintenance alert
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaintenanceAlert {
    /// Component that may need maintenance
    pub component: String,
    /// Type of issue predicted
    pub issue_type: IssueType,
    /// Urgency level
    pub urgency: Urgency,
    /// Human-readable message
    pub message: String,
    /// Estimated number of samples until the metric crosses its threshold, at the
    /// trend the window shows (None if it cannot be predicted). Samples, not
    /// hours: the engine is given samples and does not know their interval, so it
    /// cannot convert them to time without inventing one.
    pub eta_samples: Option<f64>,
    /// Current degradation rate
    pub degradation_rate: Option<f64>,
    /// Most recent sampled value the rule evaluated, in the metric's own unit.
    pub current_value: f64,
    /// Limit the rule compared against, in the same unit as `current_value`. The
    /// one exception is GPU clock degradation, where the comparison is made
    /// against the MHz decline over the window rather than the clock itself.
    pub threshold: f64,
    /// Recommended action
    pub action: String,
    /// Confidence, 0.0-1.0. Trend alerts (thermal, GPU clock, fan) carry the
    /// R-squared of their linear fit over the window, a statistic computed from
    /// the samples. Disk and memory alerts carry a fixed per-rule constant. Neither
    /// is the probability that the predicted failure happens.
    pub confidence: f64,
}

/// Type of predicted issue
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueType {
    /// Component approaching thermal limits
    ThermalDegradation,
    /// Storage device health declining
    DiskFailure,
    /// Fan speed declining (bearing wear)
    FanFailure,
    /// GPU clocks declining (chip degradation)
    GpuDegradation,
    /// Memory errors increasing
    MemoryFailure,
    /// Power supply degradation
    PowerDegradation,
    /// Capacitor aging (increasing voltage ripple)
    CapacitorAging,
}

impl std::fmt::Display for IssueType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ThermalDegradation => write!(f, "Thermal Degradation"),
            Self::DiskFailure => write!(f, "Disk Failure Risk"),
            Self::FanFailure => write!(f, "Fan Failure Risk"),
            Self::GpuDegradation => write!(f, "GPU Degradation"),
            Self::MemoryFailure => write!(f, "Memory Failure Risk"),
            Self::PowerDegradation => write!(f, "Power Degradation"),
            Self::CapacitorAging => write!(f, "Capacitor Aging"),
        }
    }
}

/// Result of one [`MaintenanceEngine::predict`] call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictionReport {
    /// Maintenance alerts raised, most urgent first.
    pub alerts: Vec<MaintenanceAlert>,
    /// Checks that could not run on the data held, with the reason for each.
    pub not_checked: Vec<NotChecked>,
}

impl PredictionReport {
    /// What this report says overall. An empty `alerts` list is not a verdict of
    /// health on its own; see [`crate::anomaly::AnomalyReport::verdict`].
    pub fn verdict(&self) -> Verdict {
        verdict_for(!self.alerts.is_empty(), &self.not_checked)
    }
}

/// Time-series data for a single metric
struct TimeSeries {
    values: Vec<f64>,
    max_size: usize,
}

impl TimeSeries {
    fn new(max_size: usize) -> Self {
        Self {
            values: Vec::with_capacity(max_size),
            max_size,
        }
    }

    fn push(&mut self, value: f64) {
        if self.values.len() >= self.max_size {
            self.values.remove(0);
        }
        self.values.push(value);
    }

    fn len(&self) -> usize {
        self.values.len()
    }

    fn last(&self) -> Option<f64> {
        self.values.last().copied()
    }

    fn mean(&self) -> f64 {
        if self.values.is_empty() {
            return 0.0;
        }
        self.values.iter().sum::<f64>() / self.values.len() as f64
    }

    /// Simple linear regression: returns (slope, intercept)
    fn linear_regression(&self) -> Option<(f64, f64)> {
        let n = self.values.len() as f64;
        if n < 3.0 {
            return None;
        }

        let x_mean = (n - 1.0) / 2.0;
        let y_mean = self.mean();

        let mut ss_xy = 0.0;
        let mut ss_xx = 0.0;

        for (i, y) in self.values.iter().enumerate() {
            let x = i as f64;
            ss_xy += (x - x_mean) * (y - y_mean);
            ss_xx += (x - x_mean) * (x - x_mean);
        }

        if ss_xx.abs() < 1e-10 {
            return None;
        }

        let slope = ss_xy / ss_xx;
        let intercept = y_mean - slope * x_mean;

        Some((slope, intercept))
    }

    /// Predict value at future index (from current last position)
    #[allow(dead_code)]
    fn predict_at(&self, steps_ahead: usize) -> Option<f64> {
        let (slope, intercept) = self.linear_regression()?;
        let future_x = (self.values.len() + steps_ahead - 1) as f64;
        Some(slope * future_x + intercept)
    }

    /// Estimate steps until value crosses threshold
    fn steps_until_threshold(&self, threshold: f64) -> Option<f64> {
        let (slope, intercept) = self.linear_regression()?;
        if slope.abs() < 1e-10 {
            return None;
        }
        let current_x = (self.values.len() - 1) as f64;
        let threshold_x = (threshold - intercept) / slope;
        let steps = threshold_x - current_x;
        if steps > 0.0 {
            Some(steps)
        } else {
            None
        }
    }

    /// R² coefficient of determination (goodness of fit)
    fn r_squared(&self) -> f64 {
        if self.values.len() < 3 {
            return 0.0;
        }
        let (slope, intercept) = match self.linear_regression() {
            Some(v) => v,
            None => return 0.0,
        };
        let y_mean = self.mean();
        let mut ss_res = 0.0;
        let mut ss_tot = 0.0;
        for (i, y) in self.values.iter().enumerate() {
            let predicted = slope * i as f64 + intercept;
            ss_res += (y - predicted).powi(2);
            ss_tot += (y - y_mean).powi(2);
        }
        if ss_tot.abs() < 1e-10 {
            return 0.0;
        }
        1.0 - (ss_res / ss_tot)
    }
}

/// Predictive maintenance engine
pub struct MaintenanceEngine {
    config: PredictionConfig,
    gpu_temps: HashMap<usize, TimeSeries>,
    gpu_clocks: HashMap<usize, TimeSeries>,
    disk_health: HashMap<usize, TimeSeries>,
    fan_rpms: HashMap<usize, TimeSeries>,
    memory_errors: TimeSeries,
}

impl MaintenanceEngine {
    /// Create a new maintenance engine
    pub fn new(config: PredictionConfig) -> Self {
        let ws = config.window_size;
        Self {
            config,
            gpu_temps: HashMap::new(),
            gpu_clocks: HashMap::new(),
            disk_health: HashMap::new(),
            fan_rpms: HashMap::new(),
            memory_errors: TimeSeries::new(ws),
        }
    }

    /// Record GPU temperature measurement
    pub fn record_gpu_temp(&mut self, gpu_idx: usize, celsius: f64) {
        self.gpu_temps
            .entry(gpu_idx)
            .or_insert_with(|| TimeSeries::new(self.config.window_size))
            .push(celsius);
    }

    /// Record GPU clock speed measurement
    pub fn record_gpu_clock(&mut self, gpu_idx: usize, mhz: f64) {
        self.gpu_clocks
            .entry(gpu_idx)
            .or_insert_with(|| TimeSeries::new(self.config.window_size))
            .push(mhz);
    }

    /// Record disk SMART health percentage
    pub fn record_disk_health(&mut self, disk_idx: usize, percent: f64) {
        self.disk_health
            .entry(disk_idx)
            .or_insert_with(|| TimeSeries::new(self.config.window_size))
            .push(percent);
    }

    /// Record fan RPM measurement
    pub fn record_fan_rpm(&mut self, fan_idx: usize, rpm: f64) {
        self.fan_rpms
            .entry(fan_idx)
            .or_insert_with(|| TimeSeries::new(self.config.window_size))
            .push(rpm);
    }

    /// Record memory error count
    pub fn record_memory_errors(&mut self, errors: f64) {
        self.memory_errors.push(errors);
    }

    /// Run prediction analysis.
    ///
    /// The report also lists every check that could not run on the data held, so
    /// an empty `alerts` list is never mistaken for "healthy".
    pub fn predict(&self) -> PredictionReport {
        let not_checked = self.check_gaps();
        let mut alerts = Vec::new();

        self.predict_gpu_thermal(&mut alerts);
        self.predict_gpu_degradation(&mut alerts);
        self.predict_disk_failure(&mut alerts);
        self.predict_fan_failure(&mut alerts);
        self.predict_memory_failure(&mut alerts);

        alerts.sort_by_key(|p| std::cmp::Reverse(p.urgency));
        PredictionReport {
            alerts,
            not_checked,
        }
    }

    /// Checks that cannot run on the data held now, using the same minimum the
    /// `predict_*` rules apply before they evaluate a series.
    fn check_gaps(&self) -> Vec<NotChecked> {
        let need = self.config.min_data_points;
        let mut gaps = Vec::new();
        for (family, series) in [
            ("GPU temperature", &self.gpu_temps),
            ("GPU clock", &self.gpu_clocks),
            ("Disk SMART health", &self.disk_health),
            ("Fan RPM", &self.fan_rpms),
        ] {
            if series.is_empty() {
                gaps.push(NotChecked {
                    check: family.to_string(),
                    reason: CheckGap::NoSamples,
                });
            }
            for (&idx, ts) in series {
                if let Some(reason) = sample_gap(ts.len(), need) {
                    gaps.push(NotChecked {
                        check: format!("{family} {idx}"),
                        reason,
                    });
                }
            }
        }
        if let Some(reason) = sample_gap(self.memory_errors.len(), need) {
            gaps.push(NotChecked {
                check: "memory errors".to_string(),
                reason,
            });
        }
        gaps.sort_by(|a, b| a.check.cmp(&b.check));
        gaps
    }

    fn predict_gpu_thermal(&self, alerts: &mut Vec<MaintenanceAlert>) {
        for (&gpu_idx, ts) in &self.gpu_temps {
            if ts.len() < self.config.min_data_points {
                continue;
            }
            let current = match ts.last() {
                Some(v) => v,
                None => continue,
            };

            // Check if trending toward thermal limit
            if let Some(eta) = ts.steps_until_threshold(self.config.gpu_thermal_limit) {
                let (slope, _) = ts.linear_regression().unwrap_or((0.0, 0.0));
                if slope > 0.1 {
                    // Temperature is rising
                    let confidence = ts.r_squared().clamp(0.0, 1.0);
                    // Urgency cut-offs are in samples, the unit of `eta_samples`.
                    let urgency = if eta < 10.0 {
                        Urgency::Critical
                    } else if eta < 50.0 {
                        Urgency::High
                    } else if eta < 200.0 {
                        Urgency::Medium
                    } else {
                        Urgency::Low
                    };

                    alerts.push(MaintenanceAlert {
                        component: format!("GPU {}", gpu_idx),
                        issue_type: IssueType::ThermalDegradation,
                        urgency,
                        message: format!(
                            "GPU {} temperature trending upward ({:.1}°C → predicted {:.1}°C). \
                             Rate: +{:.2}°C/sample",
                            gpu_idx, current, self.config.gpu_thermal_limit, slope
                        ),
                        eta_samples: Some(eta),
                        degradation_rate: Some(slope),
                        current_value: current,
                        threshold: self.config.gpu_thermal_limit,
                        action: "Check cooling system, clean heatsinks, adjust fan curve".into(),
                        confidence,
                    });
                }
            }
        }
    }

    fn predict_gpu_degradation(&self, alerts: &mut Vec<MaintenanceAlert>) {
        for (&gpu_idx, ts) in &self.gpu_clocks {
            if ts.len() < self.config.min_data_points {
                continue;
            }
            let current = match ts.last() {
                Some(v) => v,
                None => continue,
            };

            if let Some((slope, _)) = ts.linear_regression() {
                // Negative slope means clocks are declining
                if slope < -1.0 {
                    let decline = slope.abs() * ts.len() as f64;
                    if decline > self.config.clock_degradation_mhz {
                        let confidence = ts.r_squared().clamp(0.0, 1.0);
                        alerts.push(MaintenanceAlert {
                            component: format!("GPU {}", gpu_idx),
                            issue_type: IssueType::GpuDegradation,
                            urgency: if decline > 200.0 {
                                Urgency::High
                            } else {
                                Urgency::Medium
                            },
                            message: format!(
                                "GPU {} clocks declining ({:.0} MHz loss over {} samples)",
                                gpu_idx,
                                decline,
                                ts.len()
                            ),
                            eta_samples: None,
                            degradation_rate: Some(slope),
                            current_value: current,
                            threshold: self.config.clock_degradation_mhz,
                            action:
                                "May indicate chip degradation. Monitor power limits and thermals."
                                    .into(),
                            confidence,
                        });
                    }
                }
            }
        }
    }

    fn predict_disk_failure(&self, alerts: &mut Vec<MaintenanceAlert>) {
        for (&disk_idx, ts) in &self.disk_health {
            if ts.len() < self.config.min_data_points {
                continue;
            }
            let current = match ts.last() {
                Some(v) => v,
                None => continue,
            };

            if current < self.config.disk_health_warning {
                let urgency = if current < 50.0 {
                    Urgency::Critical
                } else if current < 70.0 {
                    Urgency::High
                } else {
                    Urgency::Medium
                };

                let eta = ts.steps_until_threshold(0.0);

                alerts.push(MaintenanceAlert {
                    component: format!("Disk {}", disk_idx),
                    issue_type: IssueType::DiskFailure,
                    urgency,
                    message: format!(
                        "Disk {} SMART health at {:.0}% (threshold: {:.0}%)",
                        disk_idx, current, self.config.disk_health_warning
                    ),
                    eta_samples: eta,
                    degradation_rate: ts.linear_regression().map(|(s, _)| s),
                    current_value: current,
                    threshold: self.config.disk_health_warning,
                    action: "Back up important data immediately. Plan disk replacement.".into(),
                    confidence: CONFIDENCE_DISK_HEALTH_THRESHOLD,
                });
            }
        }
    }

    fn predict_fan_failure(&self, alerts: &mut Vec<MaintenanceAlert>) {
        for (&fan_idx, ts) in &self.fan_rpms {
            if ts.len() < self.config.min_data_points {
                continue;
            }
            let current = match ts.last() {
                Some(v) => v,
                None => continue,
            };

            // Check for declining RPM
            if let Some((slope, _)) = ts.linear_regression() {
                if slope < -self.config.fan_degradation_rate / ts.len() as f64 {
                    let eta = ts.steps_until_threshold(self.config.fan_min_rpm);
                    let confidence = ts.r_squared().clamp(0.0, 1.0);

                    let urgency = if current < self.config.fan_min_rpm {
                        Urgency::Critical
                    } else if let Some(eta_val) = eta {
                        if eta_val < 50.0 {
                            Urgency::High
                        } else {
                            Urgency::Medium
                        }
                    } else {
                        Urgency::Low
                    };

                    alerts.push(MaintenanceAlert {
                        component: format!("Fan {}", fan_idx),
                        issue_type: IssueType::FanFailure,
                        urgency,
                        message: format!(
                            "Fan {} RPM declining (currently {:.0} RPM, rate: {:.1} RPM/sample)",
                            fan_idx, current, slope
                        ),
                        eta_samples: eta,
                        degradation_rate: Some(slope),
                        current_value: current,
                        threshold: self.config.fan_min_rpm,
                        action: "Inspect fan bearings, clean dust, plan replacement.".into(),
                        confidence,
                    });
                }
            }
        }
    }

    fn predict_memory_failure(&self, alerts: &mut Vec<MaintenanceAlert>) {
        if self.memory_errors.len() < self.config.min_data_points {
            return;
        }
        let current = match self.memory_errors.last() {
            Some(v) => v,
            None => return,
        };

        if current > 0.0 {
            if let Some((slope, _)) = self.memory_errors.linear_regression() {
                if slope > 0.0 {
                    let urgency = if current > self.config.memory_error_threshold * 10.0 {
                        Urgency::Critical
                    } else if current > self.config.memory_error_threshold {
                        Urgency::High
                    } else {
                        Urgency::Medium
                    };

                    alerts.push(MaintenanceAlert {
                        component: "Memory".into(),
                        issue_type: IssueType::MemoryFailure,
                        urgency,
                        message: format!(
                            "Memory errors increasing ({:.0} errors, rate: +{:.2}/sample)",
                            current, slope
                        ),
                        eta_samples: None,
                        degradation_rate: Some(slope),
                        current_value: current,
                        threshold: self.config.memory_error_threshold,
                        action: "Run memory diagnostics (memtest86+). Consider RAM replacement."
                            .into(),
                        confidence: CONFIDENCE_MEMORY_ERROR_THRESHOLD,
                    });
                }
            }
        }
    }

    /// Get a summary of maintenance status
    pub fn summary(&self) -> MaintenanceSummary {
        let report = self.predict();
        let alerts = &report.alerts;
        MaintenanceSummary {
            total_alerts: alerts.len(),
            critical: alerts
                .iter()
                .filter(|a| a.urgency == Urgency::Critical)
                .count(),
            high: alerts.iter().filter(|a| a.urgency == Urgency::High).count(),
            medium: alerts
                .iter()
                .filter(|a| a.urgency == Urgency::Medium)
                .count(),
            low: alerts.iter().filter(|a| a.urgency == Urgency::Low).count(),
            components_monitored: self.gpu_temps.len()
                + self.disk_health.len()
                + self.fan_rpms.len()
                + if self.memory_errors.len() > 0 { 1 } else { 0 },
            data_points: self.gpu_temps.values().map(|t| t.len()).sum::<usize>()
                + self.disk_health.values().map(|t| t.len()).sum::<usize>()
                + self.fan_rpms.values().map(|t| t.len()).sum::<usize>()
                + self.memory_errors.len(),
            checks_not_run: report.not_checked.len(),
        }
    }
}

/// Summary of predictive maintenance status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaintenanceSummary {
    /// Total number of active alerts
    pub total_alerts: usize,
    /// Number of critical alerts
    pub critical: usize,
    /// Number of high-urgency alerts
    pub high: usize,
    /// Number of medium-urgency alerts
    pub medium: usize,
    /// Number of low-urgency alerts
    pub low: usize,
    /// Number of components being monitored
    pub components_monitored: usize,
    /// Total data points collected
    pub data_points: usize,
    /// Checks that could not run on the data held. `total_alerts` of zero is only
    /// a clean result when this is zero too.
    pub checks_not_run: usize,
}

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

    #[test]
    fn test_linear_regression() {
        let mut ts = TimeSeries::new(100);
        for i in 0..20 {
            ts.push(i as f64 * 2.0 + 10.0);
        }
        let (slope, intercept) = ts.linear_regression().unwrap();
        assert!((slope - 2.0).abs() < 0.01);
        assert!((intercept - 10.0).abs() < 0.01);
    }

    #[test]
    fn test_steps_until_threshold() {
        let mut ts = TimeSeries::new(100);
        // Linear increase: 50, 55, 60, 65, 70...
        for i in 0..10 {
            ts.push(50.0 + i as f64 * 5.0);
        }
        // Current at 95, threshold at 100
        let steps = ts.steps_until_threshold(120.0);
        assert!(steps.is_some());
        assert!(steps.unwrap() > 0.0);
    }

    #[test]
    fn test_r_squared_perfect_fit() {
        let mut ts = TimeSeries::new(100);
        for i in 0..20 {
            ts.push(i as f64 * 3.0);
        }
        let r2 = ts.r_squared();
        assert!(
            r2 > 0.99,
            "R² should be near 1.0 for perfect linear data, got {}",
            r2
        );
    }

    #[test]
    fn test_thermal_prediction() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        // Simulated rising GPU temperatures
        for i in 0..20 {
            engine.record_gpu_temp(0, 60.0 + i as f64 * 1.5);
        }
        let alerts = engine.predict().alerts;
        assert!(!alerts.is_empty(), "Should predict thermal issue");
        assert_eq!(alerts[0].issue_type, IssueType::ThermalDegradation);
    }

    #[test]
    fn test_disk_health_alert() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        for i in 0..15 {
            engine.record_disk_health(0, 90.0 - i as f64 * 2.0);
        }
        let alerts = engine.predict().alerts;
        assert!(
            alerts
                .iter()
                .any(|a| a.issue_type == IssueType::DiskFailure),
            "Should detect disk health decline"
        );
    }

    #[test]
    fn test_fan_failure_prediction() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        for i in 0..20 {
            engine.record_fan_rpm(0, 1800.0 - i as f64 * 60.0);
        }
        let alerts = engine.predict().alerts;
        assert!(
            alerts.iter().any(|a| a.issue_type == IssueType::FanFailure),
            "Should predict fan failure"
        );
    }

    #[test]
    fn test_no_alerts_stable_system() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        for _ in 0..20 {
            engine.record_gpu_temp(0, 65.0);
            engine.record_disk_health(0, 98.0);
            engine.record_fan_rpm(0, 1800.0);
        }
        let alerts = engine.predict().alerts;
        assert!(alerts.is_empty(), "Stable system should produce no alerts");
    }

    #[test]
    fn test_maintenance_summary() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        for i in 0..20 {
            engine.record_gpu_temp(0, 60.0 + i as f64 * 1.5);
        }
        let summary = engine.summary();
        assert!(summary.components_monitored > 0);
        assert!(summary.data_points > 0);
    }

    /// An engine with no data ran no checks, so its empty list is not "healthy".
    #[test]
    fn an_empty_engine_reports_its_checks_as_not_run() {
        let engine = MaintenanceEngine::new(PredictionConfig::default());
        let report = engine.predict();
        assert!(report.alerts.is_empty());
        assert_eq!(report.verdict(), Verdict::NotFullyChecked);
        assert!(report.not_checked.contains(&NotChecked {
            check: "GPU temperature".into(),
            reason: CheckGap::NoSamples,
        }));
        assert!(report.not_checked.contains(&NotChecked {
            check: "memory errors".into(),
            reason: CheckGap::NoSamples,
        }));
        assert_eq!(engine.summary().checks_not_run, report.not_checked.len());
    }

    /// Five points are below the minimum, so the trend rule did not run on them.
    #[test]
    fn too_few_points_are_reported_as_insufficient() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        for _ in 0..5 {
            engine.record_gpu_temp(0, 65.0);
        }
        let report = engine.predict();
        assert!(report.not_checked.contains(&NotChecked {
            check: "GPU temperature 0".into(),
            reason: CheckGap::InsufficientSamples { have: 5, need: 10 },
        }));
    }

    /// Every family was evaluated on enough data and nothing is failing: clear.
    #[test]
    fn a_stable_fully_checked_system_is_clear() {
        let mut engine = MaintenanceEngine::new(PredictionConfig::default());
        for _ in 0..20 {
            engine.record_gpu_temp(0, 65.0);
            engine.record_gpu_clock(0, 1800.0);
            engine.record_disk_health(0, 98.0);
            engine.record_fan_rpm(0, 1800.0);
            engine.record_memory_errors(0.0);
        }
        let report = engine.predict();
        assert!(report.not_checked.is_empty(), "{:?}", report.not_checked);
        assert!(report.alerts.is_empty());
        assert_eq!(report.verdict(), Verdict::Clear);
    }
}