macmon 0.8.0

Apple Silicon system monitor & Rust library — CPU/GPU power, temperature, RAM. No sudo. TUI, JSON pipe, Prometheus exporter.
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
//! Low-level Apple Silicon metric sources.
//!
//! This module exposes the SMC, IOReport, IOHID, CoreFoundation, and system
//! profiler helpers used by [`crate::Sampler`]. It is useful for advanced
//! integrations, debugging new hardware, or experimenting with additional Apple
//! Silicon counters before they are added to the high-level metrics API.
//!
//! Prefer [`crate::Sampler`] for regular use. The APIs in this module are lower
//! level and may change between releases as macOS, hardware generations, and
//! metric keys change.

#![allow(non_upper_case_globals)]
#![allow(dead_code)]

use std::{
  collections::HashMap,
  ffi::CString,
  marker::{PhantomData, PhantomPinned},
  mem::{MaybeUninit, size_of},
  os::raw::c_void,
  ptr::{null, null_mut},
  sync::OnceLock,
  time::Duration,
};

use core_foundation::{
  array::{
    CFArrayAppendValue, CFArrayCreateMutable, CFArrayGetCount, CFArrayGetValueAtIndex, CFArrayRef,
    CFMutableArrayRef, kCFTypeArrayCallBacks,
  },
  base::{CFAllocatorRef, CFRange, CFRelease, CFTypeRef, kCFAllocatorDefault, kCFAllocatorNull},
  data::{CFDataGetBytes, CFDataGetLength, CFDataRef},
  dictionary::{
    CFDictionaryCreate, CFDictionaryCreateMutableCopy, CFDictionaryGetCount,
    CFDictionaryGetKeysAndValues, CFDictionaryGetValue, CFDictionaryRef, CFDictionarySetValue,
    CFMutableDictionaryRef, kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks,
  },
  number::{
    CFNumberCreate, CFNumberGetValue, CFNumberRef, kCFNumberSInt32Type, kCFNumberSInt64Type,
  },
  string::{CFStringCreateWithBytesNoCopy, CFStringGetCString, CFStringRef, kCFStringEncodingUTF8},
};
use serde::Serialize;

/// Error type used by low-level source helpers.
pub type WithError<T> = Result<T, Box<dyn std::error::Error>>;
/// Raw CoreFoundation/IOKit pointer used by FFI bindings.
pub type CVoidRef = *const std::ffi::c_void;

static SOC_INFO_CACHE: OnceLock<SocInfo> = OnceLock::new();

// MARK: CFUtils

/// Create a CoreFoundation number object from an `i32`.
pub fn cfnum(val: i32) -> CFNumberRef {
  unsafe { CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &val as *const i32 as _) }
}

/// Create a CoreFoundation string object from a Rust string.
pub fn cfstr(val: &str) -> CFStringRef {
  // this creates broken objects if string len > 9
  // CFString::from_static_string(val).as_concrete_TypeRef()
  // CFString::new(val).as_concrete_TypeRef()

  unsafe {
    CFStringCreateWithBytesNoCopy(
      kCFAllocatorDefault,
      val.as_ptr(),
      val.len() as isize,
      kCFStringEncodingUTF8,
      0,
      kCFAllocatorNull,
    )
  }
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
/// Convert a CoreFoundation string reference into a Rust `String`.
pub fn from_cfstr(val: CFStringRef) -> String {
  unsafe {
    let mut buf = Vec::with_capacity(128);
    if CFStringGetCString(val, buf.as_mut_ptr(), 128, kCFStringEncodingUTF8) == 0 {
      panic!("Failed to convert CFString to CString");
    }
    std::ffi::CStr::from_ptr(buf.as_ptr()).to_string_lossy().to_string()
  }
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
/// Return all keys from a CoreFoundation dictionary as Rust strings.
pub fn cfdict_keys(dict: CFDictionaryRef) -> Vec<String> {
  unsafe {
    let count = CFDictionaryGetCount(dict) as usize;
    let mut keys: Vec<CFStringRef> = Vec::with_capacity(count);
    let mut vals: Vec<CFTypeRef> = Vec::with_capacity(count);
    CFDictionaryGetKeysAndValues(dict, keys.as_mut_ptr() as _, vals.as_mut_ptr());
    keys.set_len(count);
    vals.set_len(count);

    keys.iter().map(|k| from_cfstr(*k as _)).collect()
  }
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
/// Look up a value in a CoreFoundation dictionary by string key.
pub fn cfdict_get_val(dict: CFDictionaryRef, key: &str) -> Option<CFTypeRef> {
  unsafe {
    let key = cfstr(key);
    let val = CFDictionaryGetValue(dict, key as _);
    CFRelease(key as _);

    match val {
      _ if val.is_null() => None,
      _ => Some(val),
    }
  }
}

// MARK: IOReport Bindings

#[link(name = "IOKit", kind = "framework")]
#[rustfmt::skip]
unsafe extern "C" {
  fn IOServiceMatching(name: *const i8) -> CFMutableDictionaryRef;
  fn IOServiceGetMatchingServices(mainPort: u32, matching: CFDictionaryRef, existing: *mut u32) -> i32;
  fn IOIteratorNext(iterator: u32) -> u32;
  fn IORegistryEntryGetName(entry: u32, name: *mut i8) -> i32;
  fn IORegistryEntryCreateCFProperties(entry: u32, properties: *mut CFMutableDictionaryRef, allocator: CFAllocatorRef, options: u32) -> i32;
  fn IOObjectRelease(obj: u32) -> u32;
}

#[repr(C)]
struct IOReportSubscription {
  _data: [u8; 0],
  _phantom: PhantomData<(*mut u8, PhantomPinned)>,
}

type IOReportSubscriptionRef = *const IOReportSubscription;
type ChannelFilter = fn(&str, &str, &str, &str) -> bool;
type ChannelFilterRef<'a> = &'a dyn Fn(&str, &str, &str, &str) -> bool;

#[link(name = "IOReport", kind = "dylib")]
#[rustfmt::skip]
unsafe extern "C" {
  fn IOReportCopyAllChannels(a: u64, b: u64) -> CFDictionaryRef;
  fn IOReportCreateSubscription(a: CVoidRef, b: CFMutableDictionaryRef, c: *mut CFMutableDictionaryRef, d: u64, b: CFTypeRef) -> IOReportSubscriptionRef;
  fn IOReportCreateSamples(a: IOReportSubscriptionRef, b: CFMutableDictionaryRef, c: CFTypeRef) -> CFDictionaryRef;
  fn IOReportCreateSamplesDelta(a: CFDictionaryRef, b: CFDictionaryRef, c: CFTypeRef) -> CFDictionaryRef;
  fn IOReportChannelGetGroup(a: CFDictionaryRef) -> CFStringRef;
  fn IOReportChannelGetSubGroup(a: CFDictionaryRef) -> CFStringRef;
  fn IOReportChannelGetChannelName(a: CFDictionaryRef) -> CFStringRef;
  fn IOReportSimpleGetIntegerValue(a: CFDictionaryRef, b: i32) -> i64;
  fn IOReportChannelGetUnitLabel(a: CFDictionaryRef) -> CFStringRef;
  fn IOReportStateGetCount(a: CFDictionaryRef) -> i32;
  fn IOReportStateGetNameForIndex(a: CFDictionaryRef, b: i32) -> CFStringRef;
  fn IOReportStateGetResidency(a: CFDictionaryRef, b: i32) -> i64;
}

// MARK: IOReport helpers

fn cfio_get_group(item: CFDictionaryRef) -> String {
  match unsafe { IOReportChannelGetGroup(item) } {
    x if x.is_null() => String::new(),
    x => from_cfstr(x),
  }
}

fn cfio_get_subgroup(item: CFDictionaryRef) -> String {
  match unsafe { IOReportChannelGetSubGroup(item) } {
    x if x.is_null() => String::new(),
    x => from_cfstr(x),
  }
}

fn cfio_get_channel(item: CFDictionaryRef) -> String {
  match unsafe { IOReportChannelGetChannelName(item) } {
    x if x.is_null() => String::new(),
    x => from_cfstr(x),
  }
}

fn cfio_channel_matches(items: &[(&str, Option<&str>)], group: &str, subgroup: &str) -> bool {
  items.is_empty()
    || items.iter().any(|(item_group, item_subgroup)| {
      *item_group == group && item_subgroup.is_none_or(|value| value == subgroup)
    })
}

/// Copy all CoreFoundation properties from an IORegistry entry.
pub fn cfio_get_props(entry: u32, name: String) -> WithError<CFDictionaryRef> {
  unsafe {
    let mut props: MaybeUninit<CFMutableDictionaryRef> = MaybeUninit::uninit();
    if IORegistryEntryCreateCFProperties(entry, props.as_mut_ptr(), kCFAllocatorDefault, 0) != 0 {
      return Err(format!("Failed to get properties for {}", name).into());
    }

    Ok(props.assume_init())
  }
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
/// Read IOReport state residency counters from a channel item.
pub fn cfio_get_residencies(item: CFDictionaryRef) -> Vec<(String, i64)> {
  let count = unsafe { IOReportStateGetCount(item) };
  let mut res = vec![];

  for i in 0..count {
    let name = unsafe { IOReportStateGetNameForIndex(item, i) };
    let val = unsafe { IOReportStateGetResidency(item, i) };
    let name = match name {
      x if x.is_null() => format!("S{i}"),
      x => from_cfstr(x),
    };
    res.push((name, val));
  }

  res
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
/// Convert an IOReport energy counter into Watts for a sampling duration.
pub fn cfio_watts(item: CFDictionaryRef, unit: &str, duration: Duration) -> WithError<f32> {
  let val = unsafe { IOReportSimpleGetIntegerValue(item, 0) } as f64;
  watts_from_energy(val, unit, duration)
}

fn watts_from_energy(val: f64, unit: &str, duration: Duration) -> WithError<f32> {
  let val = val / duration.as_secs_f64();
  match unit {
    "mJ" => Ok((val / 1e3) as f32),
    "uJ" => Ok((val / 1e6) as f32),
    "nJ" => Ok((val / 1e9) as f32),
    _ => Err(format!("Invalid energy unit: {}", unit).into()),
  }
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
/// Read the integer value from an IOReport channel item.
pub fn cfio_integer_value(item: CFDictionaryRef) -> i64 {
  unsafe { IOReportSimpleGetIntegerValue(item, 0) }
}

// MARK: IOServiceIterator

/// Iterator over IORegistry services matching a service name.
pub struct IOServiceIterator {
  existing: u32,
}

impl IOServiceIterator {
  /// Create an iterator for services such as `AppleSMC` or `AppleARMIODevice`.
  pub fn new(service_name: &str) -> WithError<Self> {
    let service_name = std::ffi::CString::new(service_name).unwrap();
    let existing = unsafe {
      let service = IOServiceMatching(service_name.as_ptr() as _);
      let mut existing = 0;
      if IOServiceGetMatchingServices(0, service, &mut existing) != 0 {
        return Err(format!("{} not found", service_name.to_string_lossy()).into());
      }
      existing
    };

    Ok(Self { existing })
  }
}

impl Drop for IOServiceIterator {
  fn drop(&mut self) {
    unsafe {
      IOObjectRelease(self.existing);
    }
  }
}

impl Iterator for IOServiceIterator {
  type Item = (u32, String);

  fn next(&mut self) -> Option<Self::Item> {
    let next = unsafe { IOIteratorNext(self.existing) };
    if next == 0 {
      return None;
    }

    let mut name = [0; 128]; // 128 defined in apple docs
    if unsafe { IORegistryEntryGetName(next, name.as_mut_ptr()) } != 0 {
      return None;
    }

    let name = unsafe { std::ffi::CStr::from_ptr(name.as_ptr()) };
    let name = name.to_string_lossy().to_string();
    Some((next, name))
  }
}

// MARK: IOReportIterator

/// Iterator over IOReport channel samples.
pub struct IOReportIterator {
  sample: CFDictionaryRef,
  index: isize,
  items: CFArrayRef,
  items_size: isize,
  metadata: Vec<(String, String, String, String)>,
}

impl IOReportIterator {
  /// Create an iterator from raw IOReport sample data and channel metadata.
  pub fn new(data: CFDictionaryRef, metadata: Vec<(String, String, String, String)>) -> Self {
    let items = cfdict_get_val(data, "IOReportChannels").unwrap() as CFArrayRef;
    let items_size = unsafe { CFArrayGetCount(items) } as isize;
    debug_assert_eq!(metadata.len(), items_size as usize);
    Self { sample: data, items, items_size, index: 0, metadata }
  }
}

impl Drop for IOReportIterator {
  fn drop(&mut self) {
    unsafe { CFRelease(self.sample as _) };
  }
}

#[derive(Debug)]
/// One IOReport channel item returned by [`IOReportIterator`].
pub struct IOReportIteratorItem {
  /// IOReport group name.
  pub group: String,
  /// IOReport subgroup name.
  pub subgroup: String,
  /// IOReport channel name.
  pub channel: String,
  /// IOReport unit label.
  pub unit: String,
  /// Raw IOReport channel dictionary for advanced parsing.
  pub item: CFDictionaryRef,
}

impl Iterator for IOReportIterator {
  type Item = IOReportIteratorItem;

  fn next(&mut self) -> Option<Self::Item> {
    if self.index >= self.items_size {
      return None;
    }

    let item = unsafe { CFArrayGetValueAtIndex(self.items, self.index) } as CFDictionaryRef;
    let (group, subgroup, channel, unit) =
      self.metadata.get(self.index as usize).cloned().unwrap_or_default();

    self.index += 1;
    Some(IOReportIteratorItem { group, subgroup, channel, unit, item })
  }
}

// MARK: RAM

/// Read used and total RAM in bytes via libc/mach APIs.
pub fn libc_ram() -> WithError<(u64, u64)> {
  let (mut usage, mut total) = (0u64, 0u64);

  unsafe {
    let mut name = [libc::CTL_HW, libc::HW_MEMSIZE];
    let mut size = std::mem::size_of::<u64>();
    let ret_code = libc::sysctl(
      name.as_mut_ptr(),
      name.len() as _,
      &mut total as *mut _ as *mut _,
      &mut size,
      std::ptr::null_mut(),
      0,
    );

    if ret_code != 0 {
      return Err("Failed to get total memory".into());
    }
  }

  unsafe {
    let mut count: u32 = libc::HOST_VM_INFO64_COUNT as _;
    let mut stats = std::mem::zeroed::<libc::vm_statistics64>();

    // todo: https://github.com/JohnTitor/mach2/issues/34
    #[allow(deprecated)]
    let ret_code = libc::host_statistics64(
      libc::mach_host_self(),
      libc::HOST_VM_INFO64,
      &mut stats as *mut _ as *mut _,
      &mut count,
    );

    if ret_code != 0 {
      return Err("Failed to get memory stats".into());
    }

    let page_size_kb = libc::sysconf(libc::_SC_PAGESIZE) as u64;

    usage = (stats.active_count as u64
      + stats.inactive_count as u64
      + stats.wire_count as u64
      + stats.speculative_count as u64
      + stats.compressor_page_count as u64
      - stats.purgeable_count as u64
      - stats.external_page_count as u64)
      * page_size_kb;
  }

  Ok((usage, total))
}

/// Read used and total swap in bytes via libc sysctl.
pub fn libc_swap() -> WithError<(u64, u64)> {
  let (mut usage, mut total) = (0u64, 0u64);

  unsafe {
    let mut name = [libc::CTL_VM, libc::VM_SWAPUSAGE];
    let mut size = std::mem::size_of::<libc::xsw_usage>();
    let mut xsw: libc::xsw_usage = std::mem::zeroed::<libc::xsw_usage>();

    let ret_code = libc::sysctl(
      name.as_mut_ptr(),
      name.len() as _,
      &mut xsw as *mut _ as *mut _,
      &mut size,
      std::ptr::null_mut(),
      0,
    );

    if ret_code != 0 {
      return Err("Failed to get swap usage".into());
    }

    usage = xsw.xsu_used;
    total = xsw.xsu_total;
  }

  Ok((usage, total))
}

// MARK: SockInfo

/// Static Apple Silicon system information.
///
/// This describes the current machine and the frequency tables used to interpret
/// CPU/GPU residency counters.
#[derive(Debug, Default, Clone, Serialize)]
pub struct SocInfo {
  /// Apple hardware model identifier, such as `Mac14,7`.
  pub mac_model: String,
  /// Human-readable chip name.
  pub chip_name: String,
  /// Installed unified memory size in GiB.
  pub memory_gb: u16,
  /// Number of efficiency-tier CPU cores.
  pub ecpu_cores: u8,
  /// Number of performance-tier CPU cores.
  pub pcpu_cores: u8,
  /// UI label for the lower CPU tier, for example `E` on M1-M4 or `P` on M5+.
  pub ecpu_label: String,
  /// UI label for the higher CPU tier, for example `P` on M1-M4 or `S` on M5+.
  pub pcpu_label: String,
  /// Supported lower-tier CPU frequencies in MHz.
  pub ecpu_freqs: Vec<u32>,
  /// Supported higher-tier CPU frequencies in MHz.
  pub pcpu_freqs: Vec<u32>,
  /// Number of GPU cores.
  pub gpu_cores: u8,
  /// Supported GPU frequencies in MHz.
  pub gpu_freqs: Vec<u32>,
}

impl SocInfo {
  /// Load static SoC information for the current machine.
  pub fn new() -> WithError<Self> {
    // Keep this constructor for external library users; internal call sites use get_soc_info().
    get_soc_info()
  }
}

/// Parse dynamic voltage and frequency scaling data from an IORegistry dictionary.
pub fn get_dvfs_mhz(dict: CFDictionaryRef, key: &str) -> Option<(Vec<u32>, Vec<u32>)> {
  unsafe {
    let obj = cfdict_get_val(dict, key)? as CFDataRef;
    let obj_len = CFDataGetLength(obj);
    let obj_val = vec![0u8; obj_len as usize];
    CFDataGetBytes(obj, CFRange::init(0, obj_len), obj_val.as_ptr() as *mut u8);

    // obj_val is pairs of (freq, voltage) 4 bytes each
    let items_count = (obj_len / 8) as usize;
    let [mut freqs, mut volts] = [vec![0u32; items_count], vec![0u32; items_count]];
    for (i, x) in obj_val.chunks_exact(8).enumerate() {
      volts[i] = u32::from_le_bytes([x[4], x[5], x[6], x[7]]);
      freqs[i] = u32::from_le_bytes([x[0], x[1], x[2], x[3]]);
    }

    Some((volts, freqs))
  }
}

// Parse acc-clusters bytes into (ecpu_key, pcpu_key) voltage-states key names.
// Each 8-byte entry: byte 0 = voltage-states index, byte 1 = cluster type
// (0 = efficiency/lowest tier, higher = higher perf tier).
// Picks highest type as pcpu, second-highest as ecpu — handles M5 Max where
// type 0 (E-core cluster) is absent and the two active tiers are 1 and 2.
fn parse_acc_clusters(data: &[u8]) -> Option<(String, String)> {
  let mut clusters: Vec<(u8, String)> = Vec::new();
  for chunk in data.chunks_exact(8) {
    clusters.push((chunk[1], format!("voltage-states{}-sram", chunk[0])));
  }
  clusters.sort_by_key(|c| c.0);
  if clusters.len() < 2 {
    return None;
  }
  let ecpu_key = clusters[clusters.len() - 2].1.clone();
  let pcpu_key = clusters.last()?.1.clone();
  Some((ecpu_key, pcpu_key))
}

// Read acc-clusters from pmgr dict and parse into (ecpu_key, pcpu_key).
fn parse_acc_clusters_from(dict: CFDictionaryRef) -> Option<(String, String)> {
  let obj = cfdict_get_val(dict, "acc-clusters")? as CFDataRef;

  let len = unsafe { CFDataGetLength(obj) } as usize;
  if len < 8 {
    return None;
  }

  let mut data = vec![0u8; len];
  unsafe { CFDataGetBytes(obj, CFRange::init(0, len as _), data.as_mut_ptr()) };

  parse_acc_clusters(&data)
}

fn to_mhz(vals: Vec<u32>, scale: u32) -> Vec<u32> {
  vals.iter().map(|x| *x / scale).collect()
}

// M1–M3 and A-series chips store frequencies in Hz; M4+ store in kHz.
fn cpu_freq_scale(chip_name: &str) -> u32 {
  let hz_freqs = chip_name.contains("M1")
    || chip_name.contains("M2")
    || chip_name.contains("M3")
    || chip_name.contains("A1"); // A14–A18 and future A1x chips
  if hz_freqs { 1_000_000 } else { 1_000 }
}

// Try known voltage-states key (M1-M4) first, fall back to acc-clusters discovery (M5+).
fn cpu_freqs(item: CFDictionaryRef, key: &str, is_ecpu: bool, scale: u32) -> Option<Vec<u32>> {
  if let Some((_, freqs)) = get_dvfs_mhz(item, key) {
    return Some(to_mhz(freqs, scale));
  }
  let (ecpu_key, pcpu_key) = parse_acc_clusters_from(item)?;
  let key = if is_ecpu { ecpu_key } else { pcpu_key };
  let (_, freqs) = get_dvfs_mhz(item, &key)?;
  Some(to_mhz(freqs, scale))
}

// Parse "proc T:P:E" (macOS 15) or "proc T:P_or_S:E:M" (macOS 26+) into (ecpu, pcpu, has_mcpu).
// macOS 26 always uses 4 fields; M5+ has M>0 (ecpu=M, pcpu=S), M1-M4 has M=0 (ecpu=E, pcpu=P).
fn parse_cpu_cores(s: &str) -> (u64, u64, bool) {
  let procs = s.strip_prefix("proc ").unwrap_or("");
  let parts: Vec<u64> = procs.split(':').map(|x| x.parse().unwrap_or(0)).collect();

  match parts.len() {
    4 => {
      let (e, m) = (parts[2], parts[3]);
      if m > 0 { (m, parts[1], true) } else { (e, parts[1], false) }
    }
    3 => (parts[2], parts[1], false), // macOS 15: "proc total:P:E"
    _ => (0, 0, false),
  }
}

// Static hardware fields obtainable either via `system_profiler` or directly via
// sysctl/IOKit. Kept separate from SocInfo so the two sourcing strategies below
// don't need to touch the CPU/GPU frequency tables, which are always read via IOKit.
#[derive(Debug)]
pub(crate) struct HwInfo {
  pub(crate) chip_name: String,
  pub(crate) mac_model: String,
  pub(crate) memory_gb: u16,
  pub(crate) ecpu_cores: u8,
  pub(crate) pcpu_cores: u8,
  pub(crate) ecpu_label: String,
  pub(crate) pcpu_label: String,
  pub(crate) gpu_cores: u8,
}

/// Read a string sysctl value by name.
pub(crate) fn sysctl_str(name: &str) -> Option<String> {
  let cname = CString::new(name).ok()?;
  unsafe {
    let mut size: usize = 0;
    let ret = libc::sysctlbyname(cname.as_ptr(), null_mut(), &mut size, null_mut(), 0);
    if ret != 0 || size == 0 {
      return None;
    }

    let mut buf = vec![0u8; size];
    let ret =
      libc::sysctlbyname(cname.as_ptr(), buf.as_mut_ptr() as *mut c_void, &mut size, null_mut(), 0);
    if ret != 0 {
      return None;
    }

    buf.truncate(size.saturating_sub(1)); // drop trailing NUL
    String::from_utf8(buf).ok()
  }
}

fn sysctl_buf<const N: usize>(name: &str) -> Option<[u8; N]> {
  let cname = CString::new(name).ok()?;
  let mut buf = [0; N];
  let mut size = N;
  let ret = unsafe {
    libc::sysctlbyname(cname.as_ptr(), buf.as_mut_ptr().cast(), &mut size, null_mut(), 0)
  };
  (ret == 0).then_some(buf)
}

fn sysctl_u32(name: &str) -> Option<u32> {
  sysctl_buf(name).map(u32::from_ne_bytes)
}

fn sysctl_u64(name: &str) -> Option<u64> {
  sysctl_buf(name).map(u64::from_ne_bytes)
}

/// Read an integer CFNumber property from an IORegistry properties dictionary.
fn cfnum_get_i64(dict: CFDictionaryRef, key: &str) -> Option<i64> {
  let obj = cfdict_get_val(dict, key)? as CFNumberRef;
  let mut val: i64 = 0;
  let ok = unsafe { CFNumberGetValue(obj, kCFNumberSInt64Type, &mut val as *mut _ as *mut c_void) };
  ok.then_some(val)
}

// perflevel0 is Apple's highest-capability CPU cluster, the last perflevel is the
// lowest (confirmed via `sysctl hw.perflevel0/1.name` -> Performance/Efficiency on
// M1-M4). M5 drops E-cores for a new higher "Super" tier above Performance, so the
// same two-slot ecpu/pcpu split still applies, just relabeled P/S instead of E/P.
// Unverified on real M5 hardware (see hw_from_profiler for the tested fallback path).
fn cpu_tier_counts(chip_name: &str) -> Option<(u8, u8, &'static str, &'static str)> {
  let nperflevels = sysctl_u32("hw.nperflevels")?;
  if nperflevels < 2 {
    return None;
  }

  let hi = sysctl_u32("hw.perflevel0.physicalcpu")?;
  let lo = sysctl_u32(&format!("hw.perflevel{}.physicalcpu", nperflevels - 1))?;

  let is_legacy = ["M1", "M2", "M3", "M4", "A1"].iter().any(|x| chip_name.contains(x));
  let (ecpu_label, pcpu_label) = if is_legacy { ("E", "P") } else { ("P", "S") };

  Some((lo as u8, hi as u8, ecpu_label, pcpu_label))
}

/// Read hardware descriptor fields via sysctl and IORegistry only (no subprocess).
pub(crate) fn hw_native() -> WithError<HwInfo> {
  let chip_name = sysctl_str("machdep.cpu.brand_string").ok_or("Failed to read chip name")?;
  let mac_model = sysctl_str("hw.model").ok_or("Failed to read mac model")?;
  let memory_gb =
    sysctl_u64("hw.memsize").ok_or("Failed to read memory size")? / (1024 * 1024 * 1024);
  let (ecpu_cores, pcpu_cores, ecpu_label, pcpu_label) =
    cpu_tier_counts(&chip_name).ok_or("Failed to read CPU core topology")?;

  let mut gpu_cores = 0u8;
  for (entry, name) in IOServiceIterator::new("AGXAccelerator")? {
    if let Ok(item) = cfio_get_props(entry, name) {
      if let Some(cores) = cfnum_get_i64(item, "gpu-core-count") {
        gpu_cores = cores as u8;
      }
      unsafe { CFRelease(item as _) }
    }
  }

  Ok(HwInfo {
    chip_name,
    mac_model,
    memory_gb: memory_gb as u16,
    ecpu_cores,
    pcpu_cores,
    ecpu_label: ecpu_label.into(),
    pcpu_label: pcpu_label.into(),
    gpu_cores,
  })
}

/// Read hardware descriptor fields via `system_profiler` (slower, ~250-300ms subprocess
/// spawn, but battle-tested against real M1-M5 hardware bug reports).
pub(crate) fn hw_from_profiler() -> WithError<HwInfo> {
  let out = std::process::Command::new("system_profiler")
    .args(["SPHardwareDataType", "SPDisplaysDataType", "-json"])
    .output()?;
  let out = std::str::from_utf8(&out.stdout)?;
  let out = serde_json::from_str::<serde_json::Value>(out)?;

  // SPHardwareDataType.0.chip_type
  let chip_name = out["SPHardwareDataType"][0]["chip_type"].as_str();
  let chip_name = chip_name.unwrap_or("Unknown chip").to_string();

  // SPHardwareDataType.0.machine_model
  let mac_model = out["SPHardwareDataType"][0]["machine_model"].as_str();
  let mac_model = mac_model.unwrap_or("Unknown model").to_string();

  // SPHardwareDataType.0.physical_memory -> "x GB"
  let mem_gb = out["SPHardwareDataType"][0]["physical_memory"].as_str();
  let mem_gb = mem_gb.and_then(|x| x.strip_suffix(" GB")).and_then(|x| x.parse::<u64>().ok());
  let mem_gb = mem_gb.unwrap_or(0);

  // SPHardwareDataType.0.number_processors -> "proc x:y:z" or "proc x:y:z:w"
  let number_processors = out["SPHardwareDataType"][0]["number_processors"].as_str().unwrap_or("");
  let (ecpu_cores, pcpu_cores, has_mcpu) = parse_cpu_cores(number_processors);

  // SPDisplaysDataType.0.sppci_cores
  let gpu_cores = out["SPDisplaysDataType"][0]["sppci_cores"].as_str();
  let gpu_cores = gpu_cores.unwrap_or("0").parse::<u64>().unwrap_or(0);

  Ok(HwInfo {
    chip_name,
    mac_model,
    memory_gb: mem_gb as u16,
    ecpu_cores: ecpu_cores as u8,
    pcpu_cores: pcpu_cores as u8,
    ecpu_label: if has_mcpu { "P".into() } else { "E".into() },
    pcpu_label: if has_mcpu { "S".into() } else { "P".into() },
    gpu_cores: gpu_cores as u8,
  })
}

fn load_soc_info() -> WithError<SocInfo> {
  let hw = match hw_native() {
    Ok(hw) => hw,
    Err(_) => hw_from_profiler()?,
  };

  let mut info = SocInfo {
    chip_name: hw.chip_name,
    mac_model: hw.mac_model,
    memory_gb: hw.memory_gb,
    ecpu_cores: hw.ecpu_cores,
    pcpu_cores: hw.pcpu_cores,
    ecpu_label: hw.ecpu_label,
    pcpu_label: hw.pcpu_label,
    gpu_cores: hw.gpu_cores,
    ..Default::default()
  };

  let cpu_scale = cpu_freq_scale(&info.chip_name);
  let gpu_scale: u32 = 1000 * 1000; // MHz

  // CPU/GPU frequencies always come from IOKit directly, regardless of how the
  // rest of the hardware descriptor above was sourced.
  for (entry, name) in IOServiceIterator::new("AppleARMIODevice")? {
    if name == "pmgr" {
      let item = cfio_get_props(entry, name)?;
      // 1) `strings /usr/bin/powermetrics | grep voltage-states` uses non-sram keys
      //    but their values are zero, so sram used here; it looks valid.
      // 2) sudo powermetrics --samplers cpu_power -i 1000 -n 1 | grep "active residency" | grep "Cluster"
      if let Some(f) = cpu_freqs(item, "voltage-states1-sram", true, cpu_scale) {
        info.ecpu_freqs = f;
      }
      if let Some(f) = cpu_freqs(item, "voltage-states5-sram", false, cpu_scale) {
        info.pcpu_freqs = f;
      }

      if let Some((_, freqs)) = get_dvfs_mhz(item, "voltage-states9") {
        info.gpu_freqs = to_mhz(freqs, gpu_scale);
      }
      unsafe { CFRelease(item as _) }
    }
  }

  if info.ecpu_freqs.is_empty() || info.pcpu_freqs.is_empty() {
    return Err("No CPU frequencies found".into());
  }

  Ok(info)
}

/// Load cached static SoC information for the current machine.
pub fn get_soc_info() -> WithError<SocInfo> {
  if let Some(info) = SOC_INFO_CACHE.get() {
    return Ok(info.clone());
  }

  let info = load_soc_info()?;
  let _ = SOC_INFO_CACHE.set(info.clone());
  Ok(info)
}

// MARK: IOReport

struct IOReportChannels {
  chan: CFMutableDictionaryRef,
  source: Option<CFDictionaryRef>,
  selected: Option<CFMutableArrayRef>,
}

fn cfio_get_chan(filter: Option<ChannelFilterRef<'_>>) -> WithError<IOReportChannels> {
  let all_channels = unsafe { IOReportCopyAllChannels(0, 0) };
  let Some(channel_array) = cfdict_get_val(all_channels, "IOReportChannels") else {
    unsafe { CFRelease(all_channels as _) };
    return Err("Failed to get channels".into());
  };
  let channel_array = channel_array as CFArrayRef;

  let size = unsafe { CFDictionaryGetCount(all_channels) };
  let chan = unsafe { CFDictionaryCreateMutableCopy(kCFAllocatorDefault, size, all_channels) };

  let mut selected_channels = None;
  if let Some(filter) = filter {
    let count = unsafe { CFArrayGetCount(channel_array) };
    let selected =
      unsafe { CFArrayCreateMutable(kCFAllocatorDefault, count, &kCFTypeArrayCallBacks) };

    for i in 0..count {
      let item = unsafe { CFArrayGetValueAtIndex(channel_array, i) } as CFDictionaryRef;
      let group = cfio_get_group(item);
      let subgroup = cfio_get_subgroup(item);
      let channel = cfio_get_channel(item);
      let unit = from_cfstr(unsafe { IOReportChannelGetUnitLabel(item) }).trim().to_string();
      if filter(&group, &subgroup, &channel, &unit) {
        unsafe { CFArrayAppendValue(selected, item as _) };
      }
    }

    let key = cfstr("IOReportChannels");
    unsafe {
      CFDictionarySetValue(chan, key as _, selected as _);
      CFRelease(key as _);
    }
    selected_channels = Some(selected);
  }

  Ok(IOReportChannels { chan, source: Some(all_channels), selected: selected_channels })
}

fn cfio_channel_metadata(channels: CFDictionaryRef) -> Vec<(String, String, String, String)> {
  let Some(channel_array) = cfdict_get_val(channels, "IOReportChannels") else {
    return Vec::new();
  };
  let channel_array = channel_array as CFArrayRef;
  let count = unsafe { CFArrayGetCount(channel_array) };
  let mut metadata = Vec::with_capacity(count as usize);

  for i in 0..count {
    let item = unsafe { CFArrayGetValueAtIndex(channel_array, i) } as CFDictionaryRef;
    metadata.push((
      cfio_get_group(item),
      cfio_get_subgroup(item),
      cfio_get_channel(item),
      from_cfstr(unsafe { IOReportChannelGetUnitLabel(item) }).trim().to_string(),
    ));
  }

  metadata
}

fn cfio_get_subs(chan: CFMutableDictionaryRef) -> WithError<IOReportSubscriptionRef> {
  let mut s: MaybeUninit<CFMutableDictionaryRef> = MaybeUninit::uninit();
  let rs = unsafe { IOReportCreateSubscription(null(), chan, s.as_mut_ptr(), 0, null()) };
  if rs.is_null() {
    return Err("Failed to create subscription".into());
  }

  unsafe { s.assume_init() };
  Ok(rs)
}

/// IOReport subscription used to sample Apple Silicon power and residency counters.
pub struct IOReport {
  subs: IOReportSubscriptionRef,
  chan: CFMutableDictionaryRef,
  source: Option<CFDictionaryRef>,
  selected: Option<CFMutableArrayRef>,
  metadata: Vec<(String, String, String, String)>,
  prev: Option<(CFDictionaryRef, std::time::Instant)>,
}

impl IOReport {
  fn from_filter(filter: Option<ChannelFilterRef<'_>>) -> WithError<Self> {
    let channels = cfio_get_chan(filter)?;
    let metadata = cfio_channel_metadata(channels.chan);
    let subs = cfio_get_subs(channels.chan)?;
    Ok(Self {
      subs,
      chan: channels.chan,
      source: channels.source,
      selected: channels.selected,
      metadata,
      prev: None,
    })
  }

  /// Subscribe to IOReport channels by group and optional subgroup.
  pub fn new(channels: Vec<(&str, Option<&str>)>) -> WithError<Self> {
    let filter = |group: &str, subgroup: &str, _channel: &str, _unit: &str| {
      cfio_channel_matches(&channels, group, subgroup)
    };
    Self::from_filter(Some(&filter))
  }

  pub(crate) fn with_filter(filter: Option<ChannelFilter>) -> WithError<Self> {
    match filter {
      Some(filter) => Self::from_filter(Some(&filter)),
      None => Self::from_filter(None),
    }
  }

  /// Collect one delta sample over `duration` milliseconds.
  pub fn get_sample(&self, duration: u64) -> IOReportIterator {
    unsafe {
      let sample1 = IOReportCreateSamples(self.subs, self.chan, null());
      std::thread::sleep(std::time::Duration::from_millis(duration));
      let sample2 = IOReportCreateSamples(self.subs, self.chan, null());

      let sample3 = IOReportCreateSamplesDelta(sample1, sample2, null());
      CFRelease(sample1 as _);
      CFRelease(sample2 as _);
      IOReportIterator::new(sample3, self.metadata.clone())
    }
  }

  fn raw_sample(&self) -> (CFDictionaryRef, std::time::Instant) {
    (unsafe { IOReportCreateSamples(self.subs, self.chan, null()) }, std::time::Instant::now())
  }

  pub(crate) fn get_sample_interval(&mut self, duration: Duration) -> (IOReportIterator, Duration) {
    let prev = match self.prev {
      Some(x) => x,
      None => self.raw_sample(),
    };

    let target_at = prev.1 + duration;
    let now = std::time::Instant::now();
    if target_at > now {
      std::thread::sleep(target_at.duration_since(now));
    }

    let next = self.raw_sample();
    let diff = unsafe { IOReportCreateSamplesDelta(prev.0, next.0, null()) };
    unsafe { CFRelease(prev.0 as _) };

    let elapsed = next.1.duration_since(prev.1).max(Duration::from_nanos(1));
    self.prev = Some(next);

    (IOReportIterator::new(diff, self.metadata.clone()), elapsed)
  }

  /// Collect multiple delta samples across one sampling window.
  pub fn get_samples(&mut self, duration: u64, count: usize) -> Vec<(IOReportIterator, u64)> {
    let count = count.clamp(1, 32);
    let mut samples: Vec<(IOReportIterator, u64)> = Vec::with_capacity(count);

    let mut prev = match self.prev {
      Some(x) => x,
      None => self.raw_sample(),
    };

    let started_at = prev.1;
    for i in 1..=count {
      // Keep the requested sampling window stable: IOReportCreateSamples time should not
      // accumulate as drift on top of the caller's interval.
      let target_msec = duration.saturating_mul(i as u64) / count as u64;
      let target_at = started_at + std::time::Duration::from_millis(target_msec);
      let now = std::time::Instant::now();
      if target_at > now {
        std::thread::sleep(target_at.duration_since(now));
      }

      let next = self.raw_sample();
      let diff = unsafe { IOReportCreateSamplesDelta(prev.0, next.0, null()) };
      unsafe { CFRelease(prev.0 as _) };

      let elapsed = next.1.duration_since(prev.1).as_millis() as u64;
      prev = next;

      samples.push((IOReportIterator::new(diff, self.metadata.clone()), elapsed.max(1)));
    }

    self.prev = Some(prev);
    samples
  }
}

impl Drop for IOReport {
  fn drop(&mut self) {
    unsafe {
      CFRelease(self.chan as _);
      CFRelease(self.subs as _);
      if let Some(selected) = self.selected {
        CFRelease(selected as _);
      }
      if let Some(source) = self.source {
        CFRelease(source as _);
      }
      if let Some(prev) = self.prev {
        CFRelease(prev.0 as _);
      }
    }
  }
}

// MARK: IOHID Bindings
// referenced from: https://github.com/freedomtan/sensors/blob/master/sensors/sensors.m

#[repr(C)]
struct IOHIDServiceClient(libc::c_void);

#[repr(C)]
struct IOHIDEventSystemClient(libc::c_void);

#[repr(C)]
struct IOHIDEvent(libc::c_void);

type IOHIDServiceClientRef = *const IOHIDServiceClient;
type IOHIDEventSystemClientRef = *const IOHIDEventSystemClient;
type IOHIDEventRef = *const IOHIDEvent;

const kHIDPage_AppleVendor: i32 = 0xff00;
const kHIDUsage_AppleVendor_TemperatureSensor: i32 = 0x0005;

const kIOHIDEventTypeTemperature: i64 = 15;
const kIOHIDEventTypePower: i64 = 25;

#[link(name = "IOKit", kind = "framework")]
#[rustfmt::skip]
unsafe extern "C" {
  fn IOHIDEventSystemClientCreate(allocator: CFAllocatorRef) -> IOHIDEventSystemClientRef;
  fn IOHIDEventSystemClientSetMatching(a: IOHIDEventSystemClientRef, b: CFDictionaryRef) -> i32;
  fn IOHIDEventSystemClientCopyServices(a: IOHIDEventSystemClientRef) -> CFArrayRef;
  fn IOHIDServiceClientCopyProperty(a: IOHIDServiceClientRef, b: CFStringRef) -> CFStringRef;
  fn IOHIDServiceClientCopyEvent(a: IOHIDServiceClientRef, v0: i64, v1: i32, v2: i64) -> IOHIDEventRef;
  fn IOHIDEventGetFloatValue(event: IOHIDEventRef, field: i64) -> f64;
}

// MARK: IOHIDSensors

/// IOHID temperature sensor reader.
pub struct IOHIDSensors {
  sensors: CFDictionaryRef,
}

impl IOHIDSensors {
  /// Create an IOHID temperature sensor reader.
  pub fn new() -> WithError<Self> {
    let keys = [cfstr("PrimaryUsagePage"), cfstr("PrimaryUsage")];
    let nums = [cfnum(kHIDPage_AppleVendor), cfnum(kHIDUsage_AppleVendor_TemperatureSensor)];

    let sensors = unsafe {
      CFDictionaryCreate(
        kCFAllocatorDefault,
        keys.as_ptr() as _,
        nums.as_ptr() as _,
        2,
        &kCFTypeDictionaryKeyCallBacks,
        &kCFTypeDictionaryValueCallBacks,
      )
    };

    Ok(Self { sensors })
  }

  /// Read temperature sensor values as `(sensor_name, celsius)`.
  pub fn get_metrics(&self) -> Vec<(String, f32)> {
    unsafe {
      let system = match IOHIDEventSystemClientCreate(kCFAllocatorDefault) {
        x if x.is_null() => return vec![],
        x => x,
      };

      IOHIDEventSystemClientSetMatching(system, self.sensors);

      let services = match IOHIDEventSystemClientCopyServices(system) {
        x if x.is_null() => return vec![],
        x => x,
      };

      let mut items = vec![] as Vec<(String, f32)>;
      for i in 0..CFArrayGetCount(services) {
        let sc = match CFArrayGetValueAtIndex(services, i) as IOHIDServiceClientRef {
          x if x.is_null() => continue,
          x => x,
        };

        let name = match IOHIDServiceClientCopyProperty(sc, cfstr("Product")) {
          x if x.is_null() => continue,
          x => from_cfstr(x),
        };

        let event = match IOHIDServiceClientCopyEvent(sc, kIOHIDEventTypeTemperature, 0, 0) {
          x if x.is_null() => continue,
          x => x,
        };

        let temp = IOHIDEventGetFloatValue(event, kIOHIDEventTypeTemperature << 16);
        CFRelease(event as _);
        if temp <= 0.0 || temp > 150.0 {
          continue;
        }
        items.push((name, temp as f32));
      }

      CFRelease(services as _);
      CFRelease(system as _);

      items.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
      items
    }
  }
}

impl Drop for IOHIDSensors {
  fn drop(&mut self) {
    unsafe { CFRelease(self.sensors as _) };
  }
}

// MARK: SMC Bindings

#[link(name = "IOKit", kind = "framework")]
unsafe extern "C" {
  fn mach_task_self() -> u32;
  fn IOServiceOpen(device: u32, a: u32, b: u32, c: *mut u32) -> i32;
  fn IOServiceClose(conn: u32) -> i32;
  fn IOConnectCallStructMethod(
    conn: u32,
    selector: u32,
    ival: *const c_void,
    isize: usize,
    oval: *mut c_void,
    osize: *mut usize,
  ) -> i32;
}

#[repr(C)]
#[derive(Debug, Default)]
/// SMC protocol version payload.
pub struct KeyDataVer {
  /// SMC protocol major version.
  pub major: u8,
  /// SMC protocol minor version.
  pub minor: u8,
  /// SMC protocol build number.
  pub build: u8,
  /// Reserved SMC protocol byte.
  pub reserved: u8,
  /// SMC protocol release number.
  pub release: u16,
}

#[repr(C)]
#[derive(Debug, Default)]
/// SMC power limit payload.
pub struct PLimitData {
  /// Payload version.
  pub version: u16,
  /// Payload length.
  pub length: u16,
  /// CPU power limit field.
  pub cpu_p_limit: u32,
  /// GPU power limit field.
  pub gpu_p_limit: u32,
  /// Memory power limit field.
  pub mem_p_limit: u32,
}

#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
/// Metadata describing an SMC key value.
pub struct KeyInfo {
  /// Size of the SMC value payload in bytes.
  pub data_size: u32,
  /// FourCC data type for the SMC value.
  pub data_type: u32,
  /// SMC key attributes.
  pub data_attributes: u8,
}

#[repr(C)]
#[derive(Debug, Default)]
/// Raw SMC request/response payload.
pub struct KeyData {
  /// Four-byte SMC key encoded as a big-endian integer.
  pub key: u32,
  /// SMC protocol version data.
  pub vers: KeyDataVer,
  /// Power limit payload.
  pub p_limit_data: PLimitData,
  /// SMC key metadata.
  pub key_info: KeyInfo,
  /// SMC result byte.
  pub result: u8,
  /// SMC status byte.
  pub status: u8,
  /// 8-bit command/data field.
  pub data8: u8,
  /// 32-bit command/data field.
  pub data32: u32,
  /// Raw SMC value bytes.
  pub bytes: [u8; 32],
}

#[derive(Debug, Clone)]
/// Decoded SMC sensor value.
pub struct SensorVal {
  /// Four-byte SMC key name.
  pub name: String,
  /// FourCC unit/data type string.
  pub unit: String,
  /// Raw sensor bytes.
  pub data: Vec<u8>,
}

// MARK: SMC

#[allow(clippy::upper_case_acronyms)]
/// Apple System Management Controller connection.
pub struct SMC {
  conn: u32,
  keys: HashMap<u32, KeyInfo>,
}

impl SMC {
  /// Open an SMC connection.
  pub fn new() -> WithError<Self> {
    let mut conn = 0;

    for (device, name) in IOServiceIterator::new("AppleSMC")? {
      if name == "AppleSMCKeysEndpoint" {
        let rs = unsafe { IOServiceOpen(device, mach_task_self(), 0, &mut conn) };
        if rs != 0 {
          return Err(format!("IOServiceOpen: {}", rs).into());
        }
      }
    }

    Ok(Self { conn, keys: HashMap::new() })
  }

  fn read(&self, input: &KeyData) -> WithError<KeyData> {
    let ival = input as *const _ as _;
    let ilen = size_of::<KeyData>();
    let mut oval = KeyData::default();
    let mut olen = size_of::<KeyData>();

    let rs = unsafe {
      IOConnectCallStructMethod(self.conn, 2, ival, ilen, &mut oval as *mut _ as _, &mut olen)
    };

    if rs != 0 {
      // println!("{:?}", input);
      return Err(format!("IOConnectCallStructMethod: {}", rs).into());
    }

    if oval.result == 132 {
      return Err("SMC key not found".into());
    }

    if oval.result != 0 {
      return Err(format!("SMC error: {}", oval.result).into());
    }

    Ok(oval)
  }

  fn parse_key(key: &str) -> WithError<u32> {
    if key.len() != 4 {
      return Err("SMC key must be 4 bytes long".into());
    }

    Ok(key.bytes().fold(0, |acc, x| (acc << 8) + x as u32))
  }

  fn read_key_info_by_id(&mut self, key: u32) -> WithError<KeyInfo> {
    if let Some(key_info) = self.keys.get(&key) {
      // println!("cache hit for {}", key);
      return Ok(*key_info);
    }

    let ival = KeyData { data8: 9, key, ..Default::default() };
    let oval = self.read(&ival)?;
    self.keys.insert(key, oval.key_info);
    Ok(oval.key_info)
  }

  /// Read an SMC key name by numeric index.
  pub fn key_by_index(&self, index: u32) -> WithError<String> {
    let ival = KeyData { data8: 8, data32: index, ..Default::default() };
    let oval = self.read(&ival)?;
    Ok(std::str::from_utf8(&oval.key.to_be_bytes()).unwrap().to_string())
  }

  /// Read metadata for a four-byte SMC key.
  pub fn read_key_info(&mut self, key: &str) -> WithError<KeyInfo> {
    let key = Self::parse_key(key)?;
    self.read_key_info_by_id(key)
  }

  /// Read a raw SMC sensor value by four-byte key.
  pub fn read_val(&mut self, key: &str) -> WithError<SensorVal> {
    let name = key.to_string();
    let key = Self::parse_key(key)?;
    let key_info = self.read_key_info_by_id(key)?;
    let ival = KeyData { data8: 5, key, key_info, ..Default::default() };
    let oval = self.read(&ival)?;

    Ok(SensorVal {
      name,
      unit: std::str::from_utf8(&key_info.data_type.to_be_bytes()).unwrap().to_string(),
      data: oval.bytes[0..key_info.data_size as usize].to_vec(),
    })
  }

  /// Read a four-byte float SMC value.
  pub fn read_float_val(&mut self, key: &str) -> WithError<f32> {
    const FLOAT_TYPE: u32 = 1718383648; // FourCC: "flt "

    let key_id = Self::parse_key(key)?;
    let key_info = self.read_key_info_by_id(key_id)?;
    if key_info.data_size != 4 || key_info.data_type != FLOAT_TYPE {
      return Err(
        format!(
          "SMC key '{}' is not a 4-byte float (size={}, type={})",
          key, key_info.data_size, key_info.data_type
        )
        .into(),
      );
    }

    let ival = KeyData { data8: 5, key: key_id, key_info, ..Default::default() };
    let oval = self.read(&ival)?;

    Ok(f32::from_le_bytes(oval.bytes[0..4].try_into().unwrap()))
  }

  /// Read the number of SMC keys exposed by the current machine.
  pub fn key_count(&mut self) -> WithError<u32> {
    let key = Self::parse_key("#KEY")?;
    let key_info = self.read_key_info_by_id(key)?;
    let ival = KeyData { data8: 5, key, key_info, ..Default::default() };
    let oval = self.read(&ival)?;
    Ok(u32::from_be_bytes(oval.bytes[0..4].try_into().unwrap()))
  }

  /// Enumerate all SMC key names.
  pub fn read_all_keys(&mut self) -> WithError<Vec<String>> {
    let count = self.key_count()?;

    let mut keys = Vec::new();
    for i in 0..count {
      match self.key_by_index(i) {
        Ok(key) => keys.push(key),
        Err(_) => continue,
      }
    }

    Ok(keys)
  }
}

impl Drop for SMC {
  fn drop(&mut self) {
    unsafe {
      IOServiceClose(self.conn);
    }
  }
}

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

  #[test]
  fn parse_acc_clusters_m5_max() {
    // Real acc-clusters bytes captured from M5 Max via ioreg
    #[rustfmt::skip]
    let data = [
      0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    ];
    let (e, p) = parse_acc_clusters(&data).unwrap();
    // Second-highest type (1 = Performance) as ecpu, highest (2 = Super) as pcpu
    assert_eq!(e, "voltage-states23-sram");
    assert_eq!(p, "voltage-states5-sram");
  }

  #[test]
  fn parse_acc_clusters_incomplete() {
    assert!(parse_acc_clusters(&[]).is_none());
    // Single cluster – need both ecpu and pcpu
    assert!(parse_acc_clusters(&[1, 0, 0, 0, 0, 0, 0, 0]).is_none());
  }

  #[test]
  fn parse_cpu_cores_macos26_4field() {
    // Real data captured from macOS 26 machines
    // M5 Max: 18 total, 6 super, 0 efficiency, 12 performance(M-cores)
    assert_eq!(parse_cpu_cores("proc 18:6:0:12"), (12, 6, true));
    // M4 Max: 16 total, 12 performance, 4 efficiency, 0 M-cores
    assert_eq!(parse_cpu_cores("proc 16:12:4:0"), (4, 12, false));
    // M3 Air: 8 total, 4 performance, 4 efficiency, 0 M-cores
    assert_eq!(parse_cpu_cores("proc 8:4:4:0"), (4, 4, false));
  }

  #[test]
  fn parse_cpu_cores_macos15_3field() {
    // Real data: M3 Air on macOS 15.6.1
    assert_eq!(parse_cpu_cores("proc 8:4:4"), (4, 4, false));
  }

  #[test]
  fn parse_cpu_cores_invalid() {
    assert_eq!(parse_cpu_cores(""), (0, 0, false));
    assert_eq!(parse_cpu_cores("garbage"), (0, 0, false));
    assert_eq!(parse_cpu_cores("10:8:2"), (0, 0, false)); // missing "proc " prefix
    assert_eq!(parse_cpu_cores("proc 8"), (0, 0, false)); // too few fields
    assert_eq!(parse_cpu_cores("proc 8:4"), (0, 0, false)); // 2 fields, unsupported
    assert_eq!(parse_cpu_cores("proc 24:6:0:12:6"), (0, 0, false)); // unknown future format
  }

  #[test]
  fn to_mhz_scales() {
    // M4+: KHz scale
    assert_eq!(to_mhz(vec![4608000, 3000000], 1000), vec![4608, 3000]);
    // M1-M3: MHz scale
    assert_eq!(to_mhz(vec![3_000_000_000, 2_000_000_000], 1000 * 1000), vec![3000, 2000]);
    assert_eq!(to_mhz(vec![], 1000), Vec::<u32>::new());
  }

  #[test]
  fn converts_energy_using_the_exact_sample_duration() {
    let watts = watts_from_energy(1_000_000.0, "uJ", Duration::from_micros(250_500)).unwrap();
    assert!((watts - 3.992_016).abs() < 0.000_001);
  }

  #[test]
  fn cfio_channel_filter_preserves_group_subscription_semantics() {
    let items = [("Energy Model", None)];

    assert!(cfio_channel_matches(&items, "Energy Model", ""));
    assert!(cfio_channel_matches(&items, "Energy Model", "CPU Core Performance States"));
    assert!(!cfio_channel_matches(&items, "CPU Stats", "CPU Core Performance States"));
  }

  #[test]
  fn cfio_channel_filter_preserves_subgroup_subscription_semantics() {
    let items = [("CPU Stats", Some("CPU Core Performance States"))];

    assert!(cfio_channel_matches(&items, "CPU Stats", "CPU Core Performance States"));
    assert!(!cfio_channel_matches(&items, "CPU Stats", "CPU Performance States"));
    assert!(!cfio_channel_matches(&items, "GPU Stats", "CPU Core Performance States"));
  }

  #[test]
  fn cfio_channel_filter_empty_items_means_all_channels() {
    assert!(cfio_channel_matches(&[], "CPU Stats", "CPU Core Performance States"));
    assert!(cfio_channel_matches(&[], "Energy Model", ""));
  }
}