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
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
//! Power profile and energy management monitoring.
//!
//! Reads OS power plans, CPU frequency governor, battery charge policy,
//! and provides inferred energy efficiency metrics.
//!
//! # Platform Support
//!
//! - **Linux**: cpufreq governors, TLP, power-profiles-daemon, `/sys/class/power_supply/`
//! - **Windows**: `powercfg`, `Win32_PowerPlan`
//! - **macOS**: `pmset`, System Preferences Energy Saver settings
//!
//! # Inference
//!
//! Infers system power behavior from governor + CPU frequency ranges + battery
//! status to classify the system as performance-focused, balanced, or power-saving.
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::power_profile::PowerProfileMonitor;
//!
//! let monitor = PowerProfileMonitor::new().unwrap();
//! println!("Active profile: {:?}", monitor.active_profile());
//! println!("Inferred behavior: {:?}", monitor.inferred_behavior());
//! ```

use crate::error::IronError;
use serde::{Deserialize, Serialize};

/// Named power profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PowerProfile {
    Performance,
    Balanced,
    PowerSaver,
    UltraPowerSaver,
    Custom(String),
    Unknown,
}

/// CPU frequency governor (Linux).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CpuGovernor {
    Performance,
    Powersave,
    Ondemand,
    Conservative,
    Schedutil,
    Userspace,
    Other(String),
}

/// Battery charge policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChargePolicy {
    /// Charge to 100%
    Full,
    /// Stop charging at threshold (e.g., 80%)
    Threshold(u8),
    /// Adaptive based on usage patterns
    Adaptive,
    /// No battery present
    NoBattery,
    Unknown,
}

/// Starting rule score for `InferredPowerBehavior::confidence`, before any input
/// matched a rule. A constant of the rule, chosen for it; it is not a measured
/// probability.
const POWER_CONFIDENCE_BASE: f32 = 0.5;
/// Rule-score step for a `performance` governor. A constant of that rule, chosen for
/// it; it is not a measured probability.
const POWER_CONFIDENCE_STEP_PERFORMANCE_GOVERNOR: f32 = 0.15;
/// Rule-score step for a `powersave` governor. A constant of that rule, chosen for it;
/// it is not a measured probability.
const POWER_CONFIDENCE_STEP_POWERSAVE_GOVERNOR: f32 = 0.15;
/// Rule-score step for a `schedutil` governor. A constant of that rule, chosen for it;
/// it is not a measured probability.
const POWER_CONFIDENCE_STEP_SCHEDUTIL_GOVERNOR: f32 = 0.1;
/// Rule-score step for an `ondemand` governor. A constant of that rule, chosen for it;
/// it is not a measured probability.
const POWER_CONFIDENCE_STEP_ONDEMAND_GOVERNOR: f32 = 0.1;
/// Rule-score step for a charge threshold at or below 80%. A constant of that rule,
/// chosen for it; it is not a measured probability.
const POWER_CONFIDENCE_STEP_CHARGE_THRESHOLD: f32 = 0.05;

/// Inferred system power behavior based on hardware + software config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferredPowerBehavior {
    /// Classification; `Unknown` when no input was read.
    pub classification: PowerProfile,
    /// Rule score in 0.0-1.0, not a probability: `POWER_CONFIDENCE_BASE` plus a fixed
    /// step per matching input (governor, charge threshold), capped at 1.0. `None`
    /// when no input was read.
    pub confidence: Option<f32>,
    /// Idle power draw in watts from a per-class table (Performance 25, Balanced 15,
    /// PowerSaver 8, UltraPowerSaver 5), not measured on this machine. `None` when no
    /// input was read.
    pub estimated_idle_watts: Option<f32>,
    /// Max power draw in watts from a per-class table (Performance 250, Balanced 200,
    /// PowerSaver 150, UltraPowerSaver 100), not measured on this machine. `None` when
    /// no input was read.
    pub estimated_max_watts: Option<f32>,
    /// Efficiency score (0-100, higher = more efficient configuration), a rule score
    /// starting from a constant 50. `None` when no input was read.
    pub efficiency_score: Option<u8>,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Power plan info (Windows).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PowerPlanInfo {
    /// Plan GUID
    pub guid: String,
    /// Plan name
    pub name: String,
    /// Whether this plan is active
    pub active: bool,
}

/// CPU frequency configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuFreqConfig {
    /// Current governor, or `None` where `scaling_governor` was absent or empty.
    pub governor: Option<CpuGovernor>,
    /// Current frequency (MHz), or `None` where `scaling_cur_freq` could not
    /// be read.
    ///
    /// **A second copy of the `cpufreq` defect, one module over.** All three
    /// of these were bare `u32` filled with `.unwrap_or(0)`, beside a
    /// `base_freq_mhz` that was already `Option` for exactly this reason --
    /// the same "bare field next to an `Option` sibling in the same struct"
    /// tell that found the other six.
    pub current_freq_mhz: Option<u32>,
    /// Minimum frequency (MHz), or `None` where unread.
    pub min_freq_mhz: Option<u32>,
    /// Maximum frequency (MHz), or `None` where unread.
    pub max_freq_mhz: Option<u32>,
    /// Base (P1) frequency if known
    pub base_freq_mhz: Option<u32>,
    /// Boost/turbo enabled, or `None` where neither boost file could be read.
    pub boost_enabled: Option<bool>,
    /// Energy Performance Preference (Linux: /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference), or `None` where unread.
    pub energy_perf_preference: Option<String>,
}

/// Full power profile state.
pub struct PowerProfileMonitor {
    active_profile: PowerProfile,
    power_plans: Vec<PowerPlanInfo>,
    cpu_freq: Option<CpuFreqConfig>,
    charge_policy: ChargePolicy,
    inferred: Option<InferredPowerBehavior>,
    /// Whether the system is on AC power.
    ///
    /// `None` when it was not established. It was a `bool` initialised to
    /// `true`, so a machine where nothing had been read was on mains, and the
    /// Windows reader set it with `text != "1"` on the output of a PowerShell
    /// query -- an empty string from a failed query is not "1", so a failure
    /// also read as mains. `on_ac_power` gates every battery recommendation
    /// this module makes, so the failure mode was silence about a laptop's
    /// power settings while it ran on battery.
    pub on_ac_power: Option<bool>,
    /// Display brightness (0-100)
    pub display_brightness: Option<u8>,
    /// Auto-sleep timeout (seconds). On macOS, the `AC Power` value only.
    pub sleep_timeout_secs: Option<u32>,
    /// Disk standby timeout (seconds). On macOS, the `AC Power` value only.
    pub disk_standby_secs: Option<u32>,
}

impl PowerProfileMonitor {
    pub fn new() -> Result<Self, IronError> {
        let mut monitor = Self {
            active_profile: PowerProfile::Unknown,
            power_plans: Vec::new(),
            cpu_freq: None,
            charge_policy: ChargePolicy::Unknown,
            inferred: None,
            on_ac_power: None,
            display_brightness: None,
            sleep_timeout_secs: None,
            disk_standby_secs: None,
        };
        monitor.refresh()?;
        Ok(monitor)
    }

    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.power_plans.clear();

        #[cfg(target_os = "linux")]
        self.refresh_linux()?;

        #[cfg(target_os = "windows")]
        self.refresh_windows()?;

        #[cfg(target_os = "macos")]
        self.refresh_macos()?;

        // Run inference
        self.inferred = Some(self.infer_behavior());

        Ok(())
    }

    pub fn active_profile(&self) -> &PowerProfile {
        &self.active_profile
    }

    pub fn power_plans(&self) -> &[PowerPlanInfo] {
        &self.power_plans
    }

    pub fn cpu_freq_config(&self) -> Option<&CpuFreqConfig> {
        self.cpu_freq.as_ref()
    }

    pub fn charge_policy(&self) -> &ChargePolicy {
        &self.charge_policy
    }

    pub fn inferred_behavior(&self) -> Option<&InferredPowerBehavior> {
        self.inferred.as_ref()
    }

    /// Infer power behavior from collected data.
    fn infer_behavior(&self) -> InferredPowerBehavior {
        // Nothing read means nothing to infer from. Without this the score starts
        // from a constant 50 and the watt figures are table values, and both would
        // be reported as if they described this machine.
        let any_input_read = self.cpu_freq.is_some()
            || self.active_profile != PowerProfile::Unknown
            || self.on_ac_power.is_some()
            || self.charge_policy != ChargePolicy::Unknown
            || self.display_brightness.is_some();
        if !any_input_read {
            return InferredPowerBehavior {
                classification: PowerProfile::Unknown,
                confidence: None,
                estimated_idle_watts: None,
                estimated_max_watts: None,
                efficiency_score: None,
                recommendations: Vec::new(),
            };
        }

        let mut score = 50u8; // Start balanced
        let mut confidence = POWER_CONFIDENCE_BASE;
        let mut recommendations = Vec::new();

        // Governor analysis
        if let Some(ref freq) = self.cpu_freq {
            match freq.governor.as_ref() {
                Some(CpuGovernor::Performance) => {
                    score = score.saturating_sub(20); // Less efficient
                    confidence += POWER_CONFIDENCE_STEP_PERFORMANCE_GOVERNOR;
                }
                Some(CpuGovernor::Powersave) => {
                    score = score.saturating_add(20);
                    confidence += POWER_CONFIDENCE_STEP_POWERSAVE_GOVERNOR;
                }
                Some(CpuGovernor::Schedutil) => {
                    score = score.saturating_add(10); // Good default
                    confidence += POWER_CONFIDENCE_STEP_SCHEDUTIL_GOVERNOR;
                }
                Some(CpuGovernor::Ondemand) => {
                    score = score.saturating_add(5);
                    confidence += POWER_CONFIDENCE_STEP_ONDEMAND_GOVERNOR;
                }
                _ => {}
            }

            // Boost analysis
            if freq.boost_enabled == Some(true) {
                score = score.saturating_sub(5);
                if self.on_ac_power == Some(false) {
                    recommendations.push(
                        "Consider disabling CPU boost on battery for better battery life".into(),
                    );
                }
            }

            // Frequency range analysis. The `> 0` pair was doing two jobs --
            // skipping an unread pair and avoiding a divide by zero -- and
            // could not tell them apart. Now it only does the second.
            if let (Some(min), Some(max)) = (freq.min_freq_mhz, freq.max_freq_mhz) {
                let ratio = if max > 0 {
                    min as f32 / max as f32
                } else {
                    0.0
                };
                if ratio > 0.8 {
                    // Min freq locked high — wasteful
                    score = score.saturating_sub(10);
                    recommendations.push(
                        "CPU minimum frequency is high — consider lowering for power savings"
                            .into(),
                    );
                }
            }

            // EPP analysis
            match freq.energy_perf_preference.as_deref() {
                Some("performance") => score = score.saturating_sub(10),
                Some("power") | Some("power_save") => score = score.saturating_add(10),
                Some("balance_performance") => {}
                Some("balance_power") => score = score.saturating_add(5),
                _ => {}
            }
        }

        // Battery / AC analysis
        if self.on_ac_power == Some(false) {
            match &self.active_profile {
                PowerProfile::Performance => {
                    recommendations.push(
                        "Running performance profile on battery — battery life will be reduced"
                            .into(),
                    );
                    score = score.saturating_sub(15);
                }
                PowerProfile::PowerSaver | PowerProfile::UltraPowerSaver => {
                    score = score.saturating_add(10);
                }
                _ => {}
            }
        }

        // Charge policy
        match &self.charge_policy {
            ChargePolicy::Threshold(t) if *t <= 80 => {
                score = score.saturating_add(5);
                confidence += POWER_CONFIDENCE_STEP_CHARGE_THRESHOLD;
            }
            ChargePolicy::Full => {
                recommendations.push(
                    "Consider setting a charge threshold (e.g., 80%) to extend battery lifespan"
                        .into(),
                );
            }
            _ => {}
        }

        // Display brightness
        if let Some(brightness) = self.display_brightness {
            if brightness > 80 && self.on_ac_power == Some(false) {
                recommendations.push(
                    "Display brightness is high on battery — consider reducing for power savings"
                        .into(),
                );
                score = score.saturating_sub(5);
            }
        }

        let classification = if score >= 70 {
            PowerProfile::PowerSaver
        } else if score >= 40 {
            PowerProfile::Balanced
        } else {
            PowerProfile::Performance
        };

        // Per-class table figures, not measurements of this machine.
        let (idle_watts, max_watts) = match &classification {
            PowerProfile::Performance => (25.0, 250.0),
            PowerProfile::Balanced => (15.0, 200.0),
            PowerProfile::PowerSaver => (8.0, 150.0),
            PowerProfile::UltraPowerSaver => (5.0, 100.0),
            _ => (15.0, 200.0),
        };

        InferredPowerBehavior {
            classification,
            confidence: Some(confidence.min(1.0)),
            estimated_idle_watts: Some(idle_watts),
            estimated_max_watts: Some(max_watts),
            efficiency_score: Some(score.min(100)),
            recommendations,
        }
    }

    #[cfg(target_os = "linux")]
    fn refresh_linux(&mut self) -> Result<(), IronError> {
        // Every source here is optional -- a kernel without cpufreq has no
        // governor, a desktop has no battery -- so nothing in this reader is
        // an enumeration whose failure means "no power profiles". The
        // signature is `Result` for consistency with the other two.
        // CPU frequency governor. Missing or empty is `None`: an unread governor
        // is not a `powersave` governor.
        let governor =
            std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")
                .ok()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .map(|gov| match gov.as_str() {
                    "performance" => CpuGovernor::Performance,
                    "powersave" => CpuGovernor::Powersave,
                    "ondemand" => CpuGovernor::Ondemand,
                    "conservative" => CpuGovernor::Conservative,
                    "schedutil" => CpuGovernor::Schedutil,
                    "userspace" => CpuGovernor::Userspace,
                    other => CpuGovernor::Other(other.to_string()),
                });

        // `.map` rather than `.unwrap_or(0)`: a kernel without cpufreq has no
        // frequency to report, and 0 MHz is not what that looks like.
        let cur_freq =
            std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq")
                .ok()
                .and_then(|s| s.trim().parse::<u32>().ok())
                .map(|khz| khz / 1000);

        let min_freq =
            std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq")
                .ok()
                .and_then(|s| s.trim().parse::<u32>().ok())
                .map(|khz| khz / 1000);

        let max_freq =
            std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")
                .ok()
                .and_then(|s| s.trim().parse::<u32>().ok())
                .map(|khz| khz / 1000);

        let base_freq =
            std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/base_frequency")
                .ok()
                .and_then(|s| s.trim().parse::<u32>().ok())
                .map(|f| f / 1000);

        // boost file: 1 = enabled; no_turbo: 0 = enabled (inverted). A file that is
        // missing or holds anything else leaves the flag unread, not false.
        let boost_enabled = std::fs::read_to_string("/sys/devices/system/cpu/cpufreq/boost")
            .ok()
            .and_then(|s| match s.trim() {
                "1" => Some(true),
                "0" => Some(false),
                _ => None,
            })
            .or_else(|| {
                std::fs::read_to_string("/sys/devices/system/cpu/intel_pstate/no_turbo")
                    .ok()
                    .and_then(|s| match s.trim() {
                        "0" => Some(true),
                        "1" => Some(false),
                        _ => None,
                    })
            });

        let epp = std::fs::read_to_string(
            "/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference",
        )
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());

        // `cpu_freq` is absent when nothing under cpufreq was read, rather than a
        // struct of unread fields that still says the reader succeeded.
        let any_cpufreq_read = governor.is_some()
            || cur_freq.is_some()
            || min_freq.is_some()
            || max_freq.is_some()
            || base_freq.is_some()
            || boost_enabled.is_some()
            || epp.is_some();
        self.cpu_freq = if any_cpufreq_read {
            Some(CpuFreqConfig {
                governor,
                current_freq_mhz: cur_freq,
                min_freq_mhz: min_freq,
                max_freq_mhz: max_freq,
                base_freq_mhz: base_freq,
                boost_enabled,
                energy_perf_preference: epp,
            })
        } else {
            None
        };

        // The OS power profile. power-profiles-daemon is the source when it is
        // running; otherwise the kernel's platform_profile. Neither is the cpufreq
        // governor: deriving the profile from the governor (as this reader did
        // before) labelled every governor not listed as Balanced. With neither
        // source readable the profile is Unknown.
        let from_ppd = std::process::Command::new("powerprofilesctl")
            .arg("get")
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .and_then(|s| match s.trim() {
                "performance" => Some(PowerProfile::Performance),
                "balanced" => Some(PowerProfile::Balanced),
                "power-saver" => Some(PowerProfile::PowerSaver),
                _ => None,
            });
        let from_platform = std::fs::read_to_string("/sys/firmware/acpi/platform_profile")
            .ok()
            .and_then(|s| match s.trim() {
                "performance" => Some(PowerProfile::Performance),
                "balanced" => Some(PowerProfile::Balanced),
                "low-power" => Some(PowerProfile::PowerSaver),
                _ => None,
            });
        self.active_profile = from_ppd.or(from_platform).unwrap_or(PowerProfile::Unknown);

        // AC power status
        // `read_dir` yields a Result; the doubled loop was iterating that Result as
        // if it were a collection, which reads as two levels of directory when
        // there is only one.
        //
        // A machine can have several mains supplies (one per USB-C port), so any
        // online one means AC; taking the last one read let an unplugged port
        // override a plugged one. Only "1" and "0" are a reading.
        if let Ok(entries) = std::fs::read_dir("/sys/class/power_supply") {
            let mut mains_online = Vec::new();
            for e in entries.flatten() {
                let path = e.path();
                if let Ok(ptype) = std::fs::read_to_string(path.join("type")) {
                    if ptype.trim() == "Mains" {
                        if let Ok(online) = std::fs::read_to_string(path.join("online")) {
                            mains_online.push(match online.trim() {
                                "1" => Some(true),
                                "0" => Some(false),
                                _ => None,
                            });
                        }
                    }
                }
            }
            self.on_ac_power = combine_mains_online(&mains_online);
        }

        // Charge threshold (ThinkPad, ASUS, etc.)
        let threshold_paths = [
            "/sys/class/power_supply/BAT0/charge_control_end_threshold",
            "/sys/class/power_supply/BAT1/charge_control_end_threshold",
        ];
        for path in &threshold_paths {
            if let Ok(val) = std::fs::read_to_string(path) {
                if let Ok(t) = val.trim().parse::<u8>() {
                    self.charge_policy = if t >= 100 {
                        ChargePolicy::Full
                    } else {
                        ChargePolicy::Threshold(t)
                    };
                    break;
                }
            }
        }

        // Brightness
        // Only the first backlight is read — the loop ended in an unconditional
        // `break`, so it never iterated. `next()` says that outright.
        if let Some(entry) = std::fs::read_dir("/sys/class/backlight")
            .ok()
            .and_then(|mut entries| entries.next())
            .and_then(|e| e.ok())
        {
            let path = entry.path();
            let cur = std::fs::read_to_string(path.join("brightness"))
                .ok()
                .and_then(|s| s.trim().parse::<u32>().ok());
            let max = std::fs::read_to_string(path.join("max_brightness"))
                .ok()
                .and_then(|s| s.trim().parse::<u32>().ok());
            if let (Some(c), Some(m)) = (cur, max) {
                if m > 0 {
                    self.display_brightness = Some(((c as f32 / m as f32) * 100.0) as u8);
                }
            }
        }
        Ok(())
    }

    #[cfg(target_os = "windows")]
    fn refresh_windows(&mut self) -> Result<(), IronError> {
        // `powercfg /list` is the enumeration. It ships with Windows, so a
        // failure to run it is a failure -- and an empty plan list is what the
        // resolver publishes as `power.profile.<none>`, a claim that this
        // machine has no power plans.
        {
            let text = crate::core::command::capture("powercfg", &["/list"])?;
            for line in text.lines() {
                // "Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced) *"
                if line.contains("GUID:") {
                    let active = line.ends_with('*');
                    // Extract GUID
                    if let Some(guid_start) = line.find("GUID:") {
                        let after = &line[guid_start + 6..];
                        let guid = after.split_whitespace().next().unwrap_or("").to_string();
                        if guid.is_empty() {
                            // A plan with no GUID cannot be addressed; it is not listed.
                            continue;
                        }
                        // Extract name in parentheses
                        let name = after
                            .split('(')
                            .nth(1)
                            .and_then(|s| s.split(')').next())
                            .unwrap_or("")
                            .to_string();

                        if active {
                            self.active_profile =
                                if name.to_lowercase().contains("high performance")
                                    || name.to_lowercase().contains("ultimate")
                                {
                                    PowerProfile::Performance
                                } else if name.to_lowercase().contains("power saver") {
                                    PowerProfile::PowerSaver
                                } else if name.to_lowercase().contains("balanced") {
                                    PowerProfile::Balanced
                                } else if name.is_empty() {
                                    PowerProfile::Unknown
                                } else {
                                    PowerProfile::Custom(name.clone())
                                };
                        }

                        self.power_plans.push(PowerPlanInfo { guid, name, active });
                    }
                }
            }
        }

        // AC power status.
        //
        // This spawned PowerShell for `(Get-CimInstance Win32_Battery).BatteryStatus`
        // and set `on_ac_power = text != "1"`. A desktop has no battery and the
        // query returns nothing, which is not "1"; a query that fails also
        // returns nothing, which is also not "1". `GetSystemPowerStatus` asks
        // the kernel directly and has a value for the third case:
        // `ACLineStatus` is 0 offline, 1 online, 255 unknown.
        {
            use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};
            let mut status = SYSTEM_POWER_STATUS::default();
            if unsafe { GetSystemPowerStatus(&mut status) }.is_ok() {
                self.on_ac_power = match status.ACLineStatus {
                    0 => Some(false),
                    1 => Some(true),
                    _ => None,
                };
            }
        }

        // Brightness
        if let Ok(output) = std::process::Command::new("powershell")
            .args(["-NoProfile", "-Command",
                "(Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightness).CurrentBrightness"])
            .output()
        {
            if let Ok(b) = String::from_utf8(output.stdout).unwrap_or_default().trim().parse::<u8>()
            {
                self.display_brightness = Some(b);
            }
        }
        Ok(())
    }

    #[cfg(target_os = "macos")]
    fn refresh_macos(&mut self) -> Result<(), IronError> {
        // `pmset` ships with macOS, so a failure to run it is a failure.
        {
            let text = crate::core::command::capture("pmset", &["-g", "custom"])?;
            let (sleep, disk_sleep) = parse_pmset_custom(&text);
            self.sleep_timeout_secs = sleep;
            self.disk_standby_secs = disk_sleep;
        }

        // Infer profile from pmset settings. `lowpowermode` is the only profile
        // signal pmset reports; with no such line the profile stays Unknown.
        if let Ok(output) = std::process::Command::new("pmset").args(["-g"]).output() {
            let text = String::from_utf8(output.stdout).unwrap_or_default();
            let modes: Vec<&str> = text
                .lines()
                .filter_map(|l| {
                    let mut parts = l.split_whitespace();
                    if parts.next() == Some("lowpowermode") {
                        parts.next()
                    } else {
                        None
                    }
                })
                .collect();
            self.active_profile = profile_from_pmset_modes(&modes);
        }

        // Check AC power. `pmset -g ps` names the source it is drawing from. A
        // failed command, or output that names no known source, leaves it unread.
        self.on_ac_power = std::process::Command::new("pmset")
            .args(["-g", "ps"])
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .and_then(|text| parse_pmset_power_source(&text));
        Ok(())
    }
}

/// Sleep and disk-sleep timeouts, in seconds, from `pmset -g custom`.
///
/// Only the `AC Power:` section is read. Both sections used to write the same
/// fields, so whichever came last in the output won, and a battery figure could
/// stand in for the mains one.
#[cfg(any(target_os = "macos", test))]
fn parse_pmset_custom(text: &str) -> (Option<u32>, Option<u32>) {
    let mut sleep = None;
    let mut disk_sleep = None;
    let mut in_ac_section = false;
    for line in text.lines() {
        let line = line.trim();
        if line.starts_with("Battery Power:") {
            in_ac_section = false;
        } else if line.starts_with("AC Power:") {
            in_ac_section = true;
        }
        if !in_ac_section {
            continue;
        }
        // The value is in minutes.
        let minutes = line
            .split_whitespace()
            .nth(1)
            .and_then(|v| v.parse::<u32>().ok())
            .map(|v| v.saturating_mul(60));
        if line.starts_with("disksleep") {
            disk_sleep = minutes.or(disk_sleep);
        } else if line.starts_with("sleep") {
            sleep = minutes.or(sleep);
        }
    }
    (sleep, disk_sleep)
}

/// The profile implied by the `lowpowermode` values in `pmset -g`.
///
/// `1` is Low Power Mode, which is `PowerSaver`. `0` means Low Power Mode is
/// off, and that is not a profile this enum names. It used to map to `Balanced`,
/// a name pmset never reports, so it is `Unknown` here.
#[cfg(any(target_os = "macos", test))]
fn profile_from_pmset_modes(modes: &[&str]) -> PowerProfile {
    if modes.contains(&"1") {
        PowerProfile::PowerSaver
    } else {
        PowerProfile::Unknown
    }
}

/// Parses `pmset -g ps` output: the line naming the power source in use.
///
/// `Some(true)` for `'AC Power'`, `Some(false)` for `'Battery Power'`, and `None`
/// for anything else, including empty output and `'UPS Power'`, none of which says
/// whether the machine is on mains.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn parse_pmset_power_source(text: &str) -> Option<bool> {
    let line = text.lines().find(|l| l.contains("drawing from"))?;
    if line.contains("'AC Power'") {
        Some(true)
    } else if line.contains("'Battery Power'") {
        Some(false)
    } else {
        None
    }
}

impl Default for PowerProfileMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            active_profile: PowerProfile::Unknown,
            power_plans: Vec::new(),
            cpu_freq: None,
            charge_policy: ChargePolicy::Unknown,
            inferred: None,
            on_ac_power: None,
            display_brightness: None,
            sleep_timeout_secs: None,
            disk_standby_secs: None,
        })
    }
}

/// Whether a machine is on AC from each mains supply's `online` reading. Any
/// supply online means AC; all read and offline means not; otherwise unknown.
#[cfg(any(target_os = "linux", test))]
fn combine_mains_online(readings: &[Option<bool>]) -> Option<bool> {
    if readings.contains(&Some(true)) {
        Some(true)
    } else if !readings.is_empty() && readings.iter().all(|r| *r == Some(false)) {
        Some(false)
    } else {
        None
    }
}

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

    #[test]
    fn any_online_mains_supply_means_ac() {
        assert_eq!(combine_mains_online(&[Some(true), Some(false)]), Some(true));
        assert_eq!(combine_mains_online(&[Some(false), Some(true)]), Some(true));
        assert_eq!(
            combine_mains_online(&[Some(false), Some(false)]),
            Some(false)
        );
        // An unread supply could be the online one, so "all offline" needs all read.
        assert_eq!(combine_mains_online(&[Some(false), None]), None);
        assert_eq!(combine_mains_online(&[]), None);
    }

    /// Constructing the monitor either enumerates or says why it could not.
    ///
    /// This asserted `is_ok()`, which was true by construction until 6.0.0
    /// because `refresh` could not fail. Now that it can, the contract is
    /// weaker and more useful: **whatever happens, the caller can tell which
    /// happened.** A failure has to carry a reason, because a reason is the
    /// whole difference between "this machine has none" and "nobody looked".
    #[test]
    fn test_power_profile_creation() {
        match PowerProfileMonitor::new() {
            Ok(_monitor) => {}
            Err(e) => {
                let why = e.to_string();
                assert!(
                    why.len() > 10,
                    "enumeration failed without saying why: {why:?}"
                );
            }
        }
    }

    #[test]
    fn test_power_profile_default() {
        let monitor = PowerProfileMonitor::default();
        let _ = monitor.active_profile();
        let _ = monitor.inferred_behavior();
        let _ = monitor.charge_policy();
    }

    #[test]
    fn test_inference_performance() {
        let monitor = PowerProfileMonitor {
            active_profile: PowerProfile::Performance,
            power_plans: Vec::new(),
            cpu_freq: Some(CpuFreqConfig {
                governor: Some(CpuGovernor::Performance),
                current_freq_mhz: Some(4500),
                min_freq_mhz: Some(4000),
                max_freq_mhz: Some(5000),
                base_freq_mhz: Some(3700),
                boost_enabled: Some(true),
                energy_perf_preference: Some("performance".into()),
            }),
            charge_policy: ChargePolicy::Full,
            inferred: None,
            on_ac_power: Some(false), // On battery with performance = bad
            display_brightness: Some(100),
            sleep_timeout_secs: None,
            disk_standby_secs: None,
        };
        let behavior = monitor.infer_behavior();
        assert!(behavior.efficiency_score.is_some_and(|s| s < 30)); // Should be low efficiency
        assert!(!behavior.recommendations.is_empty());
    }

    #[test]
    fn test_inference_powersaver() {
        let monitor = PowerProfileMonitor {
            active_profile: PowerProfile::PowerSaver,
            power_plans: Vec::new(),
            cpu_freq: Some(CpuFreqConfig {
                governor: Some(CpuGovernor::Powersave),
                current_freq_mhz: Some(800),
                min_freq_mhz: Some(400),
                max_freq_mhz: Some(3600),
                base_freq_mhz: Some(2400),
                boost_enabled: Some(false),
                energy_perf_preference: Some("power".into()),
            }),
            charge_policy: ChargePolicy::Threshold(80),
            inferred: None,
            on_ac_power: Some(false),
            display_brightness: Some(40),
            sleep_timeout_secs: Some(300),
            disk_standby_secs: Some(600),
        };
        let behavior = monitor.infer_behavior();
        assert!(behavior.efficiency_score.is_some_and(|s| s > 60)); // Should be high efficiency
    }

    /// With no input read the monitor infers nothing: the score would start from a
    /// constant and the watt figures are table values, so neither is reported.
    #[test]
    fn test_inference_without_inputs_reports_no_figures() {
        let monitor = PowerProfileMonitor {
            active_profile: PowerProfile::Unknown,
            power_plans: Vec::new(),
            cpu_freq: None,
            charge_policy: ChargePolicy::Unknown,
            inferred: None,
            on_ac_power: None,
            display_brightness: None,
            sleep_timeout_secs: None,
            disk_standby_secs: None,
        };
        let behavior = monitor.infer_behavior();
        assert_eq!(behavior.classification, PowerProfile::Unknown);
        assert_eq!(behavior.confidence, None);
        assert_eq!(behavior.estimated_idle_watts, None);
        assert_eq!(behavior.estimated_max_watts, None);
        assert_eq!(behavior.efficiency_score, None);
        assert!(behavior.recommendations.is_empty());
    }

    /// Captured shape of `pmset -g custom` on a laptop. The battery section comes
    /// last, which is the order that used to let its figures overwrite the mains
    /// ones.
    #[test]
    fn test_pmset_custom_reads_ac_section_only() {
        let text = concat!(
            "System-wide power settings:\n",
            "AC Power:\n",
            "sleep 30\n",
            "disksleep 10\n",
            "Battery Power:\n",
            "sleep 2\n",
            "disksleep 5\n",
        );
        assert_eq!(parse_pmset_custom(text), (Some(1800), Some(600)));
    }

    #[test]
    fn test_pmset_custom_without_ac_section_is_unknown() {
        let text = "Battery Power:\nsleep 2\ndisksleep 5\n";
        assert_eq!(parse_pmset_custom(text), (None, None));
    }

    #[test]
    fn test_pmset_lowpowermode_zero_is_not_balanced() {
        assert_eq!(profile_from_pmset_modes(&["1"]), PowerProfile::PowerSaver);
        assert_eq!(profile_from_pmset_modes(&["0"]), PowerProfile::Unknown);
        assert_eq!(profile_from_pmset_modes(&[]), PowerProfile::Unknown);
    }

    #[test]
    fn test_parse_pmset_power_source() {
        let ac = "Now drawing from 'AC Power'\n -InternalBattery-0 (id=1234)\t100%; charged\n";
        let battery =
            "Now drawing from 'Battery Power'\n -InternalBattery-0 (id=1234)\t72%; discharging\n";
        assert_eq!(parse_pmset_power_source(ac), Some(true));
        assert_eq!(parse_pmset_power_source(battery), Some(false));
        assert_eq!(parse_pmset_power_source(""), None);
        assert_eq!(
            parse_pmset_power_source("Some unrelated text 'AC Power'"),
            None
        );
        assert_eq!(
            parse_pmset_power_source("Now drawing from 'UPS Power'\n"),
            None
        );
    }

    #[test]
    fn test_serialization() {
        let plan = PowerPlanInfo {
            guid: "381b4222-f694-41f0-9685-ff5bb260df2e".into(),
            name: "Balanced".into(),
            active: true,
        };
        let json = serde_json::to_string(&plan).unwrap();
        let _: PowerPlanInfo = serde_json::from_str(&json).unwrap();
    }
}