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
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
//! Hardware AI inference engine — system classification, bottleneck detection,
//! performance estimation, and workload suitability analysis.
//!
//! This module applies heuristic and rule-based "AI" techniques to raw hardware
//! telemetry to produce actionable insights:
//!
//! - **System Classification**: Workstation, server, laptop, embedded, gaming, etc.
//! - **Bottleneck Detection**: CPU-bound, GPU-bound, memory-bound, I/O-bound
//! - **Performance Tier Scoring**: Low-end to ultra-high-end classification
//! - **Workload Suitability**: ML training, video editing, gaming, web server, etc.
//! - **Hardware Age Estimation**: From model numbers and specifications
//! - **Thermal Envelope Modeling**: TDP and cooling capacity analysis
//! - **Upgrade Recommendations**: Cost-effective improvement suggestions
//! - **Anomaly Detection**: Identify hardware configurations that are unusual
//!
//! # Architecture
//!
//! The engine uses a multi-layer inference pipeline:
//!
//! 1. **Feature Extraction**: Normalized hardware metrics
//! 2. **Rule Engine**: Expert-system rules for classification
//! 3. **Scoring Models**: Weighted scoring for performance tiers
//! 4. **Bayesian Reasoning**: Probabilistic workload suitability
//! 5. **Anomaly Detection**: Statistical deviation from expected configurations
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::hardware_ai::HardwareInferenceEngine;
//!
//! let engine = HardwareInferenceEngine::new().unwrap();
//! let report = engine.full_analysis();
//! println!("System: {:?}", report.classification);
//! println!("Performance tier: {:?}", report.performance_tier);
//! for bottleneck in &report.bottlenecks {
//!     println!("Bottleneck: {} (severity: {}%)", bottleneck.component, bottleneck.severity);
//! }
//! for rec in &report.upgrade_recommendations {
//!     println!("Upgrade: {} (impact: {})", rec.description, rec.expected_impact);
//! }
//! ```

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

// ────────────────────────────────────────────────────────────────────
// Classification types
// ────────────────────────────────────────────────────────────────────

/// System form factor / purpose classification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SystemClass {
    /// Desktop workstation (powerful, tower form factor)
    Workstation,
    /// Server (multi-socket, ECC RAM, IPMI)
    Server,
    /// High-end gaming desktop
    GamingDesktop,
    /// General-purpose desktop
    Desktop,
    /// Laptop (battery, mobile CPU)
    Laptop,
    /// Gaming laptop
    GamingLaptop,
    /// Ultra-portable / ultrabook
    Ultrabook,
    /// Embedded / SBC (Raspberry Pi, Jetson, etc.)
    Embedded,
    /// Virtual machine
    VirtualMachine,
    /// Container / cloud instance
    CloudInstance,
    /// Mini PC / NUC
    MiniPc,
    /// Unknown
    Unknown,
}

/// Performance tier.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum PerformanceTier {
    UltraLow,   // Raspberry Pi, IoT
    Low,        // Atom, Celeron, old hardware
    MidLow,     // i3, Ryzen 3
    Mid,        // i5, Ryzen 5, mid-range GPU
    MidHigh,    // i7, Ryzen 7, high-end GPU
    High,       // i9, Ryzen 9, workstation GPU
    Ultra,      // Threadripper, EPYC, multi-GPU
    Datacenter, // Server-class, 100+ cores
}

/// Bottleneck type — what's limiting performance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BottleneckType {
    CpuBound,
    GpuBound,
    MemoryBound,
    StorageBound,
    NetworkBound,
    ThermalThrottling,
    PowerLimited,
}

/// Confidence for the CPU-versus-GPU imbalance bottleneck. A constant of that rule,
/// chosen for it; it is not a measured probability.
const BOTTLENECK_CONFIDENCE_CPU_GPU_IMBALANCE: f32 = 0.75;
/// Confidence for the RAM-too-low-for-GPU-workloads bottleneck. A constant of that
/// rule, chosen for it; it is not a measured probability.
const BOTTLENECK_CONFIDENCE_RAM_GPU_WORKLOADS: f32 = 0.7;
/// Confidence for the RAM-per-core bottleneck. A constant of that rule, chosen for
/// it; it is not a measured probability.
const BOTTLENECK_CONFIDENCE_RAM_PER_CORE: f32 = 0.65;
/// Confidence for the no-SSD storage bottleneck. A constant of that rule, chosen for
/// it; it is not a measured probability.
const BOTTLENECK_CONFIDENCE_NO_SSD: f32 = 0.85;
/// Confidence for the SATA-with-high-core-count storage bus bottleneck. A constant of
/// that rule, chosen for it; it is not a measured probability.
const BOTTLENECK_CONFIDENCE_SATA_HIGH_CORE: f32 = 0.6;
/// Confidence for the slow server NIC bottleneck. A constant of that rule, chosen for
/// it; it is not a measured probability.
const BOTTLENECK_CONFIDENCE_SLOW_SERVER_NIC: f32 = 0.5;

/// A detected bottleneck.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bottleneck {
    /// Bottleneck type
    pub bottleneck_type: BottleneckType,
    /// Human-readable component name
    pub component: String,
    /// Severity 0-100
    pub severity: u8,
    /// Explanation
    pub reason: String,
    /// Confidence 0.0-1.0. Not a measured probability: it is the fixed constant of
    /// the rule that fired (one of the `BOTTLENECK_CONFIDENCE_*` constants in this
    /// module), chosen by the code.
    pub confidence: f32,
}

/// Workload type.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Workload {
    /// Machine learning training (GPU VRAM, tensor cores)
    MlTraining,
    /// ML inference (GPU, lower VRAM requirement)
    MlInference,
    /// Video editing / production (GPU, fast storage, RAM)
    VideoEditing,
    /// 3D rendering / CAD (GPU, multi-core CPU)
    Rendering3D,
    /// Gaming (GPU, CPU single-thread, fast storage)
    Gaming,
    /// Software compilation (multi-core CPU, RAM, fast storage)
    Compilation,
    /// Web server (network, RAM, multi-core)
    WebServer,
    /// Database server (storage IOPS, RAM, multi-core)
    DatabaseServer,
    /// Virtualization (cores, RAM, VT-x/AMD-V)
    Virtualization,
    /// Scientific computing (FP performance, RAM)
    ScientificComputing,
    /// General office / productivity
    OfficeProductivity,
    /// Media streaming
    MediaStreaming,
    /// Network appliance (NIC throughput, low latency)
    NetworkAppliance,
}

/// Confidence in the ML training suitability score. A constant of that rule, chosen
/// for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_ML_TRAINING: f32 = 0.7;
/// Confidence in the ML inference suitability score. A constant of that rule, chosen
/// for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_ML_INFERENCE: f32 = 0.75;
/// Confidence in the gaming suitability score. A constant of that rule, chosen for it;
/// it is not a measured probability.
const WORKLOAD_CONFIDENCE_GAMING: f32 = 0.8;
/// Confidence in the video editing suitability score. A constant of that rule, chosen
/// for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_VIDEO_EDITING: f32 = 0.7;
/// Confidence in the compilation suitability score. A constant of that rule, chosen
/// for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_COMPILATION: f32 = 0.8;
/// Confidence in the web server suitability score. A constant of that rule, chosen for
/// it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_WEB_SERVER: f32 = 0.65;
/// Confidence in the database server suitability score. A constant of that rule, chosen
/// for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_DATABASE_SERVER: f32 = 0.65;
/// Confidence in the virtualization suitability score. A constant of that rule, chosen
/// for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_VIRTUALIZATION: f32 = 0.7;
/// Confidence in the office productivity suitability score. A constant of that rule,
/// chosen for it; it is not a measured probability.
const WORKLOAD_CONFIDENCE_OFFICE_PRODUCTIVITY: f32 = 0.9;

/// Workload suitability score.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkloadSuitability {
    pub workload: Workload,
    /// Score 0-100 (100 = perfectly suited)
    pub score: u8,
    /// Confidence 0.0-1.0. Not a measured probability: it is the fixed constant of the
    /// rule for this workload (one of the `WORKLOAD_CONFIDENCE_*` constants in this
    /// module), chosen by the code.
    pub confidence: f32,
    /// Key limiting factors
    pub limiting_factors: Vec<String>,
    /// Key strengths for this workload
    pub strengths: Vec<String>,
}

/// Confidence in an age estimate when both the CPU and the GPU model matched a
/// year table. A constant of that rule, chosen for it; it is not a measured
/// probability.
const AGE_CONFIDENCE_CPU_AND_GPU: f32 = 0.85;

/// Confidence in an age estimate when only one of the CPU and GPU models matched
/// a year table. A constant of that rule, chosen for it; it is not a measured
/// probability.
const AGE_CONFIDENCE_CPU_OR_GPU: f32 = 0.65;

/// Inferred hardware age.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareAge {
    /// Estimated CPU generation year
    pub cpu_year: Option<u16>,
    /// Estimated GPU generation year
    pub gpu_year: Option<u16>,
    /// Overall system age estimate (years), from the release year of the CPU
    /// and/or GPU model that matched a table. `None` when neither matched: the
    /// age is not guessed from core count or drive type.
    pub estimated_age_years: Option<f32>,
    /// Confidence in `estimated_age_years`: one of the `AGE_CONFIDENCE_*`
    /// constants, fixed by which rule matched. It is a constant of the rule, not
    /// a measured probability. `None` when no model table matched.
    pub confidence: Option<f32>,
    /// Reasoning
    pub reasoning: String,
}

/// Thermal envelope analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThermalEnvelope {
    /// Estimated total system TDP (watts): the CPU and GPU figures plus a flat
    /// 30 W for RAM, storage and board. `None` unless both terms are known, since
    /// a total with one term missing would pass for a real total.
    pub estimated_total_tdp_watts: Option<f32>,
    /// CPU TDP (watts), or `None` when neither the platform nor the name table
    /// gave one.
    pub cpu_tdp_watts: Option<f32>,
    /// Whether [`Self::cpu_tdp_watts`] is the package power limit the platform
    /// enforces or this crate's name table standing in for it.
    ///
    /// False on Windows and macOS, which expose no such limit unprivileged, so
    /// the figure there is one number for a whole processor family: `ryzen 9`
    /// answers 120 W, which is right for a 9900X and wrong for a 9950X (170 W)
    /// and a 5950X (105 W). The total beside it can mix a measured GPU budget
    /// with a guessed CPU one, and this is how a consumer tells.
    pub cpu_tdp_measured: bool,
    /// GPU TDP (watts), or `None` when neither a driver cap nor the name table
    /// gave one.
    pub gpu_tdp_watts: Option<f32>,
    /// How many adapters [`Self::gpu_tdp_watts`] is the sum of.
    ///
    /// `1` when the figure is the name table's, which prices one card, and `0`
    /// when there is no figure. Before this existed the figure was the *first* adapter's
    /// cap whatever the machine held, so a desktop with two RTX 3090 Ti was
    /// graded on half its GPU budget.
    pub gpu_adapters_counted: u32,
    /// Whether [`Self::gpu_tdp_watts`] is the power cap the driver enforces or
    /// this crate's name table standing in for it.
    ///
    /// The two are different claims and were reported identically. The name
    /// table returns 350 W for anything matching "3090"; the RTX 3090 Ti this
    /// engine was audited on enforces 450 W, and NVML reports that figure to
    /// the same process. A consumer that cannot tell a read cap from a guessed
    /// one cannot tell which of its conclusions rest on the hardware.
    pub gpu_tdp_measured: bool,
    /// Thermal headroom assessment
    pub headroom: ThermalHeadroom,
    /// Cooling adequacy score (0-100), or `None` when the headroom is
    /// `Unknown`. A score for an unknown is a number nobody measured.
    pub cooling_score: Option<u8>,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Thermal headroom classification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThermalHeadroom {
    /// Plenty of cooling capacity
    Ample,
    /// Adequate cooling
    Adequate,
    /// Marginal — may throttle under sustained load
    Marginal,
    /// Insufficient — likely thermal throttling
    Insufficient,
    /// Unknown — insufficient data
    Unknown,
}

/// Upgrade recommendation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpgradeRecommendation {
    /// Component to upgrade
    pub component: String,
    /// Current state
    pub current: String,
    /// Recommended upgrade
    pub recommended: String,
    /// Description of the improvement
    pub description: String,
    /// Expected performance impact (e.g., "20-30% faster compilation")
    pub expected_impact: String,
    /// Priority 1-10 (10 = most impactful)
    pub priority: u8,
    /// Estimated relative cost (1 = cheap, 5 = expensive)
    pub cost_tier: u8,
}

/// Hardware anomaly — something unusual in the configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareAnomaly {
    /// What's anomalous
    pub description: String,
    /// Severity (info, warning, critical)
    pub severity: AnomalySeverity,
    /// Possible explanation
    pub explanation: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnomalySeverity {
    Info,
    Warning,
    Critical,
}

// ────────────────────────────────────────────────────────────────────
// Full analysis report
// ────────────────────────────────────────────────────────────────────

/// Score of the virtual-machine rule. A constant of that rule, chosen for it; it is
/// not a measured probability.
const CLASSIFICATION_CONFIDENCE_VIRTUAL_MACHINE: f32 = 0.95;

/// Weight of the server-CPU indicator in the server score. A constant of that rule,
/// chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_CPU: f32 = 0.35;
/// Weight of the ECC-memory indicator in the server score. A constant of that rule,
/// chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_ECC: f32 = 0.2;
/// Weight of the 16-or-more-physical-cores indicator in the server score. A constant of
/// that rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_PHYSICAL_CORES: f32 = 0.15;
/// Weight of the 64-GB-or-more-RAM indicator in the server score. A constant of that
/// rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_RAM: f32 = 0.1;
/// Weight of the multi-NUMA-node indicator in the server score. A constant of that
/// rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_NUMA: f32 = 0.15;
/// Weight of the server-chassis indicator in the server score. A constant of that
/// rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_CHASSIS: f32 = 0.3;
/// Weight of the no-battery indicator in the server score. A constant of that rule,
/// chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_NO_BATTERY: f32 = 0.05;
/// Weight of the two-or-more-NICs indicator in the server score. A constant of that
/// rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_SERVER_NICS: f32 = 0.1;
/// Cap on the server score. A constant of that rule, chosen for it; it is not a
/// measured probability.
const CLASSIFICATION_CONFIDENCE_SERVER_CAP: f32 = 0.95;

/// Weight of the mobile-chassis indicator in the laptop score. A constant of that rule,
/// chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_LAPTOP_MOBILE_CHASSIS: f32 = 0.6;
/// Weight of the battery indicator in the laptop score, where the chassis did not
/// answer. A constant of that rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_LAPTOP_BATTERY: f32 = 0.25;
/// Weight of the eight-or-fewer-physical-cores indicator in the laptop score. A
/// constant of that rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_LAPTOP_LOW_CORES: f32 = 0.05;
/// Weight of the 32-GB-or-less-RAM indicator in the laptop score. A constant of that
/// rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_WEIGHT_LAPTOP_LOW_RAM: f32 = 0.05;
/// Cap on the laptop score. A constant of that rule, chosen for it; it is not a
/// measured probability.
const CLASSIFICATION_CONFIDENCE_LAPTOP_CAP: f32 = 0.95;
/// Factor applied to the laptop score when the laptop is a gaming laptop. A constant of
/// that rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_SCALE_GAMING_LAPTOP: f32 = 0.9;
/// Factor applied to the laptop score when the laptop is an ultrabook. A constant of
/// that rule, chosen for it; it is not a measured probability.
const CLASSIFICATION_SCALE_ULTRABOOK: f32 = 0.8;

/// Score of the workstation rule. A constant of that rule, chosen for it; it is not a
/// measured probability.
const CLASSIFICATION_CONFIDENCE_WORKSTATION: f32 = 0.6;
/// Score of the gaming-desktop rule. A constant of that rule, chosen for it; it is not
/// a measured probability.
const CLASSIFICATION_CONFIDENCE_GAMING_DESKTOP: f32 = 0.6;
/// Score of the desktop fallback rule. A constant of that rule, chosen for it; it is
/// not a measured probability.
const CLASSIFICATION_CONFIDENCE_DESKTOP: f32 = 0.5;
/// Score of the embedded rule. A constant of that rule, chosen for it; it is not a
/// measured probability.
const CLASSIFICATION_CONFIDENCE_EMBEDDED: f32 = 0.8;
/// Score of the mini-PC rule. A constant of that rule, chosen for it; it is not a
/// measured probability.
const CLASSIFICATION_CONFIDENCE_MINI_PC: f32 = 0.7;

/// Complete hardware analysis report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareAnalysisReport {
    /// System classification
    pub classification: SystemClass,
    /// Rule score for the classification, 0.0-1.0, or `None` when the class is
    /// `Unknown`: an unknown carries no confidence, and a machine none of whose
    /// inputs was read is not classified at all. Not a measured probability: it is
    /// built from the `CLASSIFICATION_*` constants in this module (the weights, scales
    /// and caps of the rules that scored the winning class), chosen by the code.
    pub classification_confidence: Option<f32>,
    /// Performance tier, or `None` when no hardware input was read.
    pub performance_tier: Option<PerformanceTier>,
    /// Overall performance score (0-100), or `None` when no hardware input was read:
    /// the score is computed from the features, and a default feature set would score
    /// zero-valued cores and memory as if they had been measured.
    pub performance_score: Option<u8>,
    /// Detected bottlenecks
    pub bottlenecks: Vec<Bottleneck>,
    /// Workload suitability scores
    pub workload_scores: Vec<WorkloadSuitability>,
    /// Hardware age estimate
    pub hardware_age: HardwareAge,
    /// Thermal analysis
    pub thermal_envelope: ThermalEnvelope,
    /// Upgrade recommendations
    pub upgrade_recommendations: Vec<UpgradeRecommendation>,
    /// Anomalies detected
    pub anomalies: Vec<HardwareAnomaly>,
    /// Hardware fingerprint (unique identifier based on hardware config)
    pub hardware_fingerprint: String,
}

// ────────────────────────────────────────────────────────────────────
// Extracted hardware features (normalized)
// ────────────────────────────────────────────────────────────────────

/// Normalized hardware features used by the inference engine.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct HardwareFeatures {
    // CPU features. `None` is unread; a reader that failed used to leave `0`,
    // which scored as a machine with no cores or no clock.
    cpu_cores_physical: Option<u32>,
    cpu_cores_logical: Option<u32>,
    cpu_max_freq_mhz: Option<u32>,
    // `None` when no non-empty name or vendor was read. These were `""` when the
    // reader found nothing, which every consumer treated as a value.
    cpu_model: Option<String>,
    cpu_vendor: Option<String>,
    is_server_cpu: bool,
    /// ECC state. No reader sets it yet, so it is `None` everywhere. It used to be
    /// a `bool` that defaulted to `false`, which read as "no ECC".
    has_ecc: Option<bool>,
    cpu_tdp_watts: Option<f32>,
    /// Whether `cpu_tdp_watts` is the package power limit the platform enforces
    /// or the model-name table's stand-in for it. False on Windows and macOS,
    /// which expose no such limit to an unprivileged reader.
    cpu_tdp_measured: bool,

    // Memory features. `None` is unread. Used to be `0.0`, which scored as a machine
    // with no RAM and fired the RAM-upgrade advice.
    ram_total_gb: Option<f32>,
    ram_channels: u32,
    ram_speed_mhz: u32,

    // GPU features. `None` is unread throughout. `has_discrete_gpu` is read from the
    // GPU monitor's `integrated` flag; `gpu_vram_gb` from its memory total. A
    // failed or empty VRAM read used to leave `0.0`, which read as a card with no
    // memory.
    has_discrete_gpu: Option<bool>,
    gpu_count: u32,
    gpu_model: String,
    gpu_vram_gb: Option<f32>,
    /// Not read by any reader, so always `None`. Used to be inferred from the GPU
    /// model name ("rtx", "a100", "apple m"), which is a guess about the silicon.
    has_tensor_cores: Option<bool>,
    /// Not read by any reader, so always `None`. Used to be inferred from the name.
    has_rt_cores: Option<bool>,
    gpu_tdp_watts: Option<f32>,
    /// Whether `gpu_tdp_watts` is the cap the driver enforces or the name
    /// table's stand-in for it. The thermal envelope reports which, because a
    /// measured 450 W and a guessed 350 W are different claims about the same
    /// card and only one of them was checked against the hardware.
    gpu_tdp_measured: bool,
    /// How many adapters `gpu_tdp_watts` is the sum of. `1` when the figure is
    /// the name table's, which is keyed on one model name and prices one card,
    /// and `0` when there is no figure.
    gpu_adapters_counted: u32,

    // Storage features. `has_ssd` and `has_nvme` are `Some(false)` only when every
    // disk was enumerated and classified as lacking the property. A virtio disk, a
    // failed enumeration or an unknown media type leaves them `None`.
    has_nvme: Option<bool>,
    has_ssd: Option<bool>,
    total_storage_gb: Option<f32>,
    /// The drive holding the root or system volume, when it could be identified and
    /// classified. `None` otherwise, never the first disk enumerated.
    boot_drive_type: Option<String>,

    // Platform features
    has_battery: bool,
    /// SMBIOS chassis class as read, or `None` when the enclosure was not read or
    /// its code is not one the reader maps. Used to be a `"Unknown"` string, and
    /// a Windows fallback guessed "Desktop" or "Laptop" from the battery.
    chassis_type: Option<String>,
    /// Whether this is a virtual machine, or `None` when the product name or model
    /// was not read (the query failed or returned nothing). Used to be a `bool` that
    /// stayed `false` when unread, which counted as a physical-machine reading.
    is_virtual: Option<bool>,
    /// NUMA node count, or `None` when not read. Windows used to store a constant 1.
    numa_nodes: Option<u32>,
    pcie_gen: u32,

    // Network. Both are `None` when no physical interface's speed or count was read.
    // Used to be `0.0` and `0`, and "slow network" advice fired on them.
    max_nic_speed_gbps: Option<f32>,
    /// Physical network interfaces only. Loopback and virtual interfaces (veth,
    /// docker, bridges, tun/tap, vEthernet, WSL) are excluded.
    nic_count: Option<u32>,
}

impl HardwareFeatures {
    /// The chassis class for matching, where unread is the empty string. Matches
    /// nothing, so an unread chassis never satisfies a "Server" or "Laptop" test.
    fn chassis(&self) -> &str {
        self.chassis_type.as_deref().unwrap_or("")
    }

    /// RAM is known and at least `gb`. An unread RAM size satisfies no threshold.
    fn ram_at_least(&self, gb: f32) -> bool {
        self.ram_total_gb.is_some_and(|v| v >= gb)
    }

    /// RAM is known and below `gb`. An unread RAM size never triggers a shortage.
    fn ram_below(&self, gb: f32) -> bool {
        self.ram_total_gb.is_some_and(|v| v < gb)
    }

    /// VRAM is known and at least `gb`.
    fn vram_at_least(&self, gb: f32) -> bool {
        self.gpu_vram_gb.is_some_and(|v| v >= gb)
    }

    /// VRAM is known and below `gb`.
    fn vram_below(&self, gb: f32) -> bool {
        self.gpu_vram_gb.is_some_and(|v| v < gb)
    }

    /// A discrete GPU was read. `None` is not evidence of an integrated-only machine.
    fn is_discrete_gpu(&self) -> bool {
        self.has_discrete_gpu == Some(true)
    }
}

// ────────────────────────────────────────────────────────────────────
// Inference engine
// ────────────────────────────────────────────────────────────────────

/// Read a CIM enum property that may arrive as a number or as its friendly name.
///
/// `ConvertTo-Json` serialises `MSFT_PhysicalDisk.MediaType` and `.BusType` using
/// PowerShell's display formatting, so they come back as `"SSD"` and `"NVMe"`
/// rather than as `4` and `17`. Code that reached for `as_u64()` alone got
/// `None` for every disk on every Windows machine and never noticed, because the
/// fallback beneath it was a plausible-looking `0`.
///
/// Returns `None` when the property is absent or names nothing known --- which is
/// a real answer for a USB mass-storage gadget reporting `"Unspecified"`, and is
/// not the same as "this is a hard disk".
#[cfg(target_os = "windows")]
fn wmi_enum(value: Option<&serde_json::Value>, names: &[(&str, u64)]) -> Option<u64> {
    let value = value?;
    if let Some(n) = value.as_u64() {
        return Some(n);
    }
    let text = value.as_str()?.trim().to_ascii_lowercase();
    names
        .iter()
        .find(|(name, _)| *name == text)
        .map(|(_, code)| *code)
}

/// Whether any input `classify_system` reads was read from the machine.
///
/// A default feature set is every field at zero, empty or false, which is also what
/// a reader that failed leaves behind, so those values are not evidence and do not
/// count. A field counts when its value can only have come from a reading: a
/// non-empty string, a count above zero, a measured figure above zero, or a `true`
/// flag that the reader sets only once it has detected the thing.
///
/// Not counted: `numa_nodes`, `has_ecc`, `ram_channels`, `ram_speed_mhz` and `pcie_gen`,
/// which no reader sets; `is_server_cpu`, derived from `cpu_model`; and the TDP figures,
/// which are the name table where no reading exists. A chassis that is `None` is one
/// the reader did not map, so it is not counted.
fn anything_read(f: &HardwareFeatures) -> bool {
    f.cpu_cores_physical.is_some_and(|c| c > 0)
        || f.cpu_cores_logical.is_some_and(|c| c > 0)
        || f.cpu_max_freq_mhz.is_some_and(|c| c > 0)
        || f.cpu_model.is_some()
        || f.cpu_vendor.is_some()
        || f.ram_total_gb.is_some_and(|v| v > 0.0)
        || f.is_discrete_gpu()
        || f.gpu_count > 0
        || !f.gpu_model.is_empty()
        || f.has_battery
        || f.is_virtual == Some(true)
        || f.chassis_type.is_some()
        || f.nic_count.is_some_and(|n| n > 0)
        || f.max_nic_speed_gbps.is_some_and(|v| v > 0.0)
}

/// Parse the output of a PowerShell `ConvertTo-Json` call, which emits an object for a
/// single item and an array for several. `None` when there was no output or it did not
/// parse: the query failed or matched nothing, which is not the same as an empty list
/// that was read.
#[cfg(target_os = "windows")]
fn json_items(text: &str) -> Option<Vec<serde_json::Value>> {
    let text = text.trim();
    if text.starts_with('[') {
        serde_json::from_str(text).ok()
    } else {
        serde_json::from_str::<serde_json::Value>(text)
            .ok()
            .map(|v| vec![v])
    }
}

/// The label for an SMBIOS chassis code read from `/sys/class/dmi/id/chassis_type`.
/// A code this does not map is `None`: unread, not a label.
#[cfg(target_os = "linux")]
fn dmi_chassis_label(code: &str) -> Option<&'static str> {
    match code {
        "3" | "4" | "5" | "6" | "7" => Some("Desktop"),
        "8" | "9" | "10" | "14" => Some("Laptop"),
        "11" | "12" => Some("Handheld"),
        "13" => Some("All-in-One"),
        "17" | "23" => Some("Server"),
        "35" | "36" => Some("Mini PC"),
        _ => None,
    }
}

/// A sysfs frequency file's text, in kHz, as whole MHz. `None` when it does not parse or
/// is zero.
#[cfg(target_os = "linux")]
fn khz_as_mhz(text: &str) -> Option<u32> {
    text.trim()
        .parse::<u32>()
        .ok()
        .map(|khz| khz / 1000)
        .filter(|&mhz| mhz > 0)
}

/// The whole-disk name for a block device named in `/proc/mounts`: `nvme0n1` for
/// `nvme0n1p2`, `sda` for `sda2`. `None` for a device this does not map to a physical
/// disk (device-mapper, virtio `vda`, overlay).
#[cfg(target_os = "linux")]
fn base_disk_name(name: &str) -> Option<&str> {
    if name.starts_with("nvme") {
        let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
        Some(match trimmed.strip_suffix('p') {
            Some(disk) if disk.ends_with(|c: char| c.is_ascii_digit()) => disk,
            _ => name,
        })
    } else if name.starts_with("sd") {
        Some(name.trim_end_matches(|c: char| c.is_ascii_digit()))
    } else {
        None
    }
}

#[cfg(all(test, target_os = "linux"))]
mod sysfs_parse_tests {
    use super::*;

    #[test]
    fn cpufreq_is_read_in_khz_and_reported_in_mhz() {
        // cpuinfo_max_freq as sysfs writes it: a kHz figure with a newline.
        assert_eq!(khz_as_mhz("5700000\n"), Some(5700));
        assert_eq!(khz_as_mhz("2400000"), Some(2400));
        // Absent, empty, or non-numeric is unread.
        assert_eq!(khz_as_mhz(""), None);
        assert_eq!(khz_as_mhz("0\n"), None);
        assert_eq!(khz_as_mhz("n/a"), None);
    }

    #[test]
    fn a_root_partition_maps_to_its_whole_disk() {
        assert_eq!(base_disk_name("nvme0n1p2"), Some("nvme0n1"));
        assert_eq!(base_disk_name("nvme0n1"), Some("nvme0n1"));
        assert_eq!(base_disk_name("sda2"), Some("sda"));
        assert_eq!(base_disk_name("sda"), Some("sda"));
        // Devices that are not a physical disk this reader classifies.
        assert_eq!(base_disk_name("vda1"), None);
        assert_eq!(base_disk_name("mapper/cryptroot"), None);
        assert_eq!(base_disk_name("overlay"), None);
    }
}

#[cfg(all(test, target_os = "linux"))]
mod dmi_chassis_tests {
    use super::*;

    #[test]
    fn dmi_codes_map_to_labels_and_unmapped_codes_stay_unread() {
        assert_eq!(dmi_chassis_label("3"), Some("Desktop"));
        assert_eq!(dmi_chassis_label("10"), Some("Laptop"));
        assert_eq!(dmi_chassis_label("17"), Some("Server"));
        // SMBIOS 2 and 40+ codes the reader does not map. Previously "Unknown".
        assert_eq!(dmi_chassis_label("2"), None);
        assert_eq!(dmi_chassis_label(""), None);
    }
}

/// The hardware inference engine.
pub struct HardwareInferenceEngine {
    features: HardwareFeatures,
}

impl HardwareInferenceEngine {
    /// Create a new inference engine, extracting hardware features from the system.
    pub fn new() -> Result<Self, IronError> {
        let mut engine = Self {
            features: HardwareFeatures::default(),
        };
        engine.extract_features();
        Ok(engine)
    }

    /// Create from pre-populated features (for testing or external data).
    pub fn from_features(features_json: &str) -> Result<Self, IronError> {
        let features: HardwareFeatures = serde_json::from_str(features_json)
            .map_err(|e| IronError::Parse(format!("Invalid features JSON: {}", e)))?;
        Ok(Self { features })
    }

    /// Run the full analysis pipeline.
    pub fn full_analysis(&self) -> HardwareAnalysisReport {
        let (classification, class_confidence) = self.classify_system();
        let any_read = anything_read(&self.features);
        let (tier, score) = self.compute_performance_tier();
        let bottlenecks = self.detect_bottlenecks();
        let workloads = self.score_workloads();
        let age = self.estimate_hardware_age();
        let thermal = self.analyze_thermal_envelope();
        let upgrades = self.suggest_upgrades(&bottlenecks);
        let anomalies = self.detect_anomalies();
        let fingerprint = self.compute_fingerprint();

        HardwareAnalysisReport {
            classification,
            classification_confidence: class_confidence,
            // A machine nothing was read from has no tier, as it has no score.
            performance_tier: any_read.then_some(tier),
            performance_score: any_read.then_some(score),
            bottlenecks,
            workload_scores: workloads,
            hardware_age: age,
            thermal_envelope: thermal,
            upgrade_recommendations: upgrades,
            anomalies,
            hardware_fingerprint: fingerprint,
        }
    }

    // ────────────────────────────────────────────────────────────────
    // Feature extraction
    // ────────────────────────────────────────────────────────────────

    fn extract_features(&mut self) {
        self.extract_cpu_features();
        self.extract_memory_features();
        self.extract_gpu_features();
        self.extract_storage_features();
        self.extract_platform_features();
        self.extract_network_features();
    }

    /// Name and manufacturer from the `Win32_Processor` JSON. Each is `None` when
    /// absent, not a string, or blank after trimming. WMI pads `Name` with spaces,
    /// so it is trimmed before the emptiness check.
    ///
    /// `ConvertTo-Json` emits an array rather than an object when there is more than
    /// one socket. Every socket in one machine carries the same model, so a field is
    /// taken only when all elements agree; if they disagree, or one lacks it, it is
    /// `None`. This used to read only the object form, so a multi-socket machine had
    /// no CPU identity at all.
    #[cfg(any(target_os = "windows", test))]
    fn windows_cpu_identity(json: &serde_json::Value) -> (Option<String>, Option<String>) {
        let elements: Vec<&serde_json::Value> = match json.as_array() {
            Some(items) => items.iter().collect(),
            None => vec![json],
        };
        let text = |item: &serde_json::Value, key: &str| {
            item.get(key)
                .and_then(|v| v.as_str())
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
        };
        let agreed = |key: &str| {
            let mut values = elements.iter().map(|item| text(item, key));
            let first = values.next()??;
            values
                .all(|v| v.as_deref() == Some(first.as_str()))
                .then_some(first)
        };
        (agreed("Name"), agreed("Manufacturer"))
    }

    fn extract_cpu_features(&mut self) {
        #[cfg(target_os = "linux")]
        {
            if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
                let mut model = String::new();
                let mut cores = std::collections::HashSet::new();
                let mut logical = 0u32;
                let mut vendor = String::new();

                for line in cpuinfo.lines() {
                    if line.starts_with("model name") {
                        if let Some(m) = line.split(':').nth(1) {
                            model = m.trim().to_string();
                        }
                    }
                    if line.starts_with("vendor_id") {
                        if let Some(v) = line.split(':').nth(1) {
                            vendor = v.trim().to_string();
                        }
                    }
                    if line.starts_with("core id") {
                        if let Some(c) = line.split(':').nth(1) {
                            if let Ok(id) = c.trim().parse::<u32>() {
                                cores.insert(id);
                            }
                        }
                    }
                    if line.starts_with("processor") {
                        logical += 1;
                    }
                }

                self.features.cpu_model = (!model.is_empty()).then_some(model);
                self.features.cpu_vendor = (!vendor.is_empty()).then_some(vendor);
                let physical = if cores.is_empty() {
                    logical
                } else {
                    cores.len() as u32
                };
                // Zero means no line was found, which is unread, not a 0-core machine.
                self.features.cpu_cores_physical = (physical > 0).then_some(physical);
                self.features.cpu_cores_logical = (logical > 0).then_some(logical);
            }

            // The maximum clock. The "cpu MHz" lines in /proc/cpuinfo are each core's
            // current clock, and used to be taken as the maximum. cpuinfo_max_freq is
            // the rated maximum, in kHz. Absent where cpufreq is not exposed: `None`.
            self.features.cpu_max_freq_mhz =
                std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq")
                    .ok()
                    .as_deref()
                    .and_then(khz_as_mhz);
        }

        #[cfg(target_os = "windows")]
        {
            if let Ok(output) = std::process::Command::new("powershell")
                .args(["-NoProfile", "-Command",
                    "Get-CimInstance Win32_Processor | Select-Object Name,Manufacturer,NumberOfCores,NumberOfLogicalProcessors,MaxClockSpeed | ConvertTo-Json"])
                .output()
            {
                let text = String::from_utf8(output.stdout).unwrap_or_default();
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
                    // WMI pads `Name` to a fixed width: this machine reports
                    // "AMD Ryzen 9 9900X 12-Core Processor            ". The
                    // padding reached the age-estimate `reasoning` string and the
                    // hardware fingerprint, so two machines differing only in how
                    // WMI padded them would fingerprint apart.
                    // Absent or empty is unread: `None`, never `""`.
                    (self.features.cpu_model, self.features.cpu_vendor) =
                        Self::windows_cpu_identity(&json);
                    // Absent from the JSON is unread, not 0 cores or 0 MHz.
                    self.features.cpu_cores_physical = json
                        .get("NumberOfCores")
                        .and_then(|v| v.as_u64())
                        .map(|v| v as u32);
                    self.features.cpu_cores_logical = json
                        .get("NumberOfLogicalProcessors")
                        .and_then(|v| v.as_u64())
                        .map(|v| v as u32);
                    self.features.cpu_max_freq_mhz = json
                        .get("MaxClockSpeed")
                        .and_then(|v| v.as_u64())
                        .map(|v| v as u32);
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            if let Ok(output) = std::process::Command::new("sysctl")
                .args(["-n", "machdep.cpu.brand_string"])
                .output()
            {
                self.features.cpu_model = String::from_utf8(output.stdout)
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
            }
            if let Ok(output) = std::process::Command::new("sysctl")
                .args(["-n", "hw.physicalcpu"])
                .output()
            {
                self.features.cpu_cores_physical = String::from_utf8(output.stdout)
                    .unwrap_or_default()
                    .trim()
                    .parse()
                    .ok();
            }
            if let Ok(output) = std::process::Command::new("sysctl")
                .args(["-n", "hw.logicalcpu"])
                .output()
            {
                self.features.cpu_cores_logical = String::from_utf8(output.stdout)
                    .unwrap_or_default()
                    .trim()
                    .parse()
                    .ok();
            }
        }

        // Infer CPU class
        let model_lower = self
            .features
            .cpu_model
            .as_deref()
            .unwrap_or("")
            .to_lowercase();
        self.features.is_server_cpu = model_lower.contains("xeon")
            || model_lower.contains("epyc")
            || model_lower.contains("threadripper")
            || model_lower.contains("platinum")
            || model_lower.contains("gold")
            || model_lower.contains("silver");

        // Infer TDP from model
        // The package power limit the platform enforces, where one is readable,
        // and the model-name table only where it is not.
        match Self::measured_cpu_power_cap_watts() {
            Some(watts) => {
                self.features.cpu_tdp_watts = Some(watts);
                self.features.cpu_tdp_measured = true;
            }
            None => {
                self.features.cpu_tdp_watts = Self::infer_cpu_tdp(&model_lower);
                self.features.cpu_tdp_measured = false;
            }
        }
    }

    fn extract_memory_features(&mut self) {
        #[cfg(target_os = "linux")]
        {
            if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
                for line in meminfo.lines() {
                    if line.starts_with("MemTotal:") {
                        if let Some(kb) = line.split_whitespace().nth(1) {
                            if let Ok(k) = kb.parse::<u64>() {
                                self.features.ram_total_gb = Some(k as f32 / 1_048_576.0);
                            }
                        }
                    }
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            if let Ok(output) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "(Get-CimInstance Win32_OperatingSystem).TotalVisibleMemorySize",
                ])
                .output()
            {
                let text = String::from_utf8(output.stdout).unwrap_or_default();
                if let Ok(kb) = text.trim().parse::<u64>() {
                    self.features.ram_total_gb = Some(kb as f32 / 1_048_576.0);
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            if let Ok(output) = std::process::Command::new("sysctl")
                .args(["-n", "hw.memsize"])
                .output()
            {
                let text = String::from_utf8(output.stdout).unwrap_or_default();
                if let Ok(bytes) = text.trim().parse::<u64>() {
                    self.features.ram_total_gb = Some(bytes as f32 / 1_073_741_824.0);
                }
            }
        }
    }

    fn extract_gpu_features(&mut self) {
        // Model names and the adapter count come from the platform's enumeration.
        // Whether an adapter is discrete, and its memory, come from the GPU monitor.
        #[cfg(target_os = "linux")]
        {
            if let Ok(entries) = std::fs::read_dir("/sys/class/drm") {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with("card") && !name.contains('-') {
                        let label = std::fs::read_to_string(entry.path().join("device/label"))
                            .or_else(|_| {
                                std::fs::read_to_string(entry.path().join("device/product_name"))
                            })
                            .unwrap_or_default()
                            .trim()
                            .to_string();

                        if !label.is_empty() {
                            self.features.gpu_model = label;
                            self.features.gpu_count += 1;
                        }
                    }
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            if let Ok(output) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "Get-CimInstance Win32_VideoController | Select-Object Name | ConvertTo-Json",
                ])
                .output()
            {
                let text = String::from_utf8(output.stdout).unwrap_or_default();
                for gpu in json_items(&text).unwrap_or_default() {
                    if let Some(name) = gpu
                        .get("Name")
                        .and_then(|v| v.as_str())
                        .filter(|n| !n.is_empty())
                    {
                        self.features.gpu_model = name.to_string();
                        self.features.gpu_count += 1;
                    }
                }
            }
        }

        // Discrete and VRAM come from the GPU monitor, which reports whether each adapter
        // is integrated and its memory total. The model name is not used: "Radeon" names
        // integrated APUs as well as cards, and a name does not say how much memory the
        // part has. The Windows registry VRAM read is no longer used here; the monitor's
        // total for NVIDIA cards comes from NVML.
        let adapters = Self::gpu_adapters();
        let (discrete, vram) = Self::discrete_gpu_and_vram(adapters.as_deref());
        self.features.has_discrete_gpu = discrete;
        self.features.gpu_vram_gb = vram;

        // Tensor and RT cores are not read by any reader. They used to be inferred from
        // the model name ("rtx", "a100", "apple m"), which says what the silicon is
        // called, not whether it has the units.
        self.features.has_tensor_cores = None;
        self.features.has_rt_cores = None;

        // The driver's own enforced power cap, where there is one, and the name
        // table only where there is not.
        //
        // `infer_gpu_tdp` returns 350 W for anything matching "3090"; the RTX
        // 3090 Ti in this machine reports an enforced cap of 450 W through the
        // same crate's GPU monitor, in the same process. That figure feeds
        // `analyze_thermal_envelope`, so a 100 W error propagates into a cooling
        // verdict -- and the correct number was already being read on another
        // surface, which is the shape recorded in the handoff as "the reader was
        // in the same binary".
        let gpu_lower = self.features.gpu_model.to_lowercase();
        let measured = adapters
            .as_deref()
            .and_then(Self::measured_gpu_power_caps_watts);
        match measured {
            Some((watts, counted)) => {
                self.features.gpu_tdp_watts = Some(watts);
                self.features.gpu_tdp_measured = true;
                self.features.gpu_adapters_counted = counted;
            }
            None => {
                // One name, one figure. The table is keyed on the model string
                // and this machine has one of those however many cards it has,
                // so an unmeasured multi-GPU machine is priced as one card
                // rather than multiplied by a count the table knows nothing
                // about. `gpu_adapters_counted` says so: 1, or 0 when the table
                // has no match and there is no figure.
                let table = Self::infer_gpu_tdp(&gpu_lower);
                self.features.gpu_adapters_counted = u32::from(table.is_some());
                self.features.gpu_tdp_watts = table;
                self.features.gpu_tdp_measured = false;
            }
        }
    }

    /// The GPU monitor's adapters, or `None` when the monitor could not be created or
    /// could not enumerate them. Taken once per analysis: a snapshot queries every
    /// adapter, which costs seconds.
    fn gpu_adapters() -> Option<Vec<crate::GpuInfo>> {
        let monitor = crate::UnifiedMonitor::new().ok()?;
        monitor.snapshot_gpus().ok()
    }

    /// Whether a discrete GPU is present, and the largest discrete card's memory in
    /// whole GiB. Each is `None` where the adapters were not read. An empty list reads
    /// as neither. VRAM is `None` if any discrete adapter's total is unknown, because the
    /// largest of the known totals could understate the machine.
    fn discrete_gpu_and_vram(adapters: Option<&[crate::GpuInfo]>) -> (Option<bool>, Option<f32>) {
        const GIB: f32 = 1_073_741_824.0;
        let Some(gpus) = adapters.filter(|g| !g.is_empty()) else {
            return (None, None);
        };
        let discrete: Vec<&crate::GpuInfo> = gpus
            .iter()
            .filter(|g| g.static_info.integrated == Some(false))
            .collect();
        if discrete.is_empty() {
            // Every adapter is known to be integrated: a reading. Any unknown flag is not.
            let all_integrated = gpus.iter().all(|g| g.static_info.integrated == Some(true));
            return (all_integrated.then_some(false), None);
        }
        let totals: Option<Vec<u64>> = discrete
            .iter()
            .map(|g| g.dynamic_info.memory.total)
            .collect();
        let vram = totals
            .and_then(|t| t.into_iter().max())
            .map(|bytes| (bytes as f32 / GIB).round());
        (Some(true), vram)
    }

    fn extract_storage_features(&mut self) {
        // Storage is `Some(false)` only when every disk was enumerated and classified as
        // lacking the property. An unclassifiable device (virtio `vda`, `xvda`, `mmcblk`,
        // or a media type the query did not report) may be an SSD, so it leaves the answer
        // `None` rather than `false`.
        #[cfg(target_os = "linux")]
        {
            let mut classified = 0usize;
            let mut unclassified = false;
            let mut any_nvme = std::path::Path::new("/sys/class/nvme").exists();
            let mut any_ssd = any_nvme;
            let mut total: Option<f32> = None;

            if let Ok(entries) = std::fs::read_dir("/sys/block") {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    let is_nvme = name.starts_with("nvme");
                    if !(name.starts_with("sd") || is_nvme) {
                        // Pseudo devices are not storage. Anything else may be a disk.
                        let pseudo = ["loop", "ram", "zram", "sr", "dm-", "md"]
                            .iter()
                            .any(|p| name.starts_with(p));
                        if !pseudo {
                            unclassified = true;
                        }
                        continue;
                    }

                    if is_nvme {
                        any_nvme = true;
                        any_ssd = true;
                        classified += 1;
                    } else {
                        match std::fs::read_to_string(entry.path().join("queue/rotational"))
                            .ok()
                            .as_deref()
                            .map(str::trim)
                        {
                            Some("0") => {
                                any_ssd = true;
                                classified += 1;
                            }
                            Some("1") => classified += 1,
                            _ => unclassified = true,
                        }
                    }

                    if let Some(sectors) = std::fs::read_to_string(entry.path().join("size"))
                        .ok()
                        .and_then(|s| s.trim().parse::<u64>().ok())
                    {
                        total = Some(total.unwrap_or(0.0) + (sectors * 512) as f32 / 1e9);
                    }
                }
            }

            self.features.has_nvme = if any_nvme {
                Some(true)
            } else {
                (classified > 0 && !unclassified).then_some(false)
            };
            self.features.has_ssd = if any_ssd {
                Some(true)
            } else {
                (classified > 0 && !unclassified).then_some(false)
            };
            self.features.total_storage_gb = total;
            self.features.boot_drive_type = Self::linux_root_drive_type();
        }

        #[cfg(target_os = "windows")]
        {
            // Bus types as `ConvertTo-Json` names them, and as the CIM class numbers them.
            const BUS_TYPES: &[(&str, u64)] = &[
                ("scsi", 1),
                ("atapi", 2),
                ("ata", 3),
                ("1394", 4),
                ("ssa", 5),
                ("fibre channel", 6),
                ("usb", 7),
                ("raid", 8),
                ("iscsi", 9),
                ("sas", 10),
                ("sata", 11),
                ("sd", 12),
                ("mmc", 13),
                ("virtual", 14),
                ("file backed virtual", 15),
                ("storage spaces", 16),
                ("nvme", 17),
                ("scm", 18),
                ("ufs", 19),
            ];

            let disks = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "Get-PhysicalDisk | Select-Object MediaType,Size,BusType | ConvertTo-Json",
                ])
                .output()
                .ok()
                .and_then(|o| json_items(&String::from_utf8(o.stdout).unwrap_or_default()))
                .unwrap_or_default();

            // Each disk's media and bus type, `Some` only where the value was one this
            // reader knows. `Unspecified` (a USB gadget, for one) is `None`.
            let kinds: Vec<(Option<u64>, Option<u64>)> = disks
                .iter()
                .map(|disk| {
                    (
                        wmi_enum(disk.get("MediaType"), &[("hdd", 3), ("ssd", 4)]),
                        wmi_enum(disk.get("BusType"), BUS_TYPES),
                    )
                })
                .collect();

            let any_nvme = kinds.iter().any(|(_, bus)| *bus == Some(17));
            let any_ssd = kinds
                .iter()
                .any(|(media, bus)| *media == Some(4) || *bus == Some(17));
            self.features.has_nvme = if any_nvme {
                Some(true)
            } else {
                (!kinds.is_empty() && kinds.iter().all(|(_, bus)| bus.is_some())).then_some(false)
            };
            self.features.has_ssd = if any_ssd {
                Some(true)
            } else {
                (!kinds.is_empty() && kinds.iter().all(|(media, _)| *media == Some(3)))
                    .then_some(false)
            };

            // The size is known only if every disk's size was read.
            let sizes: Option<Vec<u64>> = disks
                .iter()
                .map(|d| d.get("Size").and_then(|v| v.as_u64()))
                .collect();
            self.features.total_storage_gb = (!disks.is_empty())
                .then(|| sizes.map(|s| s.iter().sum::<u64>() as f32 / 1e9))
                .flatten();

            self.features.boot_drive_type = Self::windows_system_drive_type(BUS_TYPES);
        }
    }

    /// The kind of the disk holding the root volume, read from `/proc/mounts`. `None`
    /// when the root device is not a disk this reader classifies (device-mapper, overlay,
    /// virtio), or its rotational flag was not read.
    #[cfg(target_os = "linux")]
    fn linux_root_drive_type() -> Option<String> {
        let mounts = std::fs::read_to_string("/proc/mounts").ok()?;
        let device = mounts.lines().find_map(|line| {
            let mut fields = line.split_whitespace();
            let (dev, mountpoint) = (fields.next()?, fields.next()?);
            (mountpoint == "/").then_some(dev)
        })?;
        let name = device.strip_prefix("/dev/")?;

        let base = base_disk_name(name)?;

        if base.starts_with("nvme") {
            return Some("NVMe".into());
        }
        match std::fs::read_to_string(format!("/sys/block/{base}/queue/rotational"))
            .ok()?
            .trim()
        {
            "0" => Some("SATA SSD".into()),
            "1" => Some("HDD".into()),
            _ => None,
        }
    }

    /// The kind of the disk holding the system volume. The disk number comes from the
    /// partition on the system drive letter, so this is the disk Windows boots from.
    /// `None` when that partition or disk cannot be read.
    #[cfg(target_os = "windows")]
    fn windows_system_drive_type(bus_types: &[(&str, u64)]) -> Option<String> {
        let script = concat!(
            "$p = Get-Partition -DriveLetter $env:SystemDrive.Substring(0,1) -ErrorAction Stop; ",
            "Get-PhysicalDisk | Where-Object { [string]$_.DeviceId -eq [string]$p.DiskNumber } ",
            "| Select-Object MediaType,BusType | ConvertTo-Json"
        );
        let output = std::process::Command::new("powershell")
            .args(["-NoProfile", "-Command", script])
            .output()
            .ok()?;
        let text = String::from_utf8(output.stdout).ok()?;
        let disk = json_items(&text)?.into_iter().next()?;
        let media = wmi_enum(disk.get("MediaType"), &[("hdd", 3), ("ssd", 4)]);
        let bus = wmi_enum(disk.get("BusType"), bus_types);
        if bus == Some(17) {
            Some("NVMe".into())
        } else if media == Some(4) {
            Some("SSD".into())
        } else if media == Some(3) {
            Some("HDD".into())
        } else {
            None
        }
    }

    fn extract_platform_features(&mut self) {
        #[cfg(target_os = "linux")]
        {
            // Battery check
            self.features.has_battery = std::path::Path::new("/sys/class/power_supply/BAT0")
                .exists()
                || std::path::Path::new("/sys/class/power_supply/BAT1").exists();

            // Chassis type from DMI
            if let Ok(chassis) = std::fs::read_to_string("/sys/class/dmi/id/chassis_type") {
                self.features.chassis_type = dmi_chassis_label(chassis.trim()).map(Into::into);
            }

            // VM detection
            // Absent when the DMI product name is unreadable: `None`, not `false`.
            if let Ok(product) = std::fs::read_to_string("/sys/class/dmi/id/product_name") {
                let lower = product.to_lowercase();
                self.features.is_virtual = Some(
                    lower.contains("virtual")
                        || lower.contains("vmware")
                        || lower.contains("kvm")
                        || lower.contains("qemu")
                        || lower.contains("hyperv")
                        || lower.contains("xen"),
                );
            }

            // NUMA nodes
            if let Ok(entries) = std::fs::read_dir("/sys/devices/system/node") {
                self.features.numa_nodes = Some(
                    entries
                        .flatten()
                        .filter(|e| e.file_name().to_string_lossy().starts_with("node"))
                        .count() as u32,
                );
            }
        }

        #[cfg(target_os = "windows")]
        {
            // Battery
            if let Ok(output) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "(Get-CimInstance Win32_Battery).Status",
                ])
                .output()
            {
                let text = String::from_utf8(output.stdout)
                    .unwrap_or_default()
                    .trim()
                    .to_string();
                self.features.has_battery = !text.is_empty();
            }

            // VM detection. A failed query, or an empty model, is unread: `None`.
            // The exit status is checked, since a failed PowerShell run still
            // produces an `Ok` output with nothing usable in it.
            if let Ok(output) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "(Get-CimInstance Win32_ComputerSystem).Model",
                ])
                .output()
            {
                let model = String::from_utf8(output.stdout)
                    .unwrap_or_default()
                    .trim()
                    .to_lowercase();
                self.features.is_virtual =
                    (output.status.success() && !model.is_empty()).then(|| {
                        model.contains("virtual")
                            || model.contains("vmware")
                            || model.contains("hyper-v")
                    });
            }

            // Chassis type, read rather than guessed.
            //
            // This used to be inferred: virtual, else battery present means
            // "Laptop", else "Desktop". A UPS presents as a `Win32_Battery`, so
            // the desktop workstation this was found on classified as a
            // GamingLaptop, and the misclassification cascaded --- thermal
            // headroom "Insufficient", a cooling score of 15, and the advice
            // "High GPU TDP in a laptop --- may experience thermal throttling".
            //
            // `Win32_SystemEnclosure.ChassisTypes` is the same SMBIOS enumeration
            // the Linux arm already reads out of `/sys/class/dmi/id/chassis_type`,
            // it is readable without elevation, and this machine reports 3 for
            // Desktop. One platform reading it and the other guessing at it is
            // how the two arms disagreed about the same hardware.
            if let Ok(output) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "(Get-CimInstance Win32_SystemEnclosure).ChassisTypes[0]",
                ])
                .output()
            {
                let code = String::from_utf8(output.stdout)
                    .unwrap_or_default()
                    .trim()
                    .to_string();
                let read = match code.as_str() {
                    "3" | "4" | "5" | "6" | "7" | "15" => Some("Desktop"),
                    "8" | "9" | "10" | "14" | "31" | "32" => Some("Laptop"),
                    "11" | "12" => Some("Handheld"),
                    "13" => Some("All-in-One"),
                    "17" | "23" | "28" => Some("Server"),
                    "35" | "36" => Some("Mini PC"),
                    _ => None,
                };

                // A code this does not map is unread. The battery used to decide
                // "Laptop" or "Desktop" here, a guess that scored as a reading.
                self.features.chassis_type = if self.features.is_virtual == Some(true) {
                    Some("Virtual".into())
                } else {
                    read.map(Into::into)
                };
            }

            // NUMA node count is not read on Windows. This used to store a constant 1,
            // which scored every Windows machine as single-node.
        }
    }

    fn extract_network_features(&mut self) {
        #[cfg(target_os = "linux")]
        {
            if let Ok(entries) = std::fs::read_dir("/sys/class/net") {
                let mut physical = 0u32;
                let mut fastest: Option<f32> = None;
                for entry in entries.flatten() {
                    // A physical NIC links to its bus device. Loopback, veth, bridges
                    // (docker0, br-*, virbr*), tun/tap and other virtual interfaces have
                    // no such link, so they are not counted.
                    let path = entry.path();
                    if !path.join("device").exists() {
                        continue;
                    }
                    physical += 1;

                    // A down interface has no readable speed, and is skipped rather than
                    // counted as zero.
                    if let Some(mbps) = std::fs::read_to_string(path.join("speed"))
                        .ok()
                        .and_then(|s| s.trim().parse::<u32>().ok())
                    {
                        let gbps = mbps as f32 / 1000.0;
                        fastest = Some(fastest.map_or(gbps, |f| f.max(gbps)));
                    }
                }
                self.features.nic_count = Some(physical);
                self.features.max_nic_speed_gbps = fastest;
            }
        }

        #[cfg(target_os = "windows")]
        {
            // `-Physical` excludes the vEthernet, Hyper-V and WSL adapters.
            if let Some(adapters) = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    "Get-NetAdapter -Physical | Select-Object LinkSpeed | ConvertTo-Json",
                ])
                .output()
                .ok()
                .and_then(|o| json_items(&String::from_utf8(o.stdout).unwrap_or_default()))
            {
                self.features.nic_count = Some(adapters.len() as u32);

                let mut fastest: Option<f32> = None;
                for adapter in &adapters {
                    if let Some(speed) = adapter.get("LinkSpeed").and_then(|v| v.as_str()) {
                        // Parse "1 Gbps", "10 Gbps", "100 Mbps"
                        let parts: Vec<&str> = speed.split_whitespace().collect();
                        if parts.len() >= 2 {
                            if let Ok(val) = parts[0].parse::<f32>() {
                                // Only units we can actually convert. The fallback
                                // used to divide by 1000 for *any* unrecognized unit,
                                // so a "10 Tbps" or "900 Kbps" link was silently
                                // recorded as though it read megabits.
                                let gbps = match parts[1].chars().next() {
                                    Some('G') => Some(val),
                                    Some('M') => Some(val / 1000.0),
                                    Some('K') => Some(val / 1_000_000.0),
                                    Some('T') => Some(val * 1000.0),
                                    _ => None,
                                };
                                if let Some(gbps) = gbps {
                                    fastest = Some(fastest.map_or(gbps, |f| f.max(gbps)));
                                }
                            }
                        }
                    }
                }
                self.features.max_nic_speed_gbps = fastest;
            }
        }
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: System Classification
    // ────────────────────────────────────────────────────────────────

    fn classify_system(&self) -> (SystemClass, Option<f32>) {
        // Nothing read: every rule below would score the default values, and a default
        // feature set comes out as a Desktop at the desktop rule's 0.5 -- a
        // classification of a machine nobody looked at.
        if !anything_read(&self.features) {
            return (SystemClass::Unknown, None);
        }
        let f = &self.features;
        let mut scores: Vec<(SystemClass, f32)> = Vec::new();

        // Virtual machine. Only a reading of `true` scores; `None` is unknown and
        // says nothing about the chassis.
        if f.is_virtual == Some(true) {
            scores.push((
                SystemClass::VirtualMachine,
                CLASSIFICATION_CONFIDENCE_VIRTUAL_MACHINE,
            ));
        }

        // Server indicators
        let server_score = {
            let mut s = 0.0f32;
            if f.is_server_cpu {
                s += CLASSIFICATION_WEIGHT_SERVER_CPU;
            }
            if f.has_ecc == Some(true) {
                s += CLASSIFICATION_WEIGHT_SERVER_ECC;
            }
            if f.cpu_cores_physical.is_some_and(|v| v >= 16) {
                s += CLASSIFICATION_WEIGHT_SERVER_PHYSICAL_CORES;
            }
            if f.ram_at_least(64.0) {
                s += CLASSIFICATION_WEIGHT_SERVER_RAM;
            }
            if f.numa_nodes.is_some_and(|n| n >= 2) {
                s += CLASSIFICATION_WEIGHT_SERVER_NUMA;
            }
            if f.chassis().contains("Server") {
                s += CLASSIFICATION_WEIGHT_SERVER_CHASSIS;
            }
            if !f.has_battery {
                s += CLASSIFICATION_WEIGHT_SERVER_NO_BATTERY;
            }
            if f.nic_count.is_some_and(|n| n >= 2) {
                s += CLASSIFICATION_WEIGHT_SERVER_NICS;
            }
            s.min(CLASSIFICATION_CONFIDENCE_SERVER_CAP)
        };
        if server_score > 0.3 {
            scores.push((SystemClass::Server, server_score));
        }

        // Laptop indicators.
        //
        // A battery used to score 0.4 here while a *read* chassis type scored
        // 0.3, so the guess outranked the reading: any desktop with a UPS --- which
        // presents as a `Win32_Battery` --- cleared the 0.3 threshold on battery
        // alone and classified as a laptop. The machine this was found on is an
        // enclosure-type-3 Desktop and was reported as a GamingLaptop.
        //
        // The chassis is now what decides, and the battery only speaks where the
        // enclosure did not. Both are still combined, because a read chassis can
        // be wrong on a whitebox whose vendor left the field at its default.
        let chassis_is_mobile = f.chassis().contains("Laptop") || f.chassis().contains("Handheld");
        let chassis_is_stationary = f.chassis().contains("Desktop")
            || f.chassis().contains("Server")
            || f.chassis().contains("Mini PC")
            || f.chassis().contains("All-in-One");

        let laptop_score = {
            let mut s = 0.0f32;
            if chassis_is_mobile {
                s += CLASSIFICATION_WEIGHT_LAPTOP_MOBILE_CHASSIS;
            }
            // Only where the enclosure did not answer. A UPS on a desktop is a
            // battery, and it is not evidence of a laptop.
            if f.has_battery && !chassis_is_stationary {
                s += CLASSIFICATION_WEIGHT_LAPTOP_BATTERY;
            }
            if f.cpu_cores_physical.is_some_and(|v| v <= 8) {
                s += CLASSIFICATION_WEIGHT_LAPTOP_LOW_CORES;
            }
            if f.ram_total_gb.is_some_and(|v| v <= 32.0) {
                s += CLASSIFICATION_WEIGHT_LAPTOP_LOW_RAM;
            }
            s.min(CLASSIFICATION_CONFIDENCE_LAPTOP_CAP)
        };
        if laptop_score > 0.3 {
            let gpu_lower = f.gpu_model.to_lowercase();
            if f.is_discrete_gpu() && (gpu_lower.contains("rtx") || gpu_lower.contains("rx ")) {
                scores.push((
                    SystemClass::GamingLaptop,
                    laptop_score * CLASSIFICATION_SCALE_GAMING_LAPTOP,
                ));
            } else if f.ram_total_gb.is_some_and(|v| v <= 16.0)
                && f.cpu_cores_physical.is_some_and(|v| v <= 4)
            {
                scores.push((
                    SystemClass::Ultrabook,
                    laptop_score * CLASSIFICATION_SCALE_ULTRABOOK,
                ));
            } else {
                scores.push((SystemClass::Laptop, laptop_score));
            }
        }

        // Desktop indicators.
        //
        // This was gated on `!f.has_battery`, so a desktop with a UPS was never
        // scored as a desktop at all --- not merely outvoted, but absent from the
        // ballot. The gate is now the chassis.
        // Only a reading of `false` lets this score: an unread `is_virtual` does not
        // establish that the machine is physical.
        if f.is_virtual == Some(false) && !chassis_is_mobile && !f.chassis().contains("Server") {
            let gpu_lower = f.gpu_model.to_lowercase();
            let is_gaming_gpu = gpu_lower.contains("rtx")
                || gpu_lower.contains("gtx")
                || gpu_lower.contains("rx 6")
                || gpu_lower.contains("rx 7");

            if f.is_server_cpu || f.ram_at_least(64.0) {
                scores.push((
                    SystemClass::Workstation,
                    CLASSIFICATION_CONFIDENCE_WORKSTATION,
                ));
            } else if is_gaming_gpu {
                scores.push((
                    SystemClass::GamingDesktop,
                    CLASSIFICATION_CONFIDENCE_GAMING_DESKTOP,
                ));
            } else {
                scores.push((SystemClass::Desktop, CLASSIFICATION_CONFIDENCE_DESKTOP));
            }
        }

        // Embedded
        if f.cpu_cores_physical.is_some_and(|v| v <= 4) && f.ram_total_gb.is_some_and(|v| v <= 4.0)
        {
            let model = f.cpu_model.as_deref().unwrap_or("").to_lowercase();
            if model.contains("arm") || model.contains("cortex") || model.contains("tegra") {
                scores.push((SystemClass::Embedded, CLASSIFICATION_CONFIDENCE_EMBEDDED));
            }
        }

        // Mini PC
        if f.chassis().contains("Mini") {
            scores.push((SystemClass::MiniPc, CLASSIFICATION_CONFIDENCE_MINI_PC));
        }

        // Pick highest-scoring classification. No rule matched what was read, which is
        // Unknown with no confidence.
        scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        match scores.first().cloned() {
            Some((class, score)) => (class, Some(score)),
            None => (SystemClass::Unknown, None),
        }
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Performance Tier
    // ────────────────────────────────────────────────────────────────

    fn compute_performance_tier(&self) -> (PerformanceTier, u8) {
        let f = &self.features;
        let mut score = 0u32; // 0-1000 internal scale

        // CPU scoring (up to 350 points)
        // An unread core count or clock earns no points. It used to score as 0.
        score += f.cpu_cores_physical.map_or(0, |cores| match cores {
            0..=1 => 10,
            2 => 30,
            4 => 80,
            6 => 120,
            8 => 160,
            12 => 200,
            16 => 250,
            24 => 280,
            32 => 300,
            _ => 350, // 64+ cores
        });

        // Frequency bonus
        score += f.cpu_max_freq_mhz.map_or(0, |mhz| match mhz {
            0..=1500 => 0,
            1501..=2500 => 10,
            2501..=3500 => 25,
            3501..=4500 => 40,
            _ => 50, // 4.5+ GHz
        });

        // RAM scoring (up to 200 points)
        // Each term is added only where its input was read. An unread size scores nothing
        // rather than the smallest bucket.
        score += f.ram_total_gb.map_or(0, |gb| match gb as u32 {
            0..=2 => 5,
            3..=4 => 20,
            5..=8 => 50,
            9..=16 => 80,
            17..=32 => 120,
            33..=64 => 160,
            65..=128 => 180,
            _ => 200, // 128+ GB
        });

        // GPU scoring (up to 300 points)
        if f.is_discrete_gpu() {
            score += 50; // Base discrete GPU bonus
            score += f.gpu_vram_gb.map_or(0, |gb| match gb as u32 {
                0..=2 => 10,
                3..=4 => 40,
                5..=8 => 80,
                9..=12 => 120,
                13..=16 => 160,
                17..=24 => 200,
                _ => 250, // 24+ GB VRAM
            });
            if f.has_tensor_cores == Some(true) {
                score += 30;
            }
            if f.has_rt_cores == Some(true) {
                score += 20;
            }
        }

        // Storage scoring (up to 100 points)
        if f.has_nvme == Some(true) {
            score += 60;
        } else if f.has_ssd == Some(true) {
            score += 30;
        }
        score += f.total_storage_gb.map_or(0, |gb| match gb as u32 {
            0..=128 => 5,
            129..=512 => 15,
            513..=2048 => 25,
            _ => 40,
        });

        // Network scoring (up to 50 points)
        score += f.max_nic_speed_gbps.map_or(0, |gbps| match gbps as u32 {
            0 => 0,
            1 => 15,
            10 => 30,
            25 => 40,
            _ => 50, // 40+ Gbps
        });

        // Normalize to 0-100
        let normalized = ((score as f32 / 1000.0) * 100.0).min(100.0) as u8;

        let tier = match normalized {
            0..=10 => PerformanceTier::UltraLow,
            11..=25 => PerformanceTier::Low,
            26..=35 => PerformanceTier::MidLow,
            36..=50 => PerformanceTier::Mid,
            51..=65 => PerformanceTier::MidHigh,
            66..=80 => PerformanceTier::High,
            81..=90 => PerformanceTier::Ultra,
            _ => PerformanceTier::Datacenter,
        };

        (tier, normalized)
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Bottleneck Detection
    // ────────────────────────────────────────────────────────────────

    fn detect_bottlenecks(&self) -> Vec<Bottleneck> {
        let f = &self.features;
        let mut bottlenecks = Vec::new();

        // CPU vs GPU imbalance
        // Each rule below names the inputs it reads. A rule whose input is unread (`None`)
        // emits nothing, so an unread value is never treated as zero or as false.
        if f.is_discrete_gpu()
            && f.cpu_cores_physical.is_some_and(|v| v <= 4)
            && f.vram_at_least(8.0)
        {
            bottlenecks.push(Bottleneck {
                bottleneck_type: BottleneckType::CpuBound,
                component: "CPU".into(),
                severity: 70,
                reason: format!(
                    "Only {} CPU cores paired with {}GB GPU — CPU will bottleneck GPU-intensive tasks",
                    // Guarded by `is_some_and` above, so the values are present.
                    f.cpu_cores_physical.unwrap_or_default(),
                    f.gpu_vram_gb.unwrap_or_default() as u32
                ),
                confidence: BOTTLENECK_CONFIDENCE_CPU_GPU_IMBALANCE,
            });
        }

        // RAM too low for GPU workloads
        if f.is_discrete_gpu() && f.vram_at_least(8.0) && f.ram_below(16.0) {
            bottlenecks.push(Bottleneck {
                bottleneck_type: BottleneckType::MemoryBound,
                component: "System RAM".into(),
                severity: 60,
                reason: format!(
                    "{:.0}GB RAM is insufficient for GPU workloads with {}GB VRAM",
                    f.ram_total_gb.unwrap_or_default(),
                    f.gpu_vram_gb.unwrap_or_default() as u32
                ),
                confidence: BOTTLENECK_CONFIDENCE_RAM_GPU_WORKLOADS,
            });
        }

        // RAM too low for core count
        if f.cpu_cores_physical.is_some_and(|v| v >= 8) && f.ram_below(16.0) {
            bottlenecks.push(Bottleneck {
                bottleneck_type: BottleneckType::MemoryBound,
                component: "System RAM".into(),
                severity: 55,
                reason: format!(
                    "{:.0}GB RAM for {} cores — should have at least 2GB/core",
                    f.ram_total_gb.unwrap_or_default(),
                    f.cpu_cores_physical.unwrap_or_default()
                ),
                confidence: BOTTLENECK_CONFIDENCE_RAM_PER_CORE,
            });
        }

        // No SSD. Fires only when every disk was read and none is an SSD. NVMe implies
        // SSD in the readers, so `has_ssd == Some(false)` covers both.
        if f.has_ssd == Some(false) {
            bottlenecks.push(Bottleneck {
                bottleneck_type: BottleneckType::StorageBound,
                component: "Storage".into(),
                severity: 80,
                reason: "No SSD detected — HDD will severely bottleneck modern workloads".into(),
                confidence: BOTTLENECK_CONFIDENCE_NO_SSD,
            });
        }

        // High core count with SATA (not NVMe)
        if f.cpu_cores_physical.is_some_and(|v| v >= 16)
            && f.has_ssd == Some(true)
            && f.has_nvme == Some(false)
        {
            bottlenecks.push(Bottleneck {
                bottleneck_type: BottleneckType::StorageBound,
                component: "Storage bus".into(),
                severity: 40,
                reason: "High-core-count CPU with SATA SSD — NVMe would reduce I/O bottleneck"
                    .into(),
                confidence: BOTTLENECK_CONFIDENCE_SATA_HIGH_CORE,
            });
        }

        // Slow network for server
        if f.is_server_cpu && f.max_nic_speed_gbps.is_some_and(|v| v < 10.0) {
            bottlenecks.push(Bottleneck {
                bottleneck_type: BottleneckType::NetworkBound,
                component: "Network".into(),
                severity: 45,
                reason: format!(
                    "Server CPU with only {:.0} Gbps NIC — consider 10/25 GbE",
                    f.max_nic_speed_gbps.unwrap_or_default()
                ),
                confidence: BOTTLENECK_CONFIDENCE_SLOW_SERVER_NIC,
            });
        }

        bottlenecks
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Workload Suitability (Bayesian-inspired scoring)
    // ────────────────────────────────────────────────────────────────

    fn score_workloads(&self) -> Vec<WorkloadSuitability> {
        let f = &self.features;
        let mut results = Vec::new();

        // ML Training
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.has_tensor_cores == Some(true) {
                score += 30;
                strengths.push("Tensor cores available".into());
            }
            // Each shortfall is named only when its input was read below the threshold.
            if f.vram_at_least(24.0) {
                score += 25;
                strengths.push(format!(
                    "{:.0}GB VRAM for large models",
                    f.gpu_vram_gb.unwrap_or_default()
                ));
            } else if f.vram_at_least(12.0) {
                score += 15;
            } else if f.vram_at_least(8.0) {
                score += 8;
                limiting.push("Limited VRAM for large models".into());
            } else if f.vram_below(8.0) {
                limiting.push("Insufficient VRAM for ML training".into());
            }
            if f.ram_at_least(64.0) {
                score += 15;
            } else if f.ram_at_least(32.0) {
                score += 10;
            } else if f.ram_below(32.0) {
                limiting.push("RAM may limit dataset size".into());
            }
            if f.has_nvme == Some(true) {
                score += 10;
            }
            if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
                score += 10;
            }
            if f.gpu_count > 1 {
                score += 10;
                strengths.push("Multi-GPU available".into());
            }

            results.push(WorkloadSuitability {
                workload: Workload::MlTraining,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_ML_TRAINING,
                limiting_factors: limiting,
                strengths,
            });
        }

        // ML Inference
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.is_discrete_gpu() {
                score += 30;
                strengths.push("Discrete GPU".into());
            }
            if f.vram_at_least(8.0) {
                score += 20;
            }
            if f.has_tensor_cores == Some(true) {
                score += 15;
            }
            if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
                score += 15;
            }
            if f.ram_at_least(16.0) {
                score += 10;
            }
            if f.has_nvme == Some(true) {
                score += 10;
            }
            if f.has_discrete_gpu == Some(false) {
                limiting.push("No discrete GPU — CPU inference only".into());
            }

            results.push(WorkloadSuitability {
                workload: Workload::MlInference,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_ML_INFERENCE,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Gaming
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.is_discrete_gpu() && f.vram_at_least(8.0) {
                score += 35;
                strengths.push(format!(
                    "Discrete GPU with {:.0}GB VRAM",
                    f.gpu_vram_gb.unwrap_or_default()
                ));
            } else if f.is_discrete_gpu() {
                score += 15;
            } else if f.has_discrete_gpu == Some(false) {
                limiting.push("No discrete GPU".into());
            }
            if f.has_rt_cores == Some(true) {
                score += 10;
                strengths.push("Ray tracing support".into());
            }
            if f.cpu_max_freq_mhz.is_some_and(|v| v >= 4000) {
                score += 15;
                strengths.push("High CPU clock speed".into());
            } else if f.cpu_max_freq_mhz.is_some_and(|v| v >= 3000) {
                score += 10;
            }
            if f.ram_at_least(16.0) {
                score += 10;
            } else if f.ram_below(16.0) {
                limiting.push("< 16GB RAM".into());
            }
            if f.has_nvme == Some(true) {
                score += 10;
            }
            if f.cpu_cores_physical.is_some_and(|v| v >= 6) {
                score += 10;
            }
            if f.has_ssd == Some(true) {
                score += 10;
            }

            results.push(WorkloadSuitability {
                workload: Workload::Gaming,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_GAMING,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Video Editing
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.is_discrete_gpu() {
                score += 20;
            }
            if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
                score += 20;
                strengths.push("Multi-core for rendering".into());
            } else if f.cpu_cores_physical.is_some_and(|v| v >= 6) {
                score += 15;
            }
            if f.ram_at_least(32.0) {
                score += 20;
                strengths.push("Plenty of RAM for timelines".into());
            } else if f.ram_at_least(16.0) {
                score += 10;
            } else if f.ram_below(16.0) {
                limiting.push("< 16GB RAM limits timeline length".into());
            }
            if f.has_nvme == Some(true) {
                score += 15;
                strengths.push("NVMe for fast media reads".into());
            }
            if f.total_storage_gb.is_some_and(|v| v >= 2000.0) {
                score += 10;
            } else if f.total_storage_gb.is_some_and(|v| v < 2000.0) {
                limiting.push("Limited storage for large projects".into());
            }
            if f.vram_at_least(8.0) {
                score += 15;
            }

            results.push(WorkloadSuitability {
                workload: Workload::VideoEditing,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_VIDEO_EDITING,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Compilation
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.cpu_cores_physical.is_some_and(|v| v >= 16) {
                score += 35;
                strengths.push("Many cores for parallel builds".into());
            } else if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
                score += 25;
            } else if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
                score += 15;
            } else {
                limiting.push("Few cores — slow parallel builds".into());
            }
            if f.ram_at_least(32.0) {
                score += 25;
            } else if f.ram_at_least(16.0) {
                score += 15;
            }
            if f.has_nvme == Some(true) {
                score += 20;
                strengths.push("Fast build I/O with NVMe".into());
            } else if f.has_ssd == Some(true) {
                score += 10;
            }
            if f.cpu_max_freq_mhz.is_some_and(|v| v >= 4000) {
                score += 10;
            }
            if f.total_storage_gb.is_some_and(|v| v >= 512.0) {
                score += 10;
            }

            results.push(WorkloadSuitability {
                workload: Workload::Compilation,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_COMPILATION,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Web Server
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
                score += 25;
            } else if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
                score += 15;
            }
            if f.ram_at_least(16.0) {
                score += 20;
            }
            if f.max_nic_speed_gbps.is_some_and(|v| v >= 10.0) {
                score += 25;
                strengths.push("10+ GbE networking".into());
            } else if f.max_nic_speed_gbps.is_some_and(|v| v >= 1.0) {
                score += 10;
            } else if f.max_nic_speed_gbps.is_some_and(|v| v < 1.0) {
                limiting.push("Slow network".into());
            }
            if f.has_nvme == Some(true) {
                score += 15;
            }
            if f.nic_count.is_some_and(|n| n >= 2) {
                score += 10;
                strengths.push("Multiple NICs for redundancy".into());
            }
            if f.is_server_cpu {
                score += 5;
            }

            results.push(WorkloadSuitability {
                workload: Workload::WebServer,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_WEB_SERVER,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Database Server
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.ram_at_least(64.0) {
                score += 30;
                strengths.push("Large RAM for caching".into());
            } else if f.ram_at_least(32.0) {
                score += 20;
            } else if f.ram_below(32.0) {
                limiting.push("RAM limits index caching".into());
            }
            if f.has_nvme == Some(true) {
                score += 25;
                strengths.push("NVMe for fast IOPS".into());
            } else if f.has_ssd == Some(true) {
                score += 15;
            } else if f.has_ssd == Some(false) {
                limiting.push("HDD severely limits database IOPS".into());
            }
            if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
                score += 20;
            }
            if f.total_storage_gb.is_some_and(|v| v >= 2000.0) {
                score += 15;
            }
            if f.has_ecc == Some(true) {
                score += 10;
                strengths.push("ECC memory for data integrity".into());
            }

            results.push(WorkloadSuitability {
                workload: Workload::DatabaseServer,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_DATABASE_SERVER,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Virtualization
        {
            let mut score = 0u8;
            let mut strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.cpu_cores_physical.is_some_and(|v| v >= 16) {
                score += 30;
                strengths.push("Many cores for VMs".into());
            } else if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
                score += 15;
            } else {
                limiting.push("Few cores limits VM density".into());
            }
            if f.ram_at_least(128.0) {
                score += 30;
            } else if f.ram_at_least(64.0) {
                score += 20;
                strengths.push("Good RAM for VMs".into());
            } else if f.ram_at_least(32.0) {
                score += 10;
            } else if f.ram_below(32.0) {
                limiting.push("Limited RAM for virtual machines".into());
            }
            if f.has_nvme == Some(true) {
                score += 15;
            }
            if f.numa_nodes.is_some_and(|n| n >= 2) {
                score += 10;
                strengths.push("NUMA for VM pinning".into());
            }
            if f.is_server_cpu {
                score += 10;
            }
            if f.total_storage_gb.is_some_and(|v| v >= 2000.0) {
                score += 5;
            }

            results.push(WorkloadSuitability {
                workload: Workload::Virtualization,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_VIRTUALIZATION,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Office Productivity
        {
            let mut score = 50u8; // Almost anything can handle office work
            let strengths = Vec::new();
            let mut limiting = Vec::new();

            if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
                score += 15;
            }
            if f.ram_at_least(8.0) {
                score += 15;
            } else if f.ram_below(8.0) {
                limiting.push("< 8GB RAM may cause slowdowns".into());
            }
            if f.has_ssd == Some(true) {
                score += 15;
            } else if f.has_ssd == Some(false) {
                limiting.push("HDD makes boot and app launch slow".into());
            }
            if f.cpu_cores_physical.is_some_and(|v| v < 2) || f.ram_below(4.0) {
                score = score.saturating_sub(30);
            }

            results.push(WorkloadSuitability {
                workload: Workload::OfficeProductivity,
                score: score.min(100),
                confidence: WORKLOAD_CONFIDENCE_OFFICE_PRODUCTIVITY,
                limiting_factors: limiting,
                strengths,
            });
        }

        // Sort by score descending
        results.sort_by_key(|p| std::cmp::Reverse(p.score));
        results
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Hardware Age Estimation
    // ────────────────────────────────────────────────────────────────

    fn estimate_hardware_age(&self) -> HardwareAge {
        let f = &self.features;
        let cpu_lower = f.cpu_model.as_deref().unwrap_or("").to_lowercase();
        let gpu_lower = f.gpu_model.to_lowercase();

        let cpu_year = Self::infer_cpu_year(&cpu_lower);
        let gpu_year = Self::infer_gpu_year(&gpu_lower);

        // The current year, from the clock, not from whoever last edited this
        // function. It was the literal `2025.0` in three places, so every age in
        // the report was a year short the moment the year turned and grew a year
        // more wrong for each one after -- silently, because an age is plausible
        // at any value. A hardcoded *release* year is a fact about a product; a
        // hardcoded *current* year is a fact about the editor's calendar.
        let current = Self::current_year();
        let years = match (cpu_year, gpu_year) {
            (Some(cy), Some(gy)) => {
                let avg = (cy + gy) as f32 / 2.0;
                Some((current - avg).max(0.0))
            }
            (Some(cy), None) => Some((current - cy as f32).max(0.0)),
            (None, Some(gy)) => Some((current - gy as f32).max(0.0)),
            // No model table matched, so there is no release year to age the
            // machine from. The figure that used to stand here was a guess from
            // core count and drive type, which says nothing about the machine's
            // age, so it is None rather than a number.
            (None, None) => None,
        };

        let confidence = match (cpu_year, gpu_year) {
            (Some(_), Some(_)) => Some(AGE_CONFIDENCE_CPU_AND_GPU),
            (Some(_), None) | (None, Some(_)) => Some(AGE_CONFIDENCE_CPU_OR_GPU),
            (None, None) => None,
        };

        let reasoning = format!(
            "CPU: {} (est. {}), GPU: {} (est. {})",
            f.cpu_model.as_deref().unwrap_or("unknown"),
            cpu_year.map_or("unknown".to_string(), |y| y.to_string()),
            f.gpu_model,
            gpu_year.map_or("unknown".to_string(), |y| y.to_string()),
        );

        HardwareAge {
            cpu_year,
            gpu_year,
            estimated_age_years: years,
            confidence,
            reasoning,
        }
    }

    fn infer_cpu_year(model: &str) -> Option<u16> {
        // Vendor first, because the Intel rules below match bare model numbers
        // and those numbers are not unique to Intel.
        //
        // "AMD Ryzen 9 9900X" contains "9900", so it matched the Intel 9th-gen
        // Core rule and was dated to 2018 --- a 2024 Zen 5 part reported as six
        // years old, at 0.85 confidence, with the correct `ryzen 9 9` rule
        // sitting unreached thirty lines below. The existing test covered
        // "ryzen 7 7800x3d", which happens not to collide with anything.
        let is_amd = model.contains("amd")
            || model.contains("ryzen")
            || model.contains("epyc")
            || model.contains("threadripper");

        // Intel Core generations
        if !is_amd {
            if model.contains("14th gen")
                || model.contains("core ultra")
                || model.contains("14900")
                || model.contains("14700")
            {
                return Some(2024);
            }
            if model.contains("13th gen")
                || model.contains("13900")
                || model.contains("13700")
                || model.contains("13600")
            {
                return Some(2022);
            }
            if model.contains("12th gen")
                || model.contains("12900")
                || model.contains("12700")
                || model.contains("12600")
            {
                return Some(2021);
            }
            if model.contains("11th gen") || model.contains("11900") || model.contains("11700") {
                return Some(2021);
            }
            if model.contains("10th gen") || model.contains("10900") || model.contains("10700") {
                return Some(2020);
            }
            if model.contains("9th gen") || model.contains("9900") || model.contains("9700") {
                return Some(2018);
            }
            if model.contains("8th gen") || model.contains("8700") {
                return Some(2017);
            }
        }

        // AMD Ryzen (generation from model number pattern: 3xxx=Zen2, 5xxx=Zen3, 7xxx=Zen4, 9xxx=Zen5)
        if model.contains("ryzen 9 9") || model.contains("ryzen 7 9") || model.contains("zen 5") {
            return Some(2024);
        }
        if model.contains("ryzen 9 7")
            || model.contains("ryzen 7 7")
            || model.contains("ryzen 5 7")
            || model.contains("zen 4")
        {
            return Some(2022);
        }
        if model.contains("ryzen 9 5")
            || model.contains("ryzen 7 5")
            || model.contains("ryzen 5 5")
            || model.contains("zen 3")
        {
            return Some(2020);
        }
        if model.contains("ryzen 9 3")
            || model.contains("ryzen 7 3")
            || model.contains("ryzen 5 3")
            || model.contains("zen 2")
        {
            return Some(2019);
        }

        // AMD EPYC
        if model.contains("epyc 9") {
            return Some(2023);
        }
        if model.contains("epyc 7") && model.contains("3") {
            return Some(2022);
        }
        if model.contains("epyc 7") {
            return Some(2019);
        }

        // Intel Xeon (simplified)
        if model.contains("xeon w9") || model.contains("xeon w7") {
            return Some(2023);
        }
        if model.contains("xeon") && model.contains("v5") {
            return Some(2017);
        }
        if model.contains("xeon") && model.contains("v4") {
            return Some(2016);
        }

        // Apple
        if model.contains("m4") {
            return Some(2024);
        }
        if model.contains("m3") {
            return Some(2023);
        }
        if model.contains("m2") {
            return Some(2022);
        }
        if model.contains("m1") {
            return Some(2020);
        }

        None
    }

    /// The current year, as a float, from the system clock.
    ///
    /// Seconds since the epoch divided by the mean Gregorian year (365.2425
    /// days) -- close enough for an age in years, and it needs no calendar
    /// crate. A clock before 1970 yields 1970, which will look wrong in a report
    /// rather than producing a negative age.
    fn current_year() -> f32 {
        const SECONDS_PER_YEAR: f32 = 365.2425 * 24.0 * 60.0 * 60.0;
        let secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs_f32())
            .unwrap_or(0.0);
        1970.0 + secs / SECONDS_PER_YEAR
    }

    fn infer_gpu_year(model: &str) -> Option<u16> {
        // NVIDIA GeForce
        if model.contains("rtx 50") || model.contains("5090") || model.contains("5080") {
            return Some(2025);
        }
        if model.contains("rtx 40") || model.contains("4090") || model.contains("4080") {
            return Some(2022);
        }
        // A refresh ships after the series it belongs to, so the specific model
        // has to be matched before the series rule swallows it. The 3090 Ti in
        // the development machine dated to 2020 by the `rtx 30` rule and shipped
        // in March 2022 -- the age estimate was two years out for the one card
        // this table was checked against.
        //
        // Only refreshes whose date is known are listed. A rule for every card
        // would be a release database, and this is a heuristic that says so:
        // `estimate_hardware_age` reports 0.85 confidence when both years are
        // guessed here, which is high for a substring table and is item 4 of the
        // handoff.
        if model.contains("3090 ti") {
            return Some(2022);
        }
        if model.contains("3080 ti") || model.contains("3070 ti") {
            return Some(2021);
        }
        if model.contains("rtx 30") || model.contains("3090") || model.contains("3080") {
            return Some(2020);
        }
        if model.contains("rtx 20") || model.contains("2080") || model.contains("2070") {
            return Some(2018);
        }
        if model.contains("gtx 1080") || model.contains("gtx 10") {
            return Some(2016);
        }
        if model.contains("gtx 9") {
            return Some(2014);
        }

        // NVIDIA Data Center
        if model.contains("h100") || model.contains("h200") {
            return Some(2023);
        }
        if model.contains("a100") {
            return Some(2020);
        }
        if model.contains("v100") {
            return Some(2017);
        }

        // AMD Radeon
        if model.contains("rx 9") {
            return Some(2025);
        }
        if model.contains("rx 7") {
            return Some(2022);
        }
        if model.contains("rx 6") {
            return Some(2020);
        }
        if model.contains("rx 5") {
            return Some(2019);
        }

        // Intel Arc
        if model.contains("arc b") {
            return Some(2024);
        }
        if model.contains("arc a") {
            return Some(2022);
        }

        // Apple (same as CPU year for SoC)
        if model.contains("m4") {
            return Some(2024);
        }
        if model.contains("m3") {
            return Some(2023);
        }
        if model.contains("m2") {
            return Some(2022);
        }
        if model.contains("m1") {
            return Some(2020);
        }

        None
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Thermal Envelope Modeling
    // ────────────────────────────────────────────────────────────────

    fn analyze_thermal_envelope(&self) -> ThermalEnvelope {
        let f = &self.features;
        let cpu_tdp = f.cpu_tdp_watts;
        let gpu_tdp = f.gpu_tdp_watts;
        // +30W for RAM, storage, board. A total with either term unknown is
        // unknown too: the partial sum would pass for a total.
        let total_tdp = match (cpu_tdp, gpu_tdp) {
            (Some(c), Some(g)) => Some(c + g + 30.0),
            _ => None,
        };

        // `has_battery` used to stand in for "laptop" here. A UPS made this
        // desktop workstation take the laptop cooling curve, which reported
        // headroom "Insufficient" and a cooling score of 15 for a tower with
        // room for a 500W envelope. The chassis is read now, so use it.
        let is_mobile_chassis = f.chassis().contains("Laptop") || f.chassis().contains("Handheld");

        let headroom = if is_mobile_chassis {
            // Laptop — limited cooling
            match total_tdp {
                None => ThermalHeadroom::Unknown,
                Some(t) if t > 150.0 => ThermalHeadroom::Insufficient,
                Some(t) if t > 100.0 => ThermalHeadroom::Marginal,
                Some(t) if t > 60.0 => ThermalHeadroom::Adequate,
                Some(_) => ThermalHeadroom::Ample,
            }
        } else if f.chassis().contains("Mini") {
            // Mini PC — moderate cooling
            match total_tdp {
                Some(t) if t > 120.0 => ThermalHeadroom::Marginal,
                Some(_) => ThermalHeadroom::Adequate,
                None => ThermalHeadroom::Unknown,
            }
        } else {
            // Desktop/server — no cooling reading exists, and the chassis does
            // not say how much there is. Unknown, not a guess that it is ample.
            ThermalHeadroom::Unknown
        };

        let cooling_score = match &headroom {
            ThermalHeadroom::Ample => Some(90),
            ThermalHeadroom::Adequate => Some(70),
            ThermalHeadroom::Marginal => Some(40),
            ThermalHeadroom::Insufficient => Some(15),
            ThermalHeadroom::Unknown => None,
        };

        let mut recommendations = Vec::new();
        if headroom == ThermalHeadroom::Insufficient || headroom == ThermalHeadroom::Marginal {
            recommendations.push(
                "Consider improving cooling (better fans, repasting, or external cooling)".into(),
            );
        }
        if is_mobile_chassis && gpu_tdp.is_some_and(|g| g > 80.0) {
            recommendations.push(
                "High GPU TDP in a laptop — may experience thermal throttling under sustained load"
                    .into(),
            );
        }

        ThermalEnvelope {
            estimated_total_tdp_watts: total_tdp,
            cpu_tdp_watts: cpu_tdp,
            cpu_tdp_measured: f.cpu_tdp_measured,
            gpu_tdp_watts: gpu_tdp,
            gpu_adapters_counted: f.gpu_adapters_counted,
            gpu_tdp_measured: f.gpu_tdp_measured,
            headroom,
            cooling_score,
            recommendations,
        }
    }

    /// The CPU package power limit the platform enforces, in watts.
    ///
    /// RAPL's `constraint_0_power_limit_uw` is the long-term package limit --
    /// the configured TDP, which is what `analyze_thermal_envelope` wants and
    /// what `infer_cpu_tdp` guesses at from a model name. `rapl::RaplMonitor`
    /// already reads and parses it; this only picks the package domains out and
    /// sums them, so a two-socket machine is priced as two sockets.
    ///
    /// **`None` on Windows and macOS**, where `RaplMonitor::new()` fails
    /// outright: the MSRs behind RAPL need a kernel driver on Windows and there
    /// is no sysfs equivalent. The table answers there, and
    /// `cpu_tdp_measured` says so.
    ///
    /// **Unverified on the platform it is for.** No Linux machine was available
    /// to the session that wrote this, so the Windows half — the `Err` path, the
    /// table, the flag reading false — is the only half that has run. The parse
    /// it depends on is covered by `rapl`'s own tests; the wiring is not. This
    /// is the shape item 18 of the handoff warns about, recorded rather than
    /// hidden.
    fn measured_cpu_power_cap_watts() -> Option<f32> {
        use crate::rapl::PowerDomain;
        let monitor = crate::rapl::RaplMonitor::new().ok()?;
        let watts: f64 = monitor
            .readings()
            .iter()
            .filter(|r| r.domain == PowerDomain::Package)
            .filter_map(|r| r.power_limit_uw)
            .map(|uw| uw as f64 / 1_000_000.0)
            .sum();
        (watts > 0.0).then_some(watts as f32)
    }

    fn infer_cpu_tdp(model_lower: &str) -> Option<f32> {
        // Known TDP ranges by CPU class. No match is no figure, not a default.
        if model_lower.contains("i9-14") || model_lower.contains("i9-13") {
            return Some(125.0);
        }
        if model_lower.contains("i7-14") || model_lower.contains("i7-13") {
            return Some(65.0);
        }
        if model_lower.contains("i5-14") || model_lower.contains("i5-13") {
            return Some(65.0);
        }
        if model_lower.contains("i3") {
            return Some(35.0);
        }
        if model_lower.contains("ryzen 9") {
            return Some(120.0);
        }
        if model_lower.contains("ryzen 7") {
            return Some(65.0);
        }
        if model_lower.contains("ryzen 5") {
            return Some(65.0);
        }
        if model_lower.contains("ryzen 3") {
            return Some(35.0);
        }
        if model_lower.contains("epyc") {
            return Some(225.0);
        }
        if model_lower.contains("xeon") {
            return Some(150.0);
        }
        if model_lower.contains("threadripper") {
            return Some(280.0);
        }
        if model_lower.contains("celeron") || model_lower.contains("atom") {
            return Some(15.0);
        }
        if model_lower.contains("m1") || model_lower.contains("m2") {
            return Some(20.0);
        }
        if model_lower.contains("m3") || model_lower.contains("m4") {
            return Some(22.0);
        }
        if model_lower.contains("arm") || model_lower.contains("cortex") {
            return Some(5.0);
        }
        None
    }

    /// The enforced power caps of every adapter that reports one: their sum in
    /// watts, and how many adapters contributed.
    ///
    /// This is what the drivers will actually let the cards draw, which is the
    /// number the thermal model wants; the name table below is a stand-in for
    /// when nothing reports it. NVML reports it for NVIDIA cards; the Windows
    /// AMD and Intel backends report nothing, so they contribute nothing here
    /// and the table answers for a machine where no adapter reports a cap.
    ///
    /// **It sums because a machine can have more than one card, and this one
    /// does.** Taking the first adapter's cap gave a 450 W GPU budget for a
    /// desktop with two RTX 3090 Ti in it — 450 W short — and the thermal
    /// envelope graded the cooling of a 600 W machine that can draw 1050 W. The
    /// count is carried alongside so a consumer can see the figure is a sum and
    /// over how many adapters.
    ///
    /// Milliwatts in the reading, watts here, because every threshold in
    /// `analyze_thermal_envelope` is written in watts.
    fn measured_gpu_power_caps_watts(gpus: &[crate::GpuInfo]) -> Option<(f32, u32)> {
        let caps: Vec<f32> = gpus
            .iter()
            .filter_map(|g| g.dynamic_info.power.limit)
            .map(|mw| mw as f32 / 1000.0)
            .collect();
        (!caps.is_empty()).then(|| (caps.iter().sum(), caps.len() as u32))
    }

    fn infer_gpu_tdp(model_lower: &str) -> Option<f32> {
        // Known board power by model. No match is no figure: the old default
        // of 100 W for any discrete card was a guess priced as a reading.
        if model_lower.contains("4090") {
            return Some(450.0);
        }
        if model_lower.contains("4080") {
            return Some(320.0);
        }
        if model_lower.contains("4070 ti") {
            return Some(285.0);
        }
        if model_lower.contains("4070") {
            return Some(200.0);
        }
        if model_lower.contains("4060") {
            return Some(115.0);
        }
        if model_lower.contains("3090") {
            return Some(350.0);
        }
        if model_lower.contains("3080") {
            return Some(320.0);
        }
        if model_lower.contains("3070") {
            return Some(220.0);
        }
        if model_lower.contains("3060") {
            return Some(170.0);
        }
        if model_lower.contains("h100") {
            return Some(700.0);
        }
        if model_lower.contains("a100") {
            return Some(300.0);
        }
        if model_lower.contains("rx 7900") {
            return Some(355.0);
        }
        if model_lower.contains("rx 7800") {
            return Some(263.0);
        }
        if model_lower.contains("rx 7700") {
            return Some(245.0);
        }
        if model_lower.contains("rx 7600") {
            return Some(165.0);
        }
        if model_lower.contains("arc a7") {
            return Some(225.0);
        }
        if model_lower.contains("arc a5") {
            return Some(175.0);
        }
        None
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Upgrade Recommendations
    // ────────────────────────────────────────────────────────────────

    fn suggest_upgrades(&self, bottlenecks: &[Bottleneck]) -> Vec<UpgradeRecommendation> {
        let f = &self.features;
        let mut recs = Vec::new();

        // RAM upgrades
        if f.ram_below(8.0) {
            recs.push(UpgradeRecommendation {
                component: "RAM".into(),
                current: format!("{:.0}GB", f.ram_total_gb.unwrap_or_default()),
                recommended: "16GB+".into(),
                description: "Upgrade to at least 16GB RAM".into(),
                expected_impact: "40-60% reduction in memory-related slowdowns".into(),
                priority: 9,
                cost_tier: 2,
            });
        } else if f.ram_below(16.0) && f.is_discrete_gpu() {
            recs.push(UpgradeRecommendation {
                component: "RAM".into(),
                current: format!("{:.0}GB", f.ram_total_gb.unwrap_or_default()),
                recommended: "32GB".into(),
                description: "Upgrade RAM for GPU workloads".into(),
                expected_impact: "20-30% better multitasking and GPU workflow performance".into(),
                priority: 7,
                cost_tier: 2,
            });
        }

        // Storage upgrades
        if f.has_ssd == Some(false) {
            recs.push(UpgradeRecommendation {
                component: "Boot Drive".into(),
                current: "HDD".into(),
                recommended: "NVMe SSD".into(),
                description: "Replace HDD with NVMe SSD for dramatic speed improvement".into(),
                expected_impact: "5-10x faster boot, app launch, and file operations".into(),
                priority: 10,
                cost_tier: 2,
            });
        } else if f.has_ssd == Some(true)
            && f.has_nvme == Some(false)
            && f.cpu_cores_physical.is_some_and(|v| v >= 8)
        {
            recs.push(UpgradeRecommendation {
                component: "Boot Drive".into(),
                current: "SATA SSD".into(),
                recommended: "NVMe Gen4 SSD".into(),
                description: "Upgrade to NVMe for faster I/O".into(),
                expected_impact: "3-5x faster sequential reads, lower I/O latency".into(),
                priority: 5,
                cost_tier: 2,
            });
        }

        // GPU upgrades based on bottlenecks
        for bn in bottlenecks {
            match bn.bottleneck_type {
                BottleneckType::GpuBound if bn.severity > 50 => {
                    recs.push(UpgradeRecommendation {
                        component: "GPU".into(),
                        current: f.gpu_model.clone(),
                        recommended: "Next-tier GPU".into(),
                        description: "GPU is the primary bottleneck".into(),
                        expected_impact: "30-100% improvement in GPU-bound workloads".into(),
                        priority: 8,
                        cost_tier: 4,
                    });
                }
                BottleneckType::CpuBound if bn.severity > 50 => {
                    recs.push(UpgradeRecommendation {
                        component: "CPU".into(),
                        current: f.cpu_model.clone().unwrap_or_else(|| "unknown".into()),
                        recommended: "Higher core-count CPU".into(),
                        description: "CPU bottlenecks the system".into(),
                        expected_impact: "20-50% improvement in CPU-bound workloads".into(),
                        priority: 7,
                        cost_tier: 4,
                    });
                }
                BottleneckType::NetworkBound if bn.severity > 40 => {
                    recs.push(UpgradeRecommendation {
                        component: "Network".into(),
                        current: format!(
                            "{:.0} Gbps NIC",
                            f.max_nic_speed_gbps.unwrap_or_default()
                        ),
                        recommended: "10 GbE NIC".into(),
                        description: "Network is a bottleneck for server workloads".into(),
                        expected_impact: "10x network throughput".into(),
                        priority: 6,
                        cost_tier: 3,
                    });
                }
                _ => {}
            }
        }

        // Sort by priority descending
        recs.sort_by_key(|p| std::cmp::Reverse(p.priority));
        recs
    }

    // ────────────────────────────────────────────────────────────────
    // Inference: Anomaly Detection
    // ────────────────────────────────────────────────────────────────

    fn detect_anomalies(&self) -> Vec<HardwareAnomaly> {
        let f = &self.features;
        let mut anomalies = Vec::new();

        // Huge GPU + tiny RAM
        if f.vram_at_least(16.0) && f.ram_below(16.0) {
            anomalies.push(HardwareAnomaly {
                description: format!(
                    "GPU has {:.0}GB VRAM but system only has {:.0}GB RAM",
                    f.gpu_vram_gb.unwrap_or_default(),
                    f.ram_total_gb.unwrap_or_default()
                ),
                severity: AnomalySeverity::Warning,
                explanation:
                    "GPU VRAM exceeds system RAM — data loading will bottleneck GPU workloads"
                        .into(),
            });
        }

        // Server CPU in laptop. Gated on the chassis rather than on a battery:
        // a server with a UPS is the ordinary case, not an anomaly.
        if f.is_server_cpu && (f.chassis().contains("Laptop") || f.chassis().contains("Handheld")) {
            anomalies.push(HardwareAnomaly {
                description: "Server-class CPU detected in a battery-powered system".into(),
                severity: AnomalySeverity::Info,
                explanation: "This is unusual but may be a mobile workstation".into(),
            });
        }

        // More GPU VRAM than system RAM
        // Both sizes must be read: a missing VRAM or RAM figure is not a comparison.
        if let (Some(vram), Some(ram)) = (f.gpu_vram_gb, f.ram_total_gb) {
            if vram > ram && vram > 0.0 {
                anomalies.push(HardwareAnomaly {
                    description: format!(
                        "GPU VRAM ({:.0}GB) exceeds system RAM ({:.0}GB)",
                        vram, ram
                    ),
                    severity: AnomalySeverity::Warning,
                    explanation:
                        "System RAM should typically be at least 2x GPU VRAM for optimal performance"
                            .into(),
                });
            }
        }

        // Many cores + low frequency
        if f.cpu_cores_physical.is_some_and(|v| v >= 32)
            && f.cpu_max_freq_mhz.is_some_and(|v| v < 2500)
        {
            anomalies.push(HardwareAnomaly {
                description: format!(
                    "{} cores at only {} MHz",
                    f.cpu_cores_physical.unwrap_or_default(),
                    f.cpu_max_freq_mhz.unwrap_or_default()
                ),
                severity: AnomalySeverity::Info,
                explanation: "Many-core + low clock = throughput-optimized (server/HPC), not latency-sensitive".into(),
            });
        }

        // No discrete GPU with tensor expectations
        if f.has_discrete_gpu == Some(false)
            && f.ram_at_least(64.0)
            && f.cpu_cores_physical.is_some_and(|v| v >= 16)
        {
            anomalies.push(HardwareAnomaly {
                description: "Powerful CPU and RAM but no discrete GPU".into(),
                severity: AnomalySeverity::Info,
                explanation: "System may be optimized for CPU-bound workloads or virtualization"
                    .into(),
            });
        }

        // Very large storage with slow network
        if f.total_storage_gb.is_some_and(|v| v >= 10000.0)
            && f.max_nic_speed_gbps.is_some_and(|v| v < 10.0)
        {
            anomalies.push(HardwareAnomaly {
                description: format!(
                    "{:.0}TB storage with only {:.0} Gbps network",
                    f.total_storage_gb.unwrap_or_default() / 1000.0,
                    f.max_nic_speed_gbps.unwrap_or_default()
                ),
                severity: AnomalySeverity::Warning,
                explanation: "Large storage with slow network — data transfers will be slow".into(),
            });
        }

        anomalies
    }

    // ────────────────────────────────────────────────────────────────
    // Hardware Fingerprint
    // ────────────────────────────────────────────────────────────────

    fn compute_fingerprint(&self) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        self.features.cpu_model.hash(&mut hasher);
        self.features.cpu_cores_physical.hash(&mut hasher);
        self.features.cpu_cores_logical.hash(&mut hasher);
        self.features
            .ram_total_gb
            .map(|v| v as u64)
            .hash(&mut hasher);
        self.features.gpu_model.hash(&mut hasher);
        self.features
            .gpu_vram_gb
            .map(|v| v as u64)
            .hash(&mut hasher);
        self.features.has_nvme.hash(&mut hasher);
        self.features
            .total_storage_gb
            .map(|v| v as u64)
            .hash(&mut hasher);

        format!("{:016x}", hasher.finish())
    }
}

impl Default for HardwareInferenceEngine {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            features: HardwareFeatures::default(),
        })
    }
}

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

    #[test]
    fn test_engine_creation() {
        let engine = HardwareInferenceEngine::new();
        assert!(engine.is_ok());
    }

    #[test]
    fn test_engine_default() {
        let engine = HardwareInferenceEngine::default();
        let report = engine.full_analysis();
        let _ = &report.classification;
        let _ = &report.performance_tier;
    }

    /// A machine none of whose inputs was read is not classified: Unknown, with no
    /// confidence and no performance score. Before, the default feature set came out
    /// as a Desktop at the desktop rule's 0.5.
    #[test]
    fn a_machine_nothing_was_read_from_is_unknown_with_no_confidence() {
        let engine = HardwareInferenceEngine {
            features: HardwareFeatures::default(),
        };
        let (class, confidence) = engine.classify_system();
        assert_eq!(class, SystemClass::Unknown);
        assert_eq!(confidence, None);

        let report = engine.full_analysis();
        assert_eq!(report.classification, SystemClass::Unknown);
        assert_eq!(report.classification_confidence, None);
        assert_eq!(report.performance_score, None);
        assert_eq!(report.performance_tier, None);

        // One reading is enough for the rules to run. An unread virtualization flag
        // is not a reading that the machine is physical, so the desktop indicator
        // does not score from it: no rule matched, which is Unknown.
        let one_reading = HardwareInferenceEngine {
            features: HardwareFeatures {
                ram_total_gb: Some(32.0),
                ..HardwareFeatures::default()
            },
        };
        let (class, confidence) = one_reading.classify_system();
        assert_eq!(class, SystemClass::Unknown);
        assert_eq!(confidence, None);

        // Once virtualization has been read as absent, the desktop indicator scores.
        let read_physical = HardwareInferenceEngine {
            features: HardwareFeatures {
                ram_total_gb: Some(32.0),
                is_virtual: Some(false),
                ..HardwareFeatures::default()
            },
        };
        let (class, confidence) = read_physical.classify_system();
        assert_eq!(class, SystemClass::Desktop);
        assert_eq!(confidence, Some(CLASSIFICATION_CONFIDENCE_DESKTOP));
    }

    #[test]
    fn test_full_analysis_report() {
        let engine = HardwareInferenceEngine::new().unwrap();
        let report = engine.full_analysis();
        assert!(!report.hardware_fingerprint.is_empty());
        assert!(!report.workload_scores.is_empty());
    }

    #[test]
    fn test_gaming_desktop_classification() {
        let engine = HardwareInferenceEngine {
            features: HardwareFeatures {
                cpu_cores_physical: Some(8),
                cpu_cores_logical: Some(16),
                cpu_max_freq_mhz: Some(5000),
                cpu_model: Some("Intel Core i7-14700K".into()),
                cpu_vendor: Some("Intel".into()),
                is_server_cpu: false,
                has_ecc: Some(false),
                cpu_tdp_watts: Some(125.0),
                cpu_tdp_measured: false,
                ram_total_gb: Some(32.0),
                ram_channels: 2,
                ram_speed_mhz: 3600,
                has_discrete_gpu: Some(true),
                gpu_count: 1,
                gpu_model: "NVIDIA GeForce RTX 4070 Ti".into(),
                gpu_vram_gb: Some(12.0),
                has_tensor_cores: Some(true),
                has_rt_cores: Some(true),
                gpu_tdp_watts: Some(285.0),
                // Synthetic features, so the figure above is the table's, not a
                // driver's, and it prices one adapter.
                gpu_tdp_measured: false,
                gpu_adapters_counted: 1,
                has_nvme: Some(true),
                has_ssd: Some(true),
                total_storage_gb: Some(2000.0),
                boot_drive_type: Some("NVMe".into()),
                has_battery: false,
                chassis_type: Some("Desktop".into()),
                is_virtual: Some(false),
                numa_nodes: Some(1),
                pcie_gen: 4,
                max_nic_speed_gbps: Some(2.5),
                nic_count: Some(1),
            },
        };

        let report = engine.full_analysis();
        assert!(
            report.classification == SystemClass::GamingDesktop
                || report.classification == SystemClass::Desktop
                || report.classification == SystemClass::Workstation
        );
        assert!(report.performance_tier >= Some(PerformanceTier::MidHigh));
        assert!(report.performance_score.is_some_and(|s| s >= 50));
    }

    #[test]
    fn test_server_classification() {
        let engine = HardwareInferenceEngine {
            features: HardwareFeatures {
                cpu_cores_physical: Some(64),
                cpu_cores_logical: Some(128),
                cpu_max_freq_mhz: Some(2800),
                cpu_model: Some("AMD EPYC 9554".into()),
                cpu_vendor: Some("AMD".into()),
                is_server_cpu: true,
                has_ecc: Some(true),
                cpu_tdp_watts: Some(225.0),
                cpu_tdp_measured: false,
                ram_total_gb: Some(512.0),
                ram_channels: 8,
                ram_speed_mhz: 4800,
                has_discrete_gpu: Some(false),
                gpu_count: 0,
                gpu_model: String::new(),
                gpu_vram_gb: None,
                has_tensor_cores: Some(false),
                has_rt_cores: Some(false),
                gpu_tdp_watts: None,
                // Synthetic features, so the figure above is the table's, not a
                // driver's, and it prices one adapter.
                gpu_tdp_measured: false,
                gpu_adapters_counted: 1,
                has_nvme: Some(true),
                has_ssd: Some(true),
                total_storage_gb: Some(15000.0),
                boot_drive_type: Some("NVMe".into()),
                has_battery: false,
                chassis_type: Some("Server".into()),
                is_virtual: Some(false),
                numa_nodes: Some(2),
                pcie_gen: 5,
                max_nic_speed_gbps: Some(25.0),
                nic_count: Some(4),
            },
        };

        let report = engine.full_analysis();
        assert_eq!(report.classification, SystemClass::Server);
        assert!(report.performance_tier >= Some(PerformanceTier::High));
        // Virtualization should score highly
        let virt = report
            .workload_scores
            .iter()
            .find(|w| w.workload == Workload::Virtualization)
            .unwrap();
        assert!(virt.score >= 70);
    }

    #[test]
    fn test_laptop_bottleneck() {
        let engine = HardwareInferenceEngine {
            features: HardwareFeatures {
                cpu_cores_physical: Some(4),
                cpu_cores_logical: Some(8),
                cpu_max_freq_mhz: Some(2800),
                cpu_model: Some("Intel Core i5".into()),
                cpu_vendor: Some("Intel".into()),
                is_server_cpu: false,
                has_ecc: Some(false),
                cpu_tdp_watts: Some(15.0),
                cpu_tdp_measured: false,
                ram_total_gb: Some(8.0),
                ram_channels: 2,
                ram_speed_mhz: 3200,
                has_discrete_gpu: Some(true),
                gpu_count: 1,
                gpu_model: "NVIDIA GeForce RTX 4070 Laptop".into(),
                gpu_vram_gb: Some(8.0),
                has_tensor_cores: Some(true),
                has_rt_cores: Some(true),
                gpu_tdp_watts: Some(100.0),
                // Synthetic features, so the figure above is the table's, not a
                // driver's, and it prices one adapter.
                gpu_tdp_measured: false,
                gpu_adapters_counted: 1,
                has_nvme: Some(true),
                has_ssd: Some(true),
                total_storage_gb: Some(512.0),
                boot_drive_type: Some("NVMe".into()),
                has_battery: true,
                chassis_type: Some("Laptop".into()),
                is_virtual: Some(false),
                numa_nodes: Some(1),
                pcie_gen: 4,
                max_nic_speed_gbps: Some(1.0),
                nic_count: Some(1),
            },
        };

        let report = engine.full_analysis();
        // Should detect CPU or memory bottleneck
        assert!(!report.bottlenecks.is_empty());
        // Should detect anomaly (low RAM for GPU)
        assert!(!report.anomalies.is_empty() || !report.bottlenecks.is_empty());
    }

    #[test]
    fn test_cpu_year_inference() {
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("intel core i9-14900k"),
            Some(2024)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("amd ryzen 7 7800x3d"),
            Some(2022)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("apple m3 max"),
            Some(2023)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("amd epyc 9554"),
            Some(2023)
        );
    }

    /// Model numbers are not unique to a vendor, and the Intel rules match them
    /// bare.
    ///
    /// "AMD Ryzen 9 9900X" contains "9900" and was dated 2018 by the Intel
    /// 9th-gen Core rule --- a 2024 part reported as six years old. The cases
    /// already here happened not to collide, which is why nothing caught it.
    /// These are the collisions, in both directions.
    #[test]
    fn a_model_number_is_read_for_the_right_vendor() {
        // The collision that was wrong.
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("amd ryzen 9 9900x 12-core processor"),
            Some(2024)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("amd ryzen 9 9950x3d"),
            Some(2024)
        );
        // The Intel part whose number it was borrowing must still resolve.
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("intel core i9-9900k"),
            Some(2018)
        );
        // Ryzen 7000 against Intel 7th gen, the same shape one generation over.
        assert_eq!(
            HardwareInferenceEngine::infer_cpu_year("amd ryzen 7 7700x"),
            Some(2022)
        );
    }

    /// The year the report ages hardware against comes from the clock.
    ///
    /// It was the literal `2025.0`, in three places. A test that asserted the
    /// literal would have passed forever while the answer drifted, so this
    /// asserts the property instead: the value tracks the system clock, and no
    /// build of this crate is pinned to the year it was written in.
    #[test]
    fn the_current_year_comes_from_the_clock_not_from_the_source() {
        let year = HardwareInferenceEngine::current_year();
        assert!(
            year > 2024.0 && year < 2100.0,
            "current_year() returned {year}, which is not a plausible year from a \
             working clock"
        );

        // And it is not the constant that used to be here: this crate was
        // written in 2025 and is expected to keep running afterwards.
        let from_the_clock = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("the clock is after 1970")
            .as_secs_f32()
            / (365.2425 * 24.0 * 60.0 * 60.0)
            + 1970.0;
        assert!(
            (year - from_the_clock).abs() < 0.01,
            "current_year() {year} does not match the clock {from_the_clock}"
        );
    }

    /// A refresh ships after the series it belongs to.
    #[test]
    fn a_ti_refresh_is_not_dated_from_its_series() {
        // The card this engine was audited on. `rtx 30` would answer 2020; the
        // 3090 Ti shipped in March 2022.
        assert_eq!(
            HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 3090 ti"),
            Some(2022)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 3080 ti"),
            Some(2021)
        );
        // The base cards keep the series year.
        assert_eq!(
            HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 3090"),
            Some(2020)
        );
    }

    #[test]
    fn test_gpu_year_inference() {
        assert_eq!(
            HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 4090"),
            Some(2022)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_gpu_year("amd radeon rx 7900 xtx"),
            Some(2022)
        );
        assert_eq!(
            HardwareInferenceEngine::infer_gpu_year("nvidia h100"),
            Some(2023)
        );
    }

    #[test]
    fn test_performance_tier_scoring() {
        let engine = HardwareInferenceEngine {
            features: HardwareFeatures {
                cpu_cores_physical: Some(2),
                cpu_cores_logical: Some(4),
                cpu_max_freq_mhz: Some(1800),
                ram_total_gb: Some(4.0),
                has_discrete_gpu: Some(false),
                has_ssd: Some(false),
                has_nvme: Some(false),
                total_storage_gb: Some(500.0),
                ..HardwareFeatures::default()
            },
        };
        let (tier, _score) = engine.compute_performance_tier();
        assert!(tier <= PerformanceTier::MidLow);
    }

    #[test]
    fn test_workload_suitability() {
        let engine = HardwareInferenceEngine {
            features: HardwareFeatures {
                cpu_cores_physical: Some(16),
                cpu_cores_logical: Some(32),
                cpu_max_freq_mhz: Some(4500),
                ram_total_gb: Some(128.0),
                has_discrete_gpu: Some(true),
                gpu_vram_gb: Some(24.0),
                has_tensor_cores: Some(true),
                has_nvme: Some(true),
                has_ssd: Some(true),
                total_storage_gb: Some(4000.0),
                ..HardwareFeatures::default()
            },
        };
        let workloads = engine.score_workloads();
        let ml = workloads
            .iter()
            .find(|w| w.workload == Workload::MlTraining)
            .unwrap();
        assert!(ml.score >= 60); // Should score well for ML
    }

    fn engine_with(features: HardwareFeatures) -> HardwareInferenceEngine {
        HardwareInferenceEngine { features }
    }

    fn workload(engine: &HardwareInferenceEngine, kind: Workload) -> WorkloadSuitability {
        engine
            .score_workloads()
            .into_iter()
            .find(|w| w.workload == kind)
            .unwrap()
    }

    // Each test below leaves one input `None` (unread) and checks that the rules which
    // depend on it emit nothing. Without the `None` check, the same rules fire as if the
    // value were zero or false, which is how the advice used to be generated.

    #[test]
    fn unread_storage_emits_no_storage_advice() {
        let unread = engine_with(HardwareFeatures {
            cpu_cores_physical: Some(16),
            ..HardwareFeatures::default()
        });
        assert!(!unread
            .detect_bottlenecks()
            .iter()
            .any(|b| matches!(b.bottleneck_type, BottleneckType::StorageBound)));
        assert!(!unread
            .suggest_upgrades(&[])
            .iter()
            .any(|u| u.component == "Boot Drive"));
        assert!(!workload(&unread, Workload::DatabaseServer)
            .limiting_factors
            .iter()
            .any(|s| s.contains("HDD")));

        // The same machine with its disks read as spinning rust does get the advice.
        let hdd = engine_with(HardwareFeatures {
            cpu_cores_physical: Some(16),
            has_ssd: Some(false),
            has_nvme: Some(false),
            ..HardwareFeatures::default()
        });
        assert!(hdd
            .detect_bottlenecks()
            .iter()
            .any(|b| matches!(b.bottleneck_type, BottleneckType::StorageBound)));
        assert!(hdd
            .suggest_upgrades(&[])
            .iter()
            .any(|u| u.component == "Boot Drive"));
    }

    #[test]
    fn unread_vram_emits_no_vram_advice() {
        // A discrete card whose memory was not read, in a machine whose RAM was.
        let engine = engine_with(HardwareFeatures {
            cpu_cores_physical: Some(8),
            ram_total_gb: Some(8.0),
            has_discrete_gpu: Some(true),
            gpu_vram_gb: None,
            ..HardwareFeatures::default()
        });
        assert!(!engine
            .detect_bottlenecks()
            .iter()
            .any(|b| b.reason.contains("GPU workloads")));
        assert!(!engine
            .detect_anomalies()
            .iter()
            .any(|a| a.description.contains("VRAM")));
        assert!(!workload(&engine, Workload::MlTraining)
            .limiting_factors
            .iter()
            .any(|s| s.contains("VRAM")));
    }

    #[test]
    fn unread_ram_emits_no_ram_advice() {
        let engine = engine_with(HardwareFeatures {
            cpu_cores_physical: Some(16),
            has_discrete_gpu: Some(true),
            gpu_vram_gb: Some(24.0),
            ..HardwareFeatures::default()
        });
        assert!(!engine
            .suggest_upgrades(&[])
            .iter()
            .any(|u| u.component == "RAM"));
        assert!(!engine
            .detect_anomalies()
            .iter()
            .any(|a| a.description.contains("RAM")));
        assert!(!engine
            .detect_bottlenecks()
            .iter()
            .any(|b| b.component == "System RAM"));
        assert!(!workload(&engine, Workload::MlTraining)
            .limiting_factors
            .iter()
            .any(|s| s.contains("RAM")));
    }

    #[test]
    fn unread_gpu_presence_emits_no_gpu_absence_advice() {
        let engine = engine_with(HardwareFeatures {
            cpu_cores_physical: Some(16),
            ram_total_gb: Some(64.0),
            has_discrete_gpu: None,
            ..HardwareFeatures::default()
        });
        assert!(!engine
            .detect_anomalies()
            .iter()
            .any(|a| a.description.contains("no discrete GPU")));
        for kind in [Workload::MlInference, Workload::Gaming] {
            assert!(!workload(&engine, kind)
                .limiting_factors
                .iter()
                .any(|s| s.contains("No discrete GPU")));
        }
    }

    #[test]
    fn unread_network_emits_no_network_advice() {
        let engine = engine_with(HardwareFeatures {
            cpu_cores_physical: Some(64),
            is_server_cpu: true,
            ram_total_gb: Some(512.0),
            total_storage_gb: Some(15000.0),
            max_nic_speed_gbps: None,
            nic_count: None,
            ..HardwareFeatures::default()
        });
        assert!(!engine
            .detect_bottlenecks()
            .iter()
            .any(|b| matches!(b.bottleneck_type, BottleneckType::NetworkBound)));
        assert!(!engine
            .detect_anomalies()
            .iter()
            .any(|a| a.description.contains("Gbps")));
        assert!(!engine
            .suggest_upgrades(&[])
            .iter()
            .any(|u| u.component == "Network"));
        assert!(!workload(&engine, Workload::WebServer)
            .limiting_factors
            .iter()
            .any(|s| s.contains("Slow network")));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn powershell_output_is_read_as_items_or_as_nothing() {
        // One object, as ConvertTo-Json emits for a single disk, and an array for several.
        assert_eq!(json_items(r#"{"Name":"a"}"#).map(|v| v.len()), Some(1));
        assert_eq!(
            json_items(r#"[{"Name":"a"},{"Name":"b"}]"#).map(|v| v.len()),
            Some(2)
        );
        // No output, or text that is not JSON, is unread rather than an empty list.
        assert_eq!(json_items(""), None);
        assert_eq!(json_items("Get-PhysicalDisk : not recognized"), None);

        // A media or bus type PowerShell reports as "Unspecified" is not a classification.
        let table = &[("hdd", 3), ("ssd", 4)];
        let unspecified = serde_json::Value::String("Unspecified".into());
        assert_eq!(wmi_enum(Some(&unspecified), table), None);
        let ssd = serde_json::Value::String("SSD".into());
        assert_eq!(wmi_enum(Some(&ssd), table), Some(4));
    }

    #[test]
    fn cpu_identity_is_none_unless_a_name_or_vendor_was_read() {
        // WMI pads Name to a fixed width; the padding is trimmed away.
        let json: serde_json::Value = serde_json::from_str(
            r#"{"Name":"AMD Ryzen 9 9900X 12-Core Processor            ","Manufacturer":"AuthenticAMD"}"#,
        )
        .unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&json),
            (
                Some("AMD Ryzen 9 9900X 12-Core Processor".to_string()),
                Some("AuthenticAMD".to_string())
            )
        );

        // Absent fields, blank fields and non-string fields are unread, not "".
        let missing: serde_json::Value = serde_json::from_str(r#"{"NumberOfCores":8}"#).unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&missing),
            (None, None)
        );
        let blank: serde_json::Value =
            serde_json::from_str(r#"{"Name":"   ","Manufacturer":""}"#).unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&blank),
            (None, None)
        );
        let wrong_type: serde_json::Value = serde_json::from_str(r#"{"Name":42}"#).unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&wrong_type),
            (None, None)
        );
    }

    #[test]
    fn cpu_identity_reads_a_multi_socket_array_when_sockets_agree() {
        // Two sockets of one model: ConvertTo-Json emits an array.
        let agreeing: serde_json::Value = serde_json::from_str(
            r#"[{"Name":"Intel Xeon Gold 6248R CPU @ 3.00GHz   ","Manufacturer":"GenuineIntel"},
                {"Name":"Intel Xeon Gold 6248R CPU @ 3.00GHz   ","Manufacturer":"GenuineIntel"}]"#,
        )
        .unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&agreeing),
            (
                Some("Intel Xeon Gold 6248R CPU @ 3.00GHz".to_string()),
                Some("GenuineIntel".to_string())
            )
        );

        // Sockets that disagree on the name have no single identity; the
        // manufacturer that they share still reads.
        let mixed: serde_json::Value = serde_json::from_str(
            r#"[{"Name":"Intel Xeon Gold 6248R","Manufacturer":"GenuineIntel"},
                {"Name":"Intel Xeon Silver 4210","Manufacturer":"GenuineIntel"}]"#,
        )
        .unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&mixed),
            (None, Some("GenuineIntel".to_string()))
        );

        // An empty array is nothing read.
        let empty: serde_json::Value = serde_json::from_str("[]").unwrap();
        assert_eq!(
            HardwareInferenceEngine::windows_cpu_identity(&empty),
            (None, None)
        );
    }

    #[test]
    fn test_serialization() {
        let engine = HardwareInferenceEngine::new().unwrap();
        let report = engine.full_analysis();
        let json = serde_json::to_string(&report).unwrap();
        let _: HardwareAnalysisReport = serde_json::from_str(&json).unwrap();
    }
}