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
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
// Windows motherboard and system monitoring implementation
//
// Data sources:
// - WMI Win32_BaseBoard - Motherboard information
// - WMI Win32_BIOS - BIOS information
// - WMI Win32_OperatingSystem - OS information
// - WMI Win32_ComputerSystem - System information
// - WMI Win32_PnPSignedDriver - Driver information
// - WMI MSAcpi_ThermalZoneTemperature - ACPI temperatures (if available)
// - WMI Win32_Fan - Fan information (if available)
// - WMI Win32_Processor - CPU information
// - LibreHardwareMonitor/OpenHardwareMonitor WMI (if running)

use super::traits::*;
use serde::Deserialize;
use std::collections::HashMap;
use wmi::{COMLibrary, WMIConnection};

/// Initialize COM and create WMI connection - more robust version
fn create_wmi_connection() -> Result<WMIConnection, Error> {
    // Try multiple strategies to get a working WMI connection

    // Strategy 1: Fresh COM initialization (works best in background threads)
    if let Ok(com) = COMLibrary::new() {
        if let Ok(conn) = WMIConnection::new(com) {
            return Ok(conn);
        }
    }

    // Strategy 2: COM without security init
    if let Ok(com) = COMLibrary::without_security() {
        if let Ok(conn) = WMIConnection::new(com) {
            return Ok(conn);
        }
    }

    // Strategy 3: Assume COM is already initialized by the runtime
    let com = unsafe { COMLibrary::assume_initialized() };
    WMIConnection::new(com).map_err(|e| Error::InitializationFailed(e.to_string()))
}

/// Create WMI connection to a specific namespace
fn create_wmi_connection_namespace(namespace: &str) -> Result<WMIConnection, Error> {
    // Strategy 1: Fresh COM initialization
    if let Ok(com) = COMLibrary::new() {
        if let Ok(conn) = WMIConnection::with_namespace_path(namespace, com) {
            return Ok(conn);
        }
    }

    // Strategy 2: COM without security init
    if let Ok(com) = COMLibrary::without_security() {
        if let Ok(conn) = WMIConnection::with_namespace_path(namespace, com) {
            return Ok(conn);
        }
    }

    // Strategy 3: Assume COM is already initialized
    let com = unsafe { COMLibrary::assume_initialized() };
    WMIConnection::with_namespace_path(namespace, com)
        .map_err(|e| Error::InitializationFailed(e.to_string()))
}

/// LibreHardwareMonitor/OpenHardwareMonitor WMI sensor structure
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct LhmSensor {
    name: Option<String>,
    identifier: Option<String>,
    sensor_type: Option<String>,
    value: Option<f32>,
    min: Option<f32>,
    max: Option<f32>,
    parent: Option<String>,
}

/// LibreHardwareMonitor/OpenHardwareMonitor WMI hardware structure
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct LhmHardware {
    name: Option<String>,
    identifier: Option<String>,
    hardware_type: Option<String>,
    parent: Option<String>,
}

/// Query LibreHardwareMonitor WMI for sensors (if LHM is running)
fn query_lhm_sensors() -> Option<Vec<TemperatureSensor>> {
    // Try LibreHardwareMonitor namespace first
    let namespaces = ["root\\LibreHardwareMonitor", "root\\OpenHardwareMonitor"];

    for namespace in namespaces {
        if let Ok(conn) = create_wmi_connection_namespace(namespace) {
            // Query temperature sensors
            if let Ok(sensors) = conn.raw_query::<LhmSensor>(
                "SELECT Name, Identifier, SensorType, Value, Min, Max, Parent FROM Sensor WHERE SensorType='Temperature'",
            ) {
                if !sensors.is_empty() {
                    let mut temps = Vec::new();
                    for sensor in sensors {
                        if let (Some(name), Some(value)) = (sensor.name, sensor.value) {
                            // Skip invalid readings
                            if value > 0.0 && value < 150.0 {
                                // Determine sensor type from identifier
                                let sensor_type = sensor
                                    .identifier
                                    .as_ref()
                                    .map(|id| {
                                        if id.contains("/cpu") {
                                            SensorType::Cpu
                                        } else if id.contains("/gpu") {
                                            SensorType::Gpu
                                        } else if id.contains("/hdd") || id.contains("/nvme") {
                                            SensorType::Storage
                                        } else {
                                            SensorType::Other
                                        }
                                    })
                                    .unwrap_or(SensorType::Other);

                                temps.push(TemperatureSensor {
                                    label: name,
                                    // A real reading from the provider.
                                    temperature: Some(value),
                                    max: sensor.max,
                                    critical: None,
                                    sensor_type,
                                });
                            }
                        }
                    }
                    if !temps.is_empty() {
                        return Some(temps);
                    }
                }
            }
        }
    }
    None
}

/// Query LibreHardwareMonitor for voltage sensors
fn query_lhm_voltages() -> Option<Vec<VoltageRail>> {
    let namespaces = ["root\\LibreHardwareMonitor", "root\\OpenHardwareMonitor"];

    for namespace in namespaces {
        if let Ok(conn) = create_wmi_connection_namespace(namespace) {
            if let Ok(sensors) = conn.raw_query::<LhmSensor>(
                "SELECT Name, Value, Min, Max FROM Sensor WHERE SensorType='Voltage'",
            ) {
                if !sensors.is_empty() {
                    let mut voltages = Vec::new();
                    for sensor in sensors {
                        if let (Some(name), Some(value)) = (sensor.name, sensor.value) {
                            if value > 0.0 && value < 20.0 {
                                voltages.push(VoltageRail {
                                    label: name,
                                    voltage: Some(value),
                                    min: sensor.min,
                                    max: sensor.max,
                                });
                            }
                        }
                    }
                    if !voltages.is_empty() {
                        return Some(voltages);
                    }
                }
            }
        }
    }
    None
}

/// Query LibreHardwareMonitor for fan sensors
fn query_lhm_fans() -> Option<Vec<FanInfo>> {
    let namespaces = ["root\\LibreHardwareMonitor", "root\\OpenHardwareMonitor"];

    for namespace in namespaces {
        if let Ok(conn) = create_wmi_connection_namespace(namespace) {
            if let Ok(sensors) = conn.raw_query::<LhmSensor>(
                "SELECT Name, Value, Min, Max FROM Sensor WHERE SensorType='Fan'",
            ) {
                if !sensors.is_empty() {
                    let mut fans = Vec::new();
                    for sensor in sensors {
                        if let Some(name) = sensor.name {
                            fans.push(FanInfo {
                                label: name,
                                rpm: sensor.value.map(|v| v as u32),
                                pwm: None,
                                min_rpm: sensor.min.map(|v| v as u32),
                                max_rpm: sensor.max.map(|v| v as u32),
                                controllable: None,
                            });
                        }
                    }
                    if !fans.is_empty() {
                        return Some(fans);
                    }
                }
            }
        }
    }
    None
}

/// Check if LibreHardwareMonitor or OpenHardwareMonitor is running
fn is_lhm_available() -> bool {
    let namespaces = ["root\\LibreHardwareMonitor", "root\\OpenHardwareMonitor"];

    for namespace in namespaces {
        if create_wmi_connection_namespace(namespace).is_ok() {
            return true;
        }
    }
    false
}

/// WMI structures for deserialization

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32BaseBoard {
    manufacturer: Option<String>,
    product: Option<String>,
    version: Option<String>,
    serial_number: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32Bios {
    manufacturer: Option<String>,
    #[serde(rename = "SMBIOSBIOSVersion")]
    smbios_bios_version: Option<String>,
    release_date: Option<String>,
    #[serde(rename = "SystemBiosMajorVersion")]
    system_bios_major_version: Option<u8>,
    #[serde(rename = "SystemBiosMinorVersion")]
    system_bios_minor_version: Option<u8>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32OperatingSystem {
    caption: Option<String>,
    version: Option<String>,
    build_number: Option<String>,
    #[serde(rename = "OSArchitecture")]
    os_architecture: Option<String>,
    #[serde(rename = "CSName")]
    cs_name: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32ComputerSystem {
    manufacturer: Option<String>,
    model: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32Processor {
    name: Option<String>,
    number_of_cores: Option<u32>,
    number_of_logical_processors: Option<u32>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32ComputerSystemProduct {
    #[serde(rename = "UUID")]
    uuid: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename = "MSAcpi_ThermalZoneTemperature")]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct MsAcpiThermalZoneTemperature {
    instance_name: Option<String>,
    current_temperature: Option<u32>, // In tenths of Kelvin
    active: Option<bool>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32PnPSignedDriver {
    device_name: Option<String>,
    driver_version: Option<String>,
    device_class: Option<String>,
    manufacturer: Option<String>,
    driver_date: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32Fan {
    name: Option<String>,
    device_id: Option<String>,
    status: Option<String>,
    active_cooling: Option<bool>,
}

/// WMI structure for PCI devices
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32PnPEntity {
    name: Option<String>,
    device_id: Option<String>,
    manufacturer: Option<String>,
    #[serde(rename = "PNPClass")]
    pnp_class: Option<String>,
    status: Option<String>,
}

/// WMI structure for disk drives
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32DiskDrive {
    caption: Option<String>,
    model: Option<String>,
    serial_number: Option<String>,
    firmware_revision: Option<String>,
    size: Option<u64>,
    interface_type: Option<String>,
    media_type: Option<String>,
    index: Option<u32>,
}

/// WMI structure for disk drive temperatures (via SMART if available)
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct MSStorageDriverFailurePredictData {
    instance_name: Option<String>,
    vendor_specific: Option<Vec<u8>>,
}

/// Windows motherboard sensor implementation using WMI
/// Note: WMI queries are performed on-demand since WMIConnection is not Send + Sync
pub struct WindowsSensor {
    name: String,
}

impl WindowsSensor {
    pub fn new(name: String) -> Self {
        Self { name }
    }
}

impl MotherboardDevice for WindowsSensor {
    fn name(&self) -> &str {
        &self.name
    }

    fn device_path(&self) -> Option<String> {
        if is_lhm_available() {
            Some("LibreHardwareMonitor / OpenHardwareMonitor WMI".to_string())
        } else {
            Some("WMI root\\WMI + root\\CIMV2".to_string())
        }
    }

    fn temperature_sensors(&self) -> Result<Vec<TemperatureSensor>, Error> {
        // First, try LibreHardwareMonitor/OpenHardwareMonitor if running
        if let Some(lhm_temps) = query_lhm_sensors() {
            return Ok(lhm_temps);
        }

        let mut sensors = Vec::new();
        // Failed reads are collected and reported only when they left no sensor at all.
        let mut errors: Vec<String> = Vec::new();

        // First, try Win32_TemperatureProbe in root\CIMV2 (doesn't require admin)
        let cimv2_conn = create_wmi_connection();
        if let Err(e) = &cimv2_conn {
            errors.push(format!("root\\CIMV2 connection: {}", e));
        }
        if let Ok(wmi_cimv2) = cimv2_conn {
            // Win32_TemperatureProbe - standard WMI class
            #[derive(Deserialize, Debug)]
            #[serde(rename_all = "PascalCase")]
            #[allow(dead_code)]
            struct Win32TemperatureProbe {
                description: Option<String>,
                current_reading: Option<i32>, // In tenths of degrees Celsius
                nominal_reading: Option<i32>,
                status: Option<String>,
            }

            let probes = wmi_cimv2.raw_query::<Win32TemperatureProbe>(
                "SELECT Description, CurrentReading, NominalReading, Status FROM Win32_TemperatureProbe",
            );
            if let Err(e) = &probes {
                errors.push(format!("Win32_TemperatureProbe query: {}", e));
            }
            if let Ok(probes) = probes {
                for probe in probes {
                    if let Some(temp_tenths) = probe.current_reading {
                        // Convert from tenths of Celsius
                        let temp_celsius = temp_tenths as f32 / 10.0;
                        if temp_celsius > 0.0 && temp_celsius < 150.0 {
                            sensors.push(TemperatureSensor {
                                label: probe
                                    .description
                                    .unwrap_or_else(|| "Temperature Probe".to_string()),
                                temperature: Some(temp_celsius),
                                max: probe.nominal_reading.map(|r| r as f32 / 10.0),
                                critical: None,
                                sensor_type: SensorType::Other,
                            });
                        }
                    }
                }
            }
        }

        // Try WMI with root\WMI namespace for ACPI thermal zones (may require admin).
        // A failed connection is recorded rather than returned early, so the probes
        // read above still count toward the result.
        let base_conn = create_wmi_connection();
        if let Err(e) = &base_conn {
            errors.push(format!("WMI connection: {}", e));
        }
        // Drop base_conn as we need a different namespace
        drop(base_conn);

        // We need to get the COM library to create a namespace-specific connection
        let com = unsafe { COMLibrary::assume_initialized() };

        // Query MSAcpi_ThermalZoneTemperature (requires admin and WMI namespace root\WMI)
        let thermal_zones = WMIConnection::with_namespace_path("root\\WMI", com)
            .map_err(|e| Error::InitializationFailed(e.to_string()))
            .and_then(|wmi_conn| {
                wmi_conn
                    .raw_query::<MsAcpiThermalZoneTemperature>(
                        "SELECT InstanceName, CurrentTemperature, Active FROM MSAcpi_ThermalZoneTemperature",
                    )
                    .map_err(|e| Error::QueryFailed(e.to_string()))
            });
        match thermal_zones {
            Ok(thermal_zones) => {
                for zone in thermal_zones {
                    if let Some(temp_decikelvin) = zone.current_temperature {
                        // Convert from decikelvin to Celsius: (K/10 - 273.15)
                        let temp_celsius = (temp_decikelvin as f64 / 10.0) - 273.15;

                        // Skip invalid readings (often 0 or very low values)
                        if temp_celsius > 0.0 && temp_celsius < 150.0 {
                            let name = zone
                                .instance_name
                                .unwrap_or_else(|| "ThermalZone".to_string());

                            sensors.push(TemperatureSensor {
                                label: format!("ACPI {}", name),
                                temperature: Some(temp_celsius as f32),
                                // MSAcpi reports no thresholds; none is assumed here.
                                max: None,
                                critical: None,
                                sensor_type: SensorType::Other, // ACPI thermal zone
                            });
                        }
                    }
                }
            }
            Err(e) => {
                // MSAcpi thermal zones often require admin privileges. Recorded, and
                // reported only if no other sensor was read.
                errors.push(format!("MSAcpi_ThermalZoneTemperature: {}", e));
            }
        }

        if sensors.is_empty() && !errors.is_empty() {
            return Err(Error::QueryFailed(errors.join("; ")));
        }

        Ok(sensors)
    }

    fn voltage_rails(&self) -> Result<Vec<VoltageRail>, Error> {
        // Try LibreHardwareMonitor/OpenHardwareMonitor first
        if let Some(lhm_voltages) = query_lhm_voltages() {
            return Ok(lhm_voltages);
        }

        // WMI doesn't provide voltage information directly
        // Would need LibreHardwareMonitor or OpenHardwareMonitor integration
        Ok(Vec::new())
    }

    fn fans(&self) -> Result<Vec<FanInfo>, Error> {
        // Try LibreHardwareMonitor/OpenHardwareMonitor first
        if let Some(lhm_fans) = query_lhm_fans() {
            return Ok(lhm_fans);
        }

        // Fall back to Win32_Fan. Reached only when LibreHardwareMonitor found no
        // fans, so a failed connection here means no fan source could be read at all.
        let wmi_cimv2 = create_wmi_connection()?;

        let mut fans = Vec::new();

        // Query Win32_Fan (rarely populated on most systems). Zero rows is a real
        // answer; a failed query is not, so it is returned rather than read as no fans.
        match wmi_cimv2
            .raw_query::<Win32Fan>("SELECT Name, DeviceID, Status, ActiveCooling FROM Win32_Fan")
        {
            Ok(wmi_fans) => {
                for fan in wmi_fans {
                    fans.push(FanInfo {
                        label: fan.name.unwrap_or_else(|| "System Fan".to_string()),
                        rpm: None, // Win32_Fan doesn't provide RPM
                        pwm: None,
                        min_rpm: None,
                        max_rpm: None,
                        controllable: None, // not read: this query does not fetch fan control state
                    });
                }
            }
            Err(e) => {
                return Err(Error::QueryFailed(format!("Win32_Fan query: {}", e)));
            }
        }

        Ok(fans)
    }
}

/// Enumerate motherboard sensors
pub fn enumerate() -> Result<Vec<Box<dyn MotherboardDevice>>, Error> {
    let mut devices: Vec<Box<dyn MotherboardDevice>> = Vec::new();

    // Get board name for the sensor
    let board_name = get_board_name().unwrap_or_else(|| "System Board".to_string());
    devices.push(Box::new(WindowsSensor::new(board_name)));

    Ok(devices)
}

/// Get the motherboard name from WMI
fn get_board_name() -> Option<String> {
    let wmi_conn = create_wmi_connection().ok()?;

    let boards: Vec<Win32BaseBoard> = wmi_conn
        .raw_query("SELECT Manufacturer, Product FROM Win32_BaseBoard")
        .ok()?;

    boards
        .first()
        .and_then(|b| match (&b.manufacturer, &b.product) {
            (Some(mfr), Some(prod)) => Some(format!("{} {}", mfr, prod)),
            (None, Some(prod)) => Some(prod.clone()),
            (Some(mfr), None) => Some(mfr.clone()),
            (None, None) => None,
        })
}

/// Get system information via WMI
pub fn get_system_info() -> Result<SystemInfo, Error> {
    let wmi_conn = create_wmi_connection()?;

    // Query Win32_OperatingSystem
    let os_info: Option<Win32OperatingSystem> = wmi_conn
        .raw_query::<Win32OperatingSystem>(
            "SELECT Caption, Version, BuildNumber, OSArchitecture, CSName FROM Win32_OperatingSystem",
        )
        .ok()
        .and_then(|v: Vec<Win32OperatingSystem>| v.into_iter().next());

    // Query Win32_BIOS
    let bios_info: Option<Win32Bios> = wmi_conn
        .raw_query::<Win32Bios>(
            "SELECT Manufacturer, SMBIOSBIOSVersion, ReleaseDate, SystemBiosMajorVersion, SystemBiosMinorVersion FROM Win32_BIOS",
        )
        .ok()
        .and_then(|v: Vec<Win32Bios>| v.into_iter().next());

    // Query Win32_ComputerSystem
    let cs_info: Option<Win32ComputerSystem> = wmi_conn
        .raw_query::<Win32ComputerSystem>("SELECT Manufacturer, Model FROM Win32_ComputerSystem")
        .ok()
        .and_then(|v: Vec<Win32ComputerSystem>| v.into_iter().next());

    // Query Win32_BaseBoard
    let bb_info: Option<Win32BaseBoard> = wmi_conn
        .raw_query::<Win32BaseBoard>(
            "SELECT Manufacturer, Product, Version, SerialNumber FROM Win32_BaseBoard",
        )
        .ok()
        .and_then(|v: Vec<Win32BaseBoard>| v.into_iter().next());

    // Query Win32_Processor
    let proc_info: Option<Win32Processor> = wmi_conn
        .raw_query::<Win32Processor>(
            "SELECT Name, NumberOfCores, NumberOfLogicalProcessors FROM Win32_Processor",
        )
        .ok()
        .and_then(|v: Vec<Win32Processor>| v.into_iter().next());

    // Query Win32_ComputerSystemProduct for UUID
    let csp_info: Option<Win32ComputerSystemProduct> = wmi_conn
        .raw_query::<Win32ComputerSystemProduct>("SELECT UUID FROM Win32_ComputerSystemProduct")
        .ok()
        .and_then(|v: Vec<Win32ComputerSystemProduct>| v.into_iter().next());

    // Build BIOS info
    let bios = BiosInfo {
        vendor: bios_info.as_ref().and_then(|b| b.manufacturer.clone()),
        version: bios_info
            .as_ref()
            .and_then(|b| b.smbios_bios_version.clone()),
        release_date: bios_info.as_ref().and_then(|b| {
            // WMI date format: YYYYMMDDHHMMSS.mmmmmm+UUU
            b.release_date.as_ref().map(|d| {
                if d.len() >= 8 {
                    format!("{}-{}-{}", &d[0..4], &d[4..6], &d[6..8])
                } else {
                    d.clone()
                }
            })
        }),
        revision: bios_info.as_ref().and_then(|b| {
            match (b.system_bios_major_version, b.system_bios_minor_version) {
                (Some(major), Some(minor)) => Some(format!("{}.{}", major, minor)),
                _ => None,
            }
        }),
        firmware_type: detect_firmware_type(),
        secure_boot: detect_secure_boot(),
    };

    // Win32_OperatingSystem.OSArchitecture, as WMI reports it (e.g. "64-bit").
    // Absent when that query failed. This used to fall through to
    // Win32_ComputerSystem.SystemType, which is "x64-based PC" and so is a
    // different thing, and then to the compile-time architecture of the binary.
    let architecture = os_info.as_ref().and_then(|o| o.os_architecture.clone());

    // Build OS version string
    let os_version = os_info
        .as_ref()
        .and_then(|o| match (&o.version, &o.build_number) {
            (Some(ver), Some(build)) => Some(format!("{} (Build {})", ver, build)),
            (Some(ver), None) => Some(ver.clone()),
            _ => None,
        })
        .filter(|v| !v.is_empty());

    Ok(SystemInfo {
        // Absent when the query failed. This used to fall back to the literal
        // "Windows".
        os_name: os_info.as_ref().and_then(|o| o.caption.clone()),
        os_version,
        kernel_version: os_info.as_ref().and_then(|o| o.version.clone()),
        architecture,
        hostname: os_info.as_ref().and_then(|o| o.cs_name.clone()),
        bios,
        manufacturer: cs_info.as_ref().and_then(|c| c.manufacturer.clone()),
        product_name: cs_info.as_ref().and_then(|c| c.model.clone()),
        serial_number: bb_info.as_ref().and_then(|b| b.serial_number.clone()),
        uuid: csp_info.and_then(|c| c.uuid),
        board_vendor: bb_info.as_ref().and_then(|b| b.manufacturer.clone()),
        board_name: bb_info.as_ref().and_then(|b| b.product.clone()),
        board_version: bb_info.as_ref().and_then(|b| b.version.clone()),
        cpu_name: proc_info.as_ref().and_then(|p| p.name.clone()),
        cpu_cores: proc_info.as_ref().and_then(|p| p.number_of_cores),
        cpu_threads: proc_info
            .as_ref()
            .and_then(|p| p.number_of_logical_processors),
    })
}

/// Detect firmware type (UEFI vs Legacy BIOS), from `GetFirmwareType`.
///
/// When that call fails this is `Unknown`. This used to answer UEFI for any machine
/// where the environment variable, registry key and `C:\EFI` probes all missed,
/// which was every machine that did not match them, so Legacy BIOS was never
/// reported. The SecureBoot registry key is not evidence of firmware type either.
fn detect_firmware_type() -> FirmwareType {
    use crate::boot_config::BootType;
    match crate::platform::windows::firmware_type() {
        Some(BootType::Uefi | BootType::SecureBoot) => FirmwareType::Uefi,
        Some(BootType::Legacy) => FirmwareType::Bios,
        Some(BootType::Unknown) | None => FirmwareType::Unknown,
    }
}

/// Detect Secure Boot status
fn detect_secure_boot() -> Option<bool> {
    use winreg::enums::*;
    use winreg::RegKey;

    // Try to read Secure Boot state from registry
    if let Ok(hklm) = RegKey::predef(HKEY_LOCAL_MACHINE)
        .open_subkey("SYSTEM\\CurrentControlSet\\Control\\SecureBoot\\State")
    {
        if let Ok(value) = hklm.get_value::<u32, _>("UEFISecureBootEnabled") {
            return Some(value != 0);
        }
    }

    None
}

/// Get driver versions via WMI
/// Kernel-mode drivers currently in the running state, as `(name, state)` pairs.
///
/// One WMI query over the shared COM connection. The caller previously spawned
/// PowerShell to run the same query and emit JSON, which cost roughly a second.
pub fn get_running_drivers() -> Result<Vec<(String, String)>, Error> {
    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "PascalCase")]
    struct Win32SystemDriver {
        name: Option<String>,
        state: Option<String>,
    }

    let wmi_conn = create_wmi_connection()?;
    let rows: Vec<Win32SystemDriver> = wmi_conn
        .raw_query("SELECT Name, State FROM Win32_SystemDriver WHERE State = 'Running'")
        .map_err(|e| Error::QueryFailed(e.to_string()))?;

    Ok(rows
        .into_iter()
        .filter_map(|d| {
            let name = d.name?;
            // A driver with no name identifies nothing, so it is dropped rather than
            // listed as an empty entry.
            if name.trim().is_empty() {
                return None;
            }
            Some((name, d.state.unwrap_or_default()))
        })
        .collect())
}

pub fn get_driver_versions() -> Result<Vec<DriverInfo>, Error> {
    let wmi_conn = create_wmi_connection()?;

    let mut drivers = Vec::new();
    // Failed queries are collected here. They are reported only when they left no
    // driver to return, so a partial list is still a reading.
    let mut errors: Vec<String> = Vec::new();

    // Query specific driver classes that are most useful
    let driver_classes = ["Display", "Net", "DiskDrive", "USB", "Processor"];

    for class in driver_classes {
        let query = format!(
            "SELECT DeviceName, DriverVersion, DeviceClass, Manufacturer, DriverDate FROM Win32_PnPSignedDriver WHERE DeviceClass = '{}'",
            class
        );

        match wmi_conn.raw_query::<Win32PnPSignedDriver>(&query) {
            Ok(class_drivers) => {
                for driver in class_drivers {
                    if let Some(name) = driver.device_name {
                        let driver_type = match class {
                            "Display" => DriverType::Gpu,
                            "Net" => DriverType::Network,
                            "DiskDrive" => DriverType::Storage,
                            "USB" => DriverType::Usb,
                            "Processor" => DriverType::Chipset,
                            _ => DriverType::Other,
                        };

                        // Parse WMI date format to readable format
                        let date = driver.driver_date.map(|d| {
                            if d.len() >= 8 {
                                format!("{}-{}-{}", &d[0..4], &d[4..6], &d[6..8])
                            } else {
                                d
                            }
                        });

                        drivers.push(DriverInfo {
                            name,
                            version: driver.driver_version.filter(|v| !v.trim().is_empty()),
                            driver_type,
                            description: None,
                            vendor: driver.manufacturer,
                            date,
                        });
                    }
                }
            }
            Err(e) => {
                // Recorded rather than dropped. Reported only if no driver was read.
                errors.push(format!("{} drivers query: {}", class, e));
            }
        }
    }

    // Also get any driver with NVIDIA, AMD, or Intel in the name (GPU drivers)
    let gpu_query = "SELECT DeviceName, DriverVersion, DeviceClass, Manufacturer, DriverDate FROM Win32_PnPSignedDriver WHERE DeviceName LIKE '%NVIDIA%' OR DeviceName LIKE '%AMD%' OR DeviceName LIKE '%Intel%'";

    let gpu_drivers = wmi_conn.raw_query::<Win32PnPSignedDriver>(gpu_query);
    if let Err(e) = &gpu_drivers {
        errors.push(format!("GPU driver query: {}", e));
    }
    if let Ok(gpu_drivers) = gpu_drivers {
        for driver in gpu_drivers {
            if let Some(name) = driver.device_name {
                // Skip if we already have this driver
                if drivers.iter().any(|d| d.name == name) {
                    continue;
                }

                drivers.push(DriverInfo {
                    name,
                    version: driver.driver_version.filter(|v| !v.trim().is_empty()),
                    driver_type: DriverType::Gpu,
                    description: None,
                    vendor: driver.manufacturer,
                    date: driver.driver_date.map(|d| {
                        if d.len() >= 8 {
                            format!("{}-{}-{}", &d[0..4], &d[4..6], &d[6..8])
                        } else {
                            d
                        }
                    }),
                });
            }
        }
    }

    // Errors are returned only when they left nothing to report. A partial list from
    // the queries that did answer is still a reading.
    if drivers.is_empty() && !errors.is_empty() {
        return Err(Error::QueryFailed(errors.join("; ")));
    }

    Ok(drivers)
}

/// Get PCIe devices via WMI
pub fn get_pcie_devices() -> Result<Vec<PcieDeviceInfo>, Error> {
    let wmi_conn = create_wmi_connection()?;
    let mut devices = Vec::new();

    // Query PCI devices that are connected via PCIe
    // Look for devices with PCI in their device ID
    let query = "SELECT Name, DeviceID, Manufacturer, PNPClass, Status FROM Win32_PnPEntity WHERE DeviceID LIKE 'PCI%'";

    if let Ok(pci_devices) = wmi_conn.raw_query::<Win32PnPEntity>(query) {
        for device in pci_devices {
            if let Some(name) = device.name {
                // Parse device ID for vendor/device info
                // Format: PCI\VEN_XXXX&DEV_YYYY&SUBSYS_ZZZZZZZZ&REV_RR
                let (vendor_id, device_id_hex) = if let Some(ref dev_id) = device.device_id {
                    let parts: Vec<&str> = dev_id.split('\\').collect();
                    if parts.len() >= 2 {
                        let id_part = parts[1];
                        let vendor = id_part
                            .split('&')
                            .find(|p| p.starts_with("VEN_"))
                            .map(|v| v.trim_start_matches("VEN_").to_string());
                        let dev = id_part
                            .split('&')
                            .find(|p| p.starts_with("DEV_"))
                            .map(|d| d.trim_start_matches("DEV_").to_string());
                        (vendor, dev)
                    } else {
                        (None, None)
                    }
                } else {
                    (None, None)
                };

                // Determine device class
                let device_class = device.pnp_class.clone().or_else(|| {
                    // Infer from name
                    let name_lower = name.to_lowercase();
                    if name_lower.contains("vga")
                        || name_lower.contains("display")
                        || name_lower.contains("graphics")
                    {
                        Some("Display".to_string())
                    } else if name_lower.contains("ethernet")
                        || name_lower.contains("network")
                        || name_lower.contains("wifi")
                    {
                        Some("Network".to_string())
                    } else if name_lower.contains("nvme")
                        || name_lower.contains("ssd")
                        || name_lower.contains("ahci")
                    {
                        Some("Storage".to_string())
                    } else if name_lower.contains("usb") {
                        Some("USB".to_string())
                    } else if name_lower.contains("audio") || name_lower.contains("sound") {
                        Some("Audio".to_string())
                    } else {
                        None
                    }
                });

                devices.push(PcieDeviceInfo {
                    name,
                    device_id: device_id_hex,
                    vendor: device.manufacturer.or(vendor_id),
                    pcie_version: None, // WMI doesn't directly expose PCIe version
                    link_width: None,   // Would need to query via SetupAPI
                    link_speed: None,
                    slot: None,
                    device_class,
                });
            }
        }
    }

    Ok(devices)
}

/// Get SATA/storage devices via WMI
pub fn get_sata_devices() -> Result<Vec<SataDeviceInfo>, Error> {
    let wmi_conn = create_wmi_connection()?;
    let mut devices = Vec::new();

    // Query disk drives
    let query = "SELECT Caption, Model, SerialNumber, FirmwareRevision, Size, InterfaceType, MediaType, Index FROM Win32_DiskDrive";

    if let Ok(disk_drives) = wmi_conn.raw_query::<Win32DiskDrive>(query) {
        for disk in disk_drives {
            let name = disk.caption.unwrap_or_else(|| {
                disk.model
                    .clone()
                    .unwrap_or_else(|| "Unknown Disk".to_string())
            });

            // Determine if it's SATA based on interface
            let interface = disk.interface_type.as_deref().unwrap_or("");
            let interface_speed = match interface.to_uppercase().as_str() {
                "IDE" | "SCSI" | "SATA" => Some("SATA".to_string()),
                "USB" => Some("USB".to_string()),
                "NVME" => Some("NVMe".to_string()),
                _ => disk.interface_type.clone(),
            };

            // Determine media type
            let media_type = match disk.media_type.as_deref().unwrap_or("") {
                s if s.contains("SSD") || s.contains("Solid") => SataMediaType::Ssd,
                s if s.contains("Fixed") || s.contains("HDD") => {
                    // Check model name for SSD hints
                    let model = disk.model.as_deref().unwrap_or("");
                    if model.to_uppercase().contains("SSD") || model.to_uppercase().contains("NVME")
                    {
                        SataMediaType::Ssd
                    } else {
                        SataMediaType::Hdd
                    }
                }
                _ => SataMediaType::Unknown,
            };

            // Convert size to GB
            let capacity_gb = disk.size.map(|s| s as f64 / 1_000_000_000.0);

            devices.push(SataDeviceInfo {
                name,
                model: disk.model,
                serial: disk.serial_number.map(|s| s.trim().to_string()),
                firmware: disk.firmware_revision,
                capacity_gb,
                interface_speed,
                port: disk.index.map(|i| i as u8),
                temperature: None, // Would need SMART data access
                media_type,
            });
        }
    }

    Ok(devices)
}

/// Get system temperatures from various sources
pub fn get_system_temperatures() -> Result<SystemTemperatures, Error> {
    use crate::hwmon::{self, HwSensorType, HwType};

    let mut cpu_temp: Option<f32> = None;
    let mut gpu_temp: Option<f32> = None;
    let mut mb_temp: Option<f32> = None;
    let mut storage_temps: Vec<(String, f32)> = Vec::new();

    // First, try our native hwmon implementation
    let monitor = hwmon::HardwareMonitor::new();
    let temps = monitor.temperatures();

    for sensor in &temps {
        match (sensor.sensor_type, sensor.hardware_type) {
            (HwSensorType::Temperature, HwType::Cpu) => {
                // Prefer package/Tctl temp, otherwise use first CPU temp
                if cpu_temp.is_none()
                    || sensor.name.to_lowercase().contains("package")
                    || sensor.name.to_lowercase().contains("tctl")
                {
                    cpu_temp = Some(sensor.value);
                }
            }
            (HwSensorType::Temperature, HwType::Gpu) => {
                if gpu_temp.is_none() {
                    gpu_temp = Some(sensor.value);
                }
            }
            (HwSensorType::Temperature, HwType::Storage) => {
                storage_temps.push((sensor.name.clone(), sensor.value));
            }
            (HwSensorType::Temperature, HwType::Motherboard) if mb_temp.is_none() => {
                mb_temp = Some(sensor.value);
            }
            _ => {}
        }
    }

    // If we got data from hwmon, return it
    if cpu_temp.is_some() || gpu_temp.is_some() || !storage_temps.is_empty() {
        return Ok(SystemTemperatures {
            cpu: cpu_temp,
            gpu: gpu_temp,
            motherboard: mb_temp,
            storage: storage_temps,
            network: Vec::new(),
        });
    }

    // Second fallback: try LibreHardwareMonitor/OpenHardwareMonitor if running
    if let Some(lhm_temps) = query_lhm_sensors() {
        for sensor in &lhm_temps {
            match sensor.sensor_type {
                SensorType::Cpu => {
                    // Use first CPU temp or "CPU Package" if available
                    if cpu_temp.is_none()
                        || sensor.label.to_lowercase().contains("package")
                        || sensor.label.to_lowercase().contains("tctl")
                    {
                        // Propagates absence: a sensor that could not be read
                        // leaves the summary without a CPU temperature rather
                        // than reporting one it does not have.
                        cpu_temp = sensor.temperature;
                    }
                }
                SensorType::Gpu => {
                    if gpu_temp.is_none() {
                        gpu_temp = sensor.temperature;
                    }
                }
                SensorType::Storage => {
                    if let Some(celsius) = sensor.temperature {
                        storage_temps.push((sensor.label.clone(), celsius));
                    }
                }
                SensorType::Other
                    // Check for motherboard sensor
                    if (sensor.label.to_lowercase().contains("system")
                        || sensor.label.to_lowercase().contains("motherboard")
                        || sensor.label.to_lowercase().contains("mainboard"))
                        && mb_temp.is_none() => {
                            mb_temp = sensor.temperature;
                        }
                _ => {}
            }
        }

        // If we got data from LHM, return it (still try NVML for GPU if needed)
        if cpu_temp.is_some() || !storage_temps.is_empty() {
            // Still try NVML if no GPU temp from LHM
            if gpu_temp.is_none() {
                #[cfg(feature = "nvidia")]
                {
                    use nvml_wrapper::Nvml;
                    if let Ok(nvml) = Nvml::init() {
                        if let Ok(device) = nvml.device_by_index(0) {
                            if let Ok(temp) = device.temperature(
                                nvml_wrapper::enum_wrappers::device::TemperatureSensor::Gpu,
                            ) {
                                gpu_temp = Some(temp as f32);
                            }
                        }
                    }
                }
            }

            return Ok(SystemTemperatures {
                cpu: cpu_temp,
                gpu: gpu_temp,
                motherboard: mb_temp,
                storage: storage_temps,
                network: Vec::new(),
            });
        }
    }

    // Third fallback: WMI ACPI thermal zones for CPU temp
    if let Ok(_base_conn) = create_wmi_connection() {
        drop(_base_conn);
        let com = unsafe { COMLibrary::assume_initialized() };

        if let Ok(wmi_wmi) = WMIConnection::with_namespace_path("root\\WMI", com) {
            if let Ok(thermal_zones) = wmi_wmi.raw_query::<MsAcpiThermalZoneTemperature>(
                "SELECT InstanceName, CurrentTemperature FROM MSAcpi_ThermalZoneTemperature",
            ) {
                for zone in thermal_zones {
                    // An ACPI zone measures whatever the firmware put it on. Only a
                    // zone whose name says CPU is reported as the CPU; taking the
                    // first zone passed a chassis or PCH reading off as one.
                    let names_cpu = zone
                        .instance_name
                        .as_deref()
                        .is_some_and(|name| name.to_ascii_uppercase().contains("CPU"));
                    if !names_cpu {
                        continue;
                    }
                    if let Some(temp_decikelvin) = zone.current_temperature {
                        let temp_celsius = (temp_decikelvin as f64 / 10.0) - 273.15;
                        if temp_celsius > 0.0 && temp_celsius < 150.0 && cpu_temp.is_none() {
                            cpu_temp = Some(temp_celsius as f32);
                        }
                    }
                }
            }
        }
    }

    // Try to get GPU temperature from NVML
    #[cfg(feature = "nvidia")]
    {
        use nvml_wrapper::Nvml;
        if let Ok(nvml) = Nvml::init() {
            if let Ok(device) = nvml.device_by_index(0) {
                if let Ok(temp) =
                    device.temperature(nvml_wrapper::enum_wrappers::device::TemperatureSensor::Gpu)
                {
                    gpu_temp = Some(temp as f32);
                }
            }
        }
    }

    Ok(SystemTemperatures {
        cpu: cpu_temp,
        gpu: gpu_temp,
        motherboard: mb_temp,
        storage: storage_temps,
        network: Vec::new(),
    })
}

/// WMI structure for USB devices
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32UsbHub {
    name: Option<String>,
    device_id: Option<String>,
    #[serde(rename = "PNPDeviceID")]
    pnp_device_id: Option<String>,
    status: Option<String>,
}

/// WMI structure for USB controllers
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32UsbController {
    name: Option<String>,
    device_id: Option<String>,
    manufacturer: Option<String>,
    #[serde(rename = "PNPDeviceID")]
    pnp_device_id: Option<String>,
    status: Option<String>,
}

/// WMI structure for video controllers (for display output info)
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32VideoController {
    name: Option<String>,
    adapter_compatibility: Option<String>,
    video_processor: Option<String>,
    current_horizontal_resolution: Option<u32>,
    current_vertical_resolution: Option<u32>,
    current_refresh_rate: Option<u32>,
    status: Option<String>,
}

/// WMI structure for monitors
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32DesktopMonitor {
    name: Option<String>,
    monitor_manufacturer: Option<String>,
    monitor_type: Option<String>,
    screen_width: Option<u32>,
    screen_height: Option<u32>,
}

/// WMI structure for sound devices
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32SoundDevice {
    name: Option<String>,
    manufacturer: Option<String>,
    status: Option<String>,
    device_id: Option<String>,
    #[serde(rename = "PNPDeviceID")]
    pnp_device_id: Option<String>,
}

/// WMI structure for network adapters
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32NetworkAdapterConfig {
    description: Option<String>,
    #[serde(rename = "MACAddress")]
    mac_address: Option<String>,
    #[serde(rename = "IPAddress")]
    ip_address: Option<Vec<String>>,
    #[serde(rename = "IPEnabled")]
    ip_enabled: Option<bool>,
    #[serde(rename = "Index")]
    index: Option<u32>,
}

/// WMI structure for the adapter's link state. `Index` matches a configuration
/// row to its adapter.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32NetworkAdapter {
    index: Option<u32>,
    net_connection_status: Option<u16>,
}

/// Get all peripherals information
pub fn get_peripherals() -> Result<PeripheralsInfo, Error> {
    let wmi_conn = create_wmi_connection()?;

    Ok(PeripheralsInfo {
        usb_devices: get_usb_devices(&wmi_conn),
        display_outputs: get_display_outputs(&wmi_conn),
        audio_devices: get_audio_devices(&wmi_conn),
        network_ports: get_network_ports(&wmi_conn),
        ..Default::default()
    })
}

/// Get USB devices from WMI
fn get_usb_devices(wmi_conn: &WMIConnection) -> Vec<UsbDeviceInfo> {
    let mut devices = Vec::new();

    // Query USB controllers to understand USB versions
    let controllers_query =
        "SELECT Name, DeviceID, Manufacturer, PNPDeviceID, Status FROM Win32_USBController";
    if let Ok(controllers) = wmi_conn.raw_query::<Win32UsbController>(controllers_query) {
        for controller in controllers {
            if let Some(name) = controller.name {
                // Determine USB version from controller name
                let usb_version = detect_usb_version(&name);

                devices.push(UsbDeviceInfo {
                    name,
                    device_id: controller.device_id,
                    vendor: controller.manufacturer,
                    product_id: None,
                    vendor_id: extract_vendor_id(&controller.pnp_device_id),
                    usb_version,
                    device_class: Some("Controller".to_string()),
                    status: controller.status,
                    hub_port: None,
                });
            }
        }
    }

    // Query USB hubs
    let hubs_query = "SELECT Name, DeviceID, PNPDeviceID, Status FROM Win32_USBHub";
    if let Ok(hubs) = wmi_conn.raw_query::<Win32UsbHub>(hubs_query) {
        for hub in hubs {
            if let Some(name) = hub.name {
                let usb_version = detect_usb_version(&name);

                devices.push(UsbDeviceInfo {
                    name,
                    device_id: hub.device_id,
                    vendor: None,
                    product_id: None,
                    vendor_id: extract_vendor_id(&hub.pnp_device_id),
                    usb_version,
                    device_class: Some("Hub".to_string()),
                    status: hub.status,
                    hub_port: None,
                });
            }
        }
    }

    // Query connected USB devices via PnP
    let pnp_query = "SELECT Name, DeviceID, Manufacturer, PNPClass, Status FROM Win32_PnPEntity WHERE DeviceID LIKE 'USB%' AND PNPClass != 'USB'";
    if let Ok(pnp_devices) = wmi_conn.raw_query::<Win32PnPEntity>(pnp_query) {
        for device in pnp_devices {
            if let Some(name) = device.name {
                // Skip controllers and hubs we already have
                if name.to_lowercase().contains("controller") || name.to_lowercase().contains("hub")
                {
                    continue;
                }

                let usb_version = detect_usb_version(&name);

                devices.push(UsbDeviceInfo {
                    name,
                    device_id: device.device_id.clone(),
                    vendor: device.manufacturer,
                    product_id: None,
                    vendor_id: extract_vendor_id(&device.device_id),
                    usb_version,
                    device_class: device.pnp_class,
                    status: device.status,
                    hub_port: None,
                });
            }
        }
    }

    devices
}

/// Detect USB version from device name
fn detect_usb_version(name: &str) -> UsbVersion {
    let name_lower = name.to_lowercase();

    if name_lower.contains("usb4") || name_lower.contains("usb 4") {
        UsbVersion::Usb4
    } else if name_lower.contains("3.2") || name_lower.contains("superspeedplus") {
        UsbVersion::Usb3_2
    } else if name_lower.contains("3.1") {
        UsbVersion::Usb3_1
    } else if name_lower.contains("3.0")
        || name_lower.contains("xhci")
        || name_lower.contains("superspeed")
    {
        UsbVersion::Usb3_0
    } else if name_lower.contains("2.0")
        || name_lower.contains("ehci")
        || name_lower.contains("enhanced")
    {
        UsbVersion::Usb2_0
    } else if name_lower.contains("1.1")
        || name_lower.contains("uhci")
        || name_lower.contains("ohci")
    {
        UsbVersion::Usb1_1
    } else {
        UsbVersion::Unknown
    }
}

/// Extract vendor ID from PNP device ID
fn extract_vendor_id(device_id: &Option<String>) -> Option<String> {
    device_id.as_ref().and_then(|id| {
        // Format: USB\VID_XXXX&PID_YYYY\...
        id.split('\\').nth(1).and_then(|part| {
            part.split('&')
                .find(|p| p.starts_with("VID_"))
                .map(|v| v.trim_start_matches("VID_").to_string())
        })
    })
}

/// Get display outputs from WMI
fn get_display_outputs(wmi_conn: &WMIConnection) -> Vec<DisplayOutputInfo> {
    let mut outputs = Vec::new();

    // Query video controllers
    let video_query = "SELECT Name, AdapterCompatibility, VideoProcessor, CurrentHorizontalResolution, CurrentVerticalResolution, CurrentRefreshRate, Status FROM Win32_VideoController";
    if let Ok(controllers) = wmi_conn.raw_query::<Win32VideoController>(video_query) {
        for controller in controllers {
            let name = controller
                .name
                .unwrap_or_else(|| "Unknown Display Adapter".to_string());

            // Infer output type from adapter name
            let output_type = detect_display_output_type(&name);

            let resolution = match (
                controller.current_horizontal_resolution,
                controller.current_vertical_resolution,
            ) {
                (Some(w), Some(h)) => Some(format!("{}x{}", w, h)),
                _ => None,
            };

            outputs.push(DisplayOutputInfo {
                name: name.clone(),
                output_type,
                connected: controller.status.as_deref() == Some("OK"),
                resolution,
                refresh_rate: controller.current_refresh_rate,
                adapter: controller.adapter_compatibility.or(Some(name)),
            });
        }
    }

    // Query monitors for additional info
    let monitor_query = "SELECT Name, MonitorManufacturer, MonitorType, ScreenWidth, ScreenHeight FROM Win32_DesktopMonitor";
    if let Ok(monitors) = wmi_conn.raw_query::<Win32DesktopMonitor>(monitor_query) {
        for monitor in monitors {
            let name = monitor.name.unwrap_or_else(|| "Monitor".to_string());
            let output_type = detect_display_output_type(&name);

            let resolution = match (monitor.screen_width, monitor.screen_height) {
                (Some(w), Some(h)) if w > 0 && h > 0 => Some(format!("{}x{}", w, h)),
                _ => None,
            };

            // Only add if we don't already have this from video controllers
            if !outputs
                .iter()
                .any(|o| o.resolution == resolution && resolution.is_some())
            {
                outputs.push(DisplayOutputInfo {
                    name,
                    output_type,
                    connected: true,
                    resolution,
                    refresh_rate: None,
                    adapter: monitor.monitor_manufacturer,
                });
            }
        }
    }

    outputs
}

/// Detect display output type from name
fn detect_display_output_type(name: &str) -> DisplayOutputType {
    let name_lower = name.to_lowercase();

    if name_lower.contains("hdmi") {
        DisplayOutputType::Hdmi
    } else if name_lower.contains("displayport") || name_lower.contains("dp") {
        DisplayOutputType::DisplayPort
    } else if name_lower.contains("dvi") {
        DisplayOutputType::Dvi
    } else if name_lower.contains("vga") {
        DisplayOutputType::Vga
    } else if name_lower.contains("thunderbolt") {
        DisplayOutputType::Thunderbolt
    } else if name_lower.contains("usb-c") || name_lower.contains("type-c") {
        DisplayOutputType::UsbC
    } else if name_lower.contains("internal")
        || name_lower.contains("laptop")
        || name_lower.contains("built-in")
    {
        DisplayOutputType::Internal
    } else {
        DisplayOutputType::Unknown
    }
}

/// Get audio devices from WMI
fn get_audio_devices(wmi_conn: &WMIConnection) -> Vec<AudioDeviceInfo> {
    let mut devices = Vec::new();

    let audio_query =
        "SELECT Name, Manufacturer, Status, DeviceID, PNPDeviceID FROM Win32_SoundDevice";
    if let Ok(sound_devices) = wmi_conn.raw_query::<Win32SoundDevice>(audio_query) {
        for device in sound_devices {
            let name = device.name.unwrap_or_else(|| "Audio Device".to_string());

            // Direction is not read. `Win32_SoundDevice` carries no data-flow field
            // (input or output), so `None`. This used to be guessed from the name
            // ("microphone", "speaker", ...), which is not a reading of the device.
            let device_type = None;

            devices.push(AudioDeviceInfo {
                name,
                device_type,
                manufacturer: device.manufacturer,
                status: device.status,
                is_default: false, // Would need additional API to determine
            });
        }
    }

    devices
}

/// Map `Win32_NetworkAdapter.NetConnectionStatus` to a link state. Only 2 (Connected),
/// 0 (Disconnected) and 7 (Media disconnected) are a reading of the link. Other
/// values, such as connecting, authenticating or hardware disabled, do not say
/// whether it is up.
fn link_state_from_status(status: Option<u16>) -> Option<bool> {
    match status {
        Some(2) => Some(true),
        Some(0 | 7) => Some(false),
        _ => None,
    }
}

/// Get network ports from WMI
fn get_network_ports(wmi_conn: &WMIConnection) -> Vec<NetworkPortInfo> {
    let mut ports = Vec::new();

    // Link state comes from Win32_NetworkAdapter, matched by Index. IPEnabled is an
    // IP-configuration flag, not a link state, so it is not used for `connected`.
    let mut net_status = HashMap::new();
    let link_query = "SELECT Index, NetConnectionStatus FROM Win32_NetworkAdapter";
    if let Ok(adapters) = wmi_conn.raw_query::<Win32NetworkAdapter>(link_query) {
        for adapter in adapters {
            if let (Some(index), Some(status)) = (adapter.index, adapter.net_connection_status) {
                net_status.insert(index, status);
            }
        }
    }

    // Query network adapters
    let net_query = "SELECT Description, MACAddress, IPAddress, IPEnabled, Index FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True";
    if let Ok(adapters) = wmi_conn.raw_query::<Win32NetworkAdapterConfig>(net_query) {
        for adapter in adapters {
            let name = adapter
                .description
                .unwrap_or_else(|| "Network Adapter".to_string());

            let port_type = detect_network_port_type(&name);
            let speed = detect_network_speed(&name);

            ports.push(NetworkPortInfo {
                name,
                port_type,
                speed,
                mac_address: adapter.mac_address,
                // No matching adapter, or no status it maps from, leaves the link unread
                connected: adapter
                    .index
                    .and_then(|index| link_state_from_status(net_status.get(&index).copied())),
            });
        }
    }

    ports
}

/// Detect network port type from name
fn detect_network_port_type(name: &str) -> NetworkPortType {
    let name_lower = name.to_lowercase();

    if name_lower.contains("wifi")
        || name_lower.contains("wi-fi")
        || name_lower.contains("wireless")
        || name_lower.contains("802.11")
    {
        NetworkPortType::WiFi
    } else if name_lower.contains("bluetooth") {
        NetworkPortType::Bluetooth
    } else if name_lower.contains("thunderbolt") {
        NetworkPortType::Thunderbolt
    } else if name_lower.contains("ethernet")
        || name_lower.contains("realtek")
        || name_lower.contains("intel")
        || name_lower.contains("gigabit")
    {
        NetworkPortType::Ethernet
    } else {
        NetworkPortType::Other
    }
}

/// Detect network speed from adapter name
fn detect_network_speed(name: &str) -> Option<String> {
    let name_lower = name.to_lowercase();

    if name_lower.contains("10gbe") || name_lower.contains("10 gigabit") {
        Some("10 Gbps".to_string())
    } else if name_lower.contains("5gbe") || name_lower.contains("5 gigabit") {
        Some("5 Gbps".to_string())
    } else if name_lower.contains("2.5gbe") || name_lower.contains("2.5 gigabit") {
        Some("2.5 Gbps".to_string())
    } else if name_lower.contains("gigabit")
        || name_lower.contains("gbe")
        || name_lower.contains("1000")
    {
        Some("1 Gbps".to_string())
    } else if name_lower.contains("fast ethernet") || name_lower.contains("100") {
        Some("100 Mbps".to_string())
    } else if name_lower.contains("wifi 6e") || name_lower.contains("ax") {
        Some("Wi-Fi 6E".to_string())
    } else if name_lower.contains("wifi 6") || name_lower.contains("802.11ax") {
        Some("Wi-Fi 6".to_string())
    } else if name_lower.contains("wifi 5") || name_lower.contains("802.11ac") {
        Some("Wi-Fi 5".to_string())
    } else {
        None
    }
}