denet 0.7.0

a simple process monitor
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
#[cfg(any(not(target_os = "linux"), test))]
#[allow(unused_imports)]
use crate::core::constants::delays;
use crate::core::constants::system;
use crate::monitor::{
    AggregatedMetrics, Capabilities, ChildProcessMetrics, Metrics, ProcessMetadata,
    ProcessTreeMetrics, Summary,
};
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use sysinfo::{self, Pid, ProcessRefreshKind, ProcessesToUpdate, System};

/// Default process refresh flags.
///
/// `ProcessRefreshKind::everything()` enables `tasks: true`, which makes
/// sysinfo enumerate every kernel thread under `/proc/[tgid]/task/` as its
/// own entry in `System::processes()`. Those task entries report the tgid as
/// their parent, so any code that walks `processes()` looking for children
/// would treat each thread of the monitored process as a child and
/// double-count its CPU time (the parent's `/proc/[pid]/stat` already
/// includes all threads). We never read `process.tasks()`, so disable it
/// everywhere.
fn process_refresh_kind() -> ProcessRefreshKind {
    ProcessRefreshKind::everything().without_tasks()
}

// Constants for better maintainability
const DEFAULT_THREAD_COUNT: usize = 1;
// Linux-specific constants with separate test access
#[cfg(any(target_os = "linux", test))]
const LINUX_PROC_DIR: &str = "/proc";
#[cfg(any(target_os = "linux", test))]
const LINUX_TASK_SUBDIR: &str = "/task";

/// Get the number of threads for a process
/// In the long run, we will want this function to be more robust
/// or use platform-specific APIs. For now, we'll keep it simple.
pub(crate) fn get_thread_count(pid: usize) -> usize {
    get_linux_thread_count(pid).unwrap_or(DEFAULT_THREAD_COUNT)
}

#[cfg(target_os = "linux")]
fn get_linux_thread_count(pid: usize) -> Option<usize> {
    let task_dir = format!("{LINUX_PROC_DIR}/{pid}{LINUX_TASK_SUBDIR}");
    std::fs::read_dir(task_dir)
        .ok()
        .map(|entries| entries.count())
}

#[cfg(not(target_os = "linux"))]
fn get_linux_thread_count(_pid: usize) -> Option<usize> {
    None
}

/// Read rchar/wchar (bytes moved through read()/write() syscalls) from /proc/pid/io.
/// Returns (read_chars, write_chars). Captures page-cache hits that `read_bytes` misses.
/// Does NOT capture mmap access — see `read_page_faults` for that.
#[cfg(target_os = "linux")]
fn read_syscall_io_bytes(pid: usize) -> Option<(u64, u64)> {
    let content = std::fs::read_to_string(format!("{LINUX_PROC_DIR}/{pid}/io")).ok()?;
    let mut rchar = None;
    let mut wchar = None;
    for line in content.lines() {
        if let Some(v) = line.strip_prefix("rchar: ") {
            rchar = v.trim().parse::<u64>().ok();
        } else if let Some(v) = line.strip_prefix("wchar: ") {
            wchar = v.trim().parse::<u64>().ok();
        }
    }
    Some((rchar?, wchar?))
}

#[cfg(not(target_os = "linux"))]
fn read_syscall_io_bytes(_pid: usize) -> Option<(u64, u64)> {
    None
}

/// Read minor and major page fault counters from /proc/pid/stat.
/// Fields 10 (minflt) and 12 (majflt) — the process's own faults, excluding children.
/// Major faults indicate disk reads (incl. mmap cold pages); minor faults indicate
/// page activity that was satisfied from cache (incl. mmap warm pages).
#[cfg(target_os = "linux")]
fn read_page_faults(pid: usize) -> Option<(u64, u64)> {
    let content = std::fs::read_to_string(format!("{LINUX_PROC_DIR}/{pid}/stat")).ok()?;
    // comm (field 2) is parenthesized and may contain spaces/parens; split after the last ')'
    let rparen = content.rfind(')')?;
    let rest = &content[rparen + 1..];
    let fields: Vec<&str> = rest.split_whitespace().collect();
    // After comm: index 0 = state (field 3). minflt is field 10 → index 7. majflt is field 12 → index 9.
    let minflt = fields.get(7)?.parse::<u64>().ok()?;
    let majflt = fields.get(9)?.parse::<u64>().ok()?;
    Some((minflt, majflt))
}

#[cfg(not(target_os = "linux"))]
fn read_page_faults(_pid: usize) -> Option<(u64, u64)> {
    None
}

/// Subtract two Option<u64> counters for delta-from-baseline; preserves None when
/// either side is unavailable so the metric stays honestly missing.
#[inline]
fn option_sub(cur: Option<u64>, base: Option<u64>) -> Option<u64> {
    match (cur, base) {
        (Some(c), Some(b)) => Some(c.saturating_sub(b)),
        _ => None,
    }
}

/// Detect optional memory-characterization sources at startup. Always returns
/// a populated `Capabilities`; on non-Linux or restricted environments the
/// fields just describe why each source was skipped.
#[cfg(target_os = "linux")]
fn init_mem_sources(pid: usize) -> (Option<crate::perf::PerfGroup>, Capabilities) {
    let psi = Some(crate::psi::detect(pid));
    let mut perf_cap = crate::perf::detect();
    let perf_group = if perf_cap.available {
        match crate::perf::PerfGroup::open(pid as libc::pid_t) {
            Ok(g) => {
                // Replace the speculative event list from detect() with the
                // events that actually opened on the target.
                perf_cap.events = g.opened_events();
                Some(g)
            }
            Err(reason) => {
                perf_cap.available = false;
                perf_cap.reason = Some(format!("opened on self but not on target pid: {reason}"));
                perf_cap.events.clear();
                None
            }
        }
    } else {
        None
    };
    (
        perf_group,
        Capabilities {
            psi,
            perf_hw: Some(perf_cap),
        },
    )
}

#[cfg(not(target_os = "linux"))]
fn init_mem_sources(pid: usize) -> ((), Capabilities) {
    let psi = Some(crate::psi::detect(pid));
    ((), Capabilities { psi, perf_hw: None })
}

/// Read metrics from a JSON file and generate a summary
pub fn summary_from_json_file<P: AsRef<Path>>(path: P) -> io::Result<Summary> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    let mut metrics_vec: Vec<AggregatedMetrics> = Vec::new();
    let mut regular_metrics: Vec<Metrics> = Vec::new();
    let mut first_timestamp: Option<u64> = None;
    let mut last_timestamp: Option<u64> = None;

    // Process file line by line since each line is a separate JSON object
    for line in reader.lines() {
        let line = line?;

        // Skip empty lines
        if line.trim().is_empty() {
            continue;
        }

        // Try the tagged Record schema first; fall back to legacy untagged
        // shapes for files written before the `kind` discriminator existed.
        match crate::monitor::record::parse_record(&line) {
            Some(crate::monitor::record::Record::Aggregated(agg)) => {
                if first_timestamp.is_none() {
                    first_timestamp = Some(agg.ts_ms);
                }
                last_timestamp = Some(agg.ts_ms);
                metrics_vec.push(*agg);
            }
            Some(crate::monitor::record::Record::Tree(tree)) => {
                if let Some(agg) = tree.aggregated {
                    if first_timestamp.is_none() {
                        first_timestamp = Some(agg.ts_ms);
                    }
                    last_timestamp = Some(agg.ts_ms);
                    metrics_vec.push(agg);
                }
            }
            Some(crate::monitor::record::Record::Sample(metric)) => {
                if first_timestamp.is_none() {
                    first_timestamp = Some(metric.ts_ms);
                }
                last_timestamp = Some(metric.ts_ms);
                regular_metrics.push(metric);
            }
            // Env / Metadata / unknown: header records, no metric content.
            _ => {}
        }
    }

    // Calculate total time
    let elapsed_time = match (first_timestamp, last_timestamp) {
        (Some(first), Some(last)) => (last - first) as f64 / 1000.0,
        _ => 0.0,
    };

    // Generate summary based on the metrics we found
    if !metrics_vec.is_empty() {
        Ok(Summary::from_aggregated_metrics(&metrics_vec, elapsed_time))
    } else if !regular_metrics.is_empty() {
        Ok(Summary::from_metrics(&regular_metrics, elapsed_time))
    } else {
        Ok(Summary::default()) // Return empty summary if no metrics found
    }
}

#[derive(Debug, Clone)]
pub struct IoBaseline {
    pub disk_read_bytes: u64,
    pub disk_write_bytes: u64,
    pub syscall_read_bytes: Option<u64>,
    pub syscall_write_bytes: Option<u64>,
    pub page_faults_cached: Option<u64>,
    pub page_faults_disk: Option<u64>,
    pub sys_net_rx_bytes: u64,
    pub sys_net_tx_bytes: u64,
}

#[derive(Debug, Clone)]
pub struct ChildIoBaseline {
    pub pid: usize,
    pub disk_read_bytes: u64,
    pub disk_write_bytes: u64,
    pub syscall_read_bytes: Option<u64>,
    pub syscall_write_bytes: Option<u64>,
    pub page_faults_cached: Option<u64>,
    pub page_faults_disk: Option<u64>,
    pub sys_net_rx_bytes: u64,
    pub sys_net_tx_bytes: u64,
}

// Main process monitor implementation
#[derive(Debug)]
pub struct ProcessMonitor {
    child: Option<Child>,
    pid: usize,
    sys: System,
    base_interval: Duration,
    max_interval: Duration,
    start_time: Instant,
    t0_ms: u64,
    io_baseline: Option<IoBaseline>,
    child_io_baselines: std::collections::HashMap<usize, ChildIoBaseline>,
    since_process_start: bool,
    include_children: bool,
    enable_ebpf: bool,
    debug_mode: bool,
    #[cfg(feature = "ebpf")]
    ebpf_tracker: Option<crate::ebpf::SyscallTracker>,
    #[cfg(feature = "ebpf")]
    offcpu_profiler: Option<crate::ebpf::OffCpuProfiler>,
    last_refresh_time: Instant,
    #[cfg(target_os = "linux")]
    cpu_sampler: crate::cpu_sampler::CpuSampler,
    #[cfg(feature = "gpu")]
    gpu_monitor: crate::gpu::GpuMonitor,
    /// Per-pid hardware perf counters; `None` if perf_event_open was denied or
    /// not supported. Detected once at startup.
    #[cfg(target_os = "linux")]
    perf_group: Option<crate::perf::PerfGroup>,
    /// Whether per-process PSI is readable for `pid`. System-wide PSI is
    /// always tried as a fallback.
    psi_per_process: bool,
    /// Capability manifest, captured once at startup so `get_metadata()` can
    /// surface it in the JSONL header without re-detecting.
    capabilities: Capabilities,
}

// We'll use a Result type directly instead of a custom ErrorType to avoid orphan rule issues
pub type ProcessResult<T> = std::result::Result<T, std::io::Error>;

impl ProcessMonitor {
    pub fn new(
        cmd: Vec<String>,
        base_interval: Duration,
        max_interval: Duration,
    ) -> ProcessResult<Self> {
        Self::new_with_options(cmd, base_interval, max_interval, false)
    }

    // Create a new process monitor with I/O accounting options
    pub fn new_with_options(
        cmd: Vec<String>,
        base_interval: Duration,
        max_interval: Duration,
        since_process_start: bool,
    ) -> ProcessResult<Self> {
        if cmd.is_empty() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Command cannot be empty",
            ));
        }

        let child = Command::new(&cmd[0])
            .args(&cmd[1..])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()?;
        let pid = child.id();

        // Use minimal system initialization - avoid expensive system-wide scans
        let mut sys = System::new();
        // Only refresh CPU info once at startup
        sys.refresh_cpu_all();

        let now = Instant::now();
        let pid_usize: usize = pid.try_into().unwrap();
        #[cfg(target_os = "linux")]
        let (perf_group, capabilities) = init_mem_sources(pid_usize);
        #[cfg(not(target_os = "linux"))]
        let (_unit, capabilities) = init_mem_sources(pid_usize);
        let psi_per_process = capabilities
            .psi
            .as_ref()
            .map(|c| c.per_process)
            .unwrap_or(false);
        Ok(Self {
            child: Some(child),
            pid: pid_usize,
            sys,
            base_interval,
            max_interval,
            start_time: now,
            t0_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("Time went backwards")
                .as_millis() as u64,
            include_children: true,
            debug_mode: false,
            io_baseline: None,
            child_io_baselines: std::collections::HashMap::new(),
            since_process_start,
            enable_ebpf: false,
            #[cfg(feature = "ebpf")]
            ebpf_tracker: None,
            #[cfg(feature = "ebpf")]
            offcpu_profiler: None,
            last_refresh_time: now,
            #[cfg(target_os = "linux")]
            cpu_sampler: crate::cpu_sampler::CpuSampler::new(),
            #[cfg(feature = "gpu")]
            gpu_monitor: crate::gpu::GpuMonitor::new(),
            #[cfg(target_os = "linux")]
            perf_group,
            psi_per_process,
            capabilities,
        })
    }

    // Create a process monitor for an existing process
    pub fn from_pid(
        pid: usize,
        base_interval: Duration,
        max_interval: Duration,
    ) -> ProcessResult<Self> {
        Self::from_pid_with_options(pid, base_interval, max_interval, false)
    }

    // Create a process monitor for an existing process with I/O accounting options
    pub fn from_pid_with_options(
        pid: usize,
        base_interval: Duration,
        max_interval: Duration,
        since_process_start: bool,
    ) -> ProcessResult<Self> {
        // Use minimal system initialization - avoid expensive system-wide scans
        let mut sys = System::new();
        // Only refresh CPU info once at startup
        sys.refresh_cpu_all();

        // Check if the specific process exists - much faster than system-wide scan
        let pid_sys = Pid::from_u32(pid as u32);

        // Try to refresh just this process instead of all processes
        let mut retries = 3;
        let mut process_found = false;

        while retries > 0 && !process_found {
            // Only refresh the specific process we care about
            sys.refresh_processes_specifics(
                ProcessesToUpdate::Some(&[pid_sys]),
                true,
                process_refresh_kind(),
            );
            if sys.process(pid_sys).is_some() {
                process_found = true;
            } else {
                retries -= 1;
                // Shorter sleep since we're doing targeted refresh
                std::thread::sleep(system::PROCESS_DETECTION);
            }
        }

        if !process_found {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Process with PID {pid} not found"),
            ));
        }

        let now = Instant::now();
        #[cfg(target_os = "linux")]
        let (perf_group, capabilities) = init_mem_sources(pid);
        #[cfg(not(target_os = "linux"))]
        let (_unit, capabilities) = init_mem_sources(pid);
        let psi_per_process = capabilities
            .psi
            .as_ref()
            .map(|c| c.per_process)
            .unwrap_or(false);
        Ok(Self {
            child: None,
            pid,
            sys,
            base_interval,
            max_interval,
            start_time: now,
            t0_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("Time went backwards")
                .as_millis() as u64,
            include_children: true,
            debug_mode: false,
            io_baseline: None,
            child_io_baselines: std::collections::HashMap::new(),
            since_process_start,
            enable_ebpf: false,
            #[cfg(feature = "ebpf")]
            ebpf_tracker: None,
            #[cfg(feature = "ebpf")]
            offcpu_profiler: None,
            last_refresh_time: now,
            #[cfg(target_os = "linux")]
            cpu_sampler: crate::cpu_sampler::CpuSampler::new(),
            #[cfg(feature = "gpu")]
            gpu_monitor: crate::gpu::GpuMonitor::new(),
            #[cfg(target_os = "linux")]
            perf_group,
            psi_per_process,
            capabilities,
        })
    }

    /// Set debug mode for verbose output
    pub fn set_debug_mode(&mut self, debug: bool) {
        self.debug_mode = debug;

        #[cfg(feature = "ebpf")]
        unsafe {
            crate::ebpf::debug::set_debug_mode(debug);
        }

        if debug {
            log::info!("Debug mode enabled - verbose output will be shown");
        }
    }

    /// Enable eBPF profiling for this monitor
    #[cfg(feature = "ebpf")]
    pub fn enable_ebpf(&mut self) -> crate::error::Result<()> {
        if !self.enable_ebpf {
            log::info!("Attempting to enable eBPF profiling");
            if self.debug_mode {
                println!("DEBUG: Attempting to enable eBPF profiling");

                // Print current process info
                println!(
                    "DEBUG: Process monitor running with PID: {}",
                    std::process::id()
                );
                println!("DEBUG: Monitoring target PID: {}", self.pid);

                // Check for eBPF feature compilation
                println!("DEBUG: eBPF feature is enabled at compile time");
            }

            // Collect all PIDs in the process tree
            let mut pids = vec![self.pid as u32];

            // Add child PIDs
            self.sys.refresh_processes_specifics(
                ProcessesToUpdate::All,
                true,
                process_refresh_kind(),
            );
            if let Some(_parent_proc) = self.sys.process(Pid::from_u32(self.pid as u32)) {
                for child_pid in self.sys.processes().keys() {
                    if let Some(child_proc) = self.sys.process(*child_pid) {
                        if let Some(parent_pid) = child_proc.parent() {
                            if parent_pid == Pid::from_u32(self.pid as u32) {
                                pids.push(child_pid.as_u32());
                            }
                        }
                    }
                }
            }

            if self.debug_mode {
                println!(
                    "DEBUG: Collected {} PIDs to monitor: {:?}",
                    pids.len(),
                    pids
                );
            }
            log::info!("Collected {} PIDs to monitor", pids.len());

            // Check system readiness for eBPF
            if self.debug_mode {
                let readiness_check = std::process::Command::new("sh")
                    .arg("-c")
                    .arg("echo 'Checking eBPF prerequisites from process_monitor:'; \
                        echo -n 'Kernel version: '; uname -r; \
                        echo -n 'Debugfs mounted: '; mount | grep -q debugfs && echo 'YES' || echo 'NO'; \
                        echo -n 'Tracefs accessible: '; [ -d /sys/kernel/debug/tracing ] && echo 'YES' || echo 'NO';")
                    .output();

                if let Ok(output) = readiness_check {
                    let report = String::from_utf8_lossy(&output.stdout);
                    println!("DEBUG: {}", report);
                    log::info!("eBPF readiness: {}", report);
                }
            }

            // Initialize eBPF tracker
            match crate::ebpf::SyscallTracker::new(pids.clone()) {
                Ok(tracker) => {
                    self.ebpf_tracker = Some(tracker);
                    self.enable_ebpf = true;
                    log::info!("✅ eBPF profiling successfully enabled");
                    if self.debug_mode {
                        println!("DEBUG: eBPF profiling successfully enabled");
                    }
                }
                Err(e) => {
                    log::warn!("Failed to enable eBPF: {}", e);
                    if self.debug_mode {
                        println!("DEBUG: Failed to enable eBPF: {}", e);

                        // Additional diagnostics
                        if let Ok(output) = std::process::Command::new("sh")
                            .arg("-c")
                            .arg("dmesg | grep -i bpf | tail -5")
                            .output()
                        {
                            let kernel_logs = String::from_utf8_lossy(&output.stdout);
                            if !kernel_logs.trim().is_empty() {
                                println!("DEBUG: Recent kernel BPF logs:\n{}", kernel_logs);
                                log::warn!("Recent kernel BPF logs:\n{}", kernel_logs);
                            }
                        }
                    }

                    return Err(e);
                }
            }

            // Initialize off-CPU profiler
            match crate::ebpf::OffCpuProfiler::new(pids) {
                Ok(mut profiler) => {
                    if self.debug_mode {
                        profiler.enable_debug_mode();
                    }
                    self.offcpu_profiler = Some(profiler);
                    log::info!("Off-CPU profiler enabled");
                }
                Err(e) => {
                    log::warn!("Failed to enable off-CPU profiler: {}", e);
                }
            }

            Ok(())
        } else {
            // Already enabled, just return success
            Ok(())
        }
    }

    /// Enable eBPF profiling for this monitor (no-op on non-eBPF builds)
    #[cfg(not(feature = "ebpf"))]
    pub fn enable_ebpf(&mut self) -> crate::error::Result<()> {
        log::warn!("eBPF feature not enabled at compile time");
        if self.debug_mode {
            println!(
                "DEBUG: eBPF feature not enabled at compile time. Cannot enable eBPF profiling."
            );
            println!("DEBUG: To enable eBPF support, rebuild with: cargo build --features ebpf");
        }
        // Set the flag to false to ensure consistent behavior
        self.enable_ebpf = false;
        Err(crate::error::DenetError::EbpfNotSupported(
            "eBPF feature not enabled. Build with --features ebpf".to_string(),
        ))
    }

    pub fn adaptive_interval(&self) -> Duration {
        // Adaptive sampling strategy:
        // - First 1 second: use base_interval (fast sampling for short processes)
        // - 1-10 seconds: gradually increase from base to max
        // - After 10 seconds: use max_interval
        let elapsed = self.start_time.elapsed().as_secs_f64();

        let interval_secs = if elapsed < 1.0 {
            // First second: sample at base rate
            self.base_interval.as_secs_f64()
        } else if elapsed < 10.0 {
            // 1-10 seconds: linear interpolation between base and max
            let t = (elapsed - 1.0) / 9.0; // 0 to 1 over 9 seconds
            let base = self.base_interval.as_secs_f64();
            let max = self.max_interval.as_secs_f64();
            base + (max - base) * t
        } else {
            // After 10 seconds: use max interval
            self.max_interval.as_secs_f64()
        };

        Duration::from_secs_f64(interval_secs)
    }

    pub fn sample_metrics(&mut self) -> Option<Metrics> {
        let now = Instant::now();
        self.last_refresh_time = now;

        // We still need to refresh the process for memory and other metrics
        let pid = Pid::from_u32(self.pid as u32);
        self.sys.refresh_processes_specifics(
            ProcessesToUpdate::Some(&[pid]),
            false,
            process_refresh_kind(),
        );

        let process = self.sys.process(pid)?;

        // Extract basic process info
        let mem_rss_kb = process.memory() / 1024;
        let mem_vms_kb = process.virtual_memory() / 1024;
        let current_disk_read = process.disk_usage().total_read_bytes;
        let current_disk_write = process.disk_usage().total_written_bytes;
        let current_syscall_io = read_syscall_io_bytes(self.pid);
        let current_faults = read_page_faults(self.pid);
        let thread_count = get_thread_count(self.pid);
        let uptime_secs = process.run_time();

        // Get CPU usage based on platform
        #[cfg(target_os = "linux")]
        let cpu_usage = self.cpu_sampler.get_cpu_usage(self.pid).unwrap_or(0.0);

        #[cfg(not(target_os = "linux"))]
        let cpu_usage = {
            // Store CPU usage before refreshing
            let old_cpu_usage = process.cpu_usage();

            // On non-Linux platforms, we need to refresh CPU info for accurate measurement
            let time_since_last_refresh = now.duration_since(self.last_refresh_time);

            // Get a copy of the process info before refreshing
            let _pid_copy = process.pid();

            // Now we can safely refresh
            let _ = process; // Explicitly drop the process reference
            self.sys.refresh_cpu_all();

            // If not enough time has passed, add a delay for accuracy
            if time_since_last_refresh < delays::CPU_MEASUREMENT {
                std::thread::sleep(delays::CPU_MEASUREMENT);
                self.sys.refresh_cpu_all();
                self.sys.refresh_processes_specifics(
                    ProcessesToUpdate::Some(&[pid]),
                    false,
                    process_refresh_kind(),
                );

                // Get updated CPU usage if process still exists
                if let Some(updated_proc) = self.sys.process(pid) {
                    updated_proc.cpu_usage()
                } else {
                    old_cpu_usage
                }
            } else {
                old_cpu_usage
            }
        };

        // Get network I/O
        let current_net_rx = self.get_process_sys_net_rx_bytes();
        let current_net_tx = self.get_process_sys_net_tx_bytes();

        let cur_rchar = current_syscall_io.map(|(r, _)| r);
        let cur_wchar = current_syscall_io.map(|(_, w)| w);
        let cur_minflt = current_faults.map(|(m, _)| m);
        let cur_majflt = current_faults.map(|(_, m)| m);

        // Handle I/O baseline for delta calculation
        let (
            disk_read_bytes,
            disk_write_bytes,
            syscall_read_bytes,
            syscall_write_bytes,
            page_faults_cached,
            page_faults_disk,
            sys_net_rx_bytes,
            sys_net_tx_bytes,
        ) = if self.since_process_start {
            (
                current_disk_read,
                current_disk_write,
                cur_rchar,
                cur_wchar,
                cur_minflt,
                cur_majflt,
                current_net_rx,
                current_net_tx,
            )
        } else if let Some(baseline) = self.io_baseline.as_ref() {
            (
                current_disk_read.saturating_sub(baseline.disk_read_bytes),
                current_disk_write.saturating_sub(baseline.disk_write_bytes),
                option_sub(cur_rchar, baseline.syscall_read_bytes),
                option_sub(cur_wchar, baseline.syscall_write_bytes),
                option_sub(cur_minflt, baseline.page_faults_cached),
                option_sub(cur_majflt, baseline.page_faults_disk),
                current_net_rx.saturating_sub(baseline.sys_net_rx_bytes),
                current_net_tx.saturating_sub(baseline.sys_net_tx_bytes),
            )
        } else {
            self.io_baseline = Some(IoBaseline {
                disk_read_bytes: current_disk_read,
                disk_write_bytes: current_disk_write,
                syscall_read_bytes: cur_rchar,
                syscall_write_bytes: cur_wchar,
                page_faults_cached: cur_minflt,
                page_faults_disk: cur_majflt,
                sys_net_rx_bytes: current_net_rx,
                sys_net_tx_bytes: current_net_tx,
            });
            // First sample shows 0 delta; Option fields are Some(0) when source is available.
            (
                0,
                0,
                cur_rchar.map(|_| 0),
                cur_wchar.map(|_| 0),
                cur_minflt.map(|_| 0),
                cur_majflt.map(|_| 0),
                0,
                0,
            )
        };

        let ts_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as u64;

        // Sample GPU metrics if available
        #[cfg(feature = "gpu")]
        let gpu_metrics = if self.gpu_monitor.is_enabled() {
            Some(self.gpu_monitor.sample_metrics(&[self.pid as u32]))
        } else {
            None
        };

        #[cfg(not(feature = "gpu"))]
        let gpu_metrics = None;

        // PSI: prefer per-process if available, else fall back to system-wide.
        let psi_mem = if self.psi_per_process {
            crate::psi::read_process(self.pid).or_else(crate::psi::read_system)
        } else {
            crate::psi::read_system()
        };

        // Hardware perf counter deltas (Linux only).
        #[cfg(target_os = "linux")]
        let perf = self.perf_group.as_mut().and_then(|g| g.sample_delta());
        #[cfg(not(target_os = "linux"))]
        let perf = None;

        Some(Metrics {
            ts_ms,
            cpu_usage,
            mem_rss_kb,
            mem_vms_kb,
            disk_read_bytes,
            disk_write_bytes,
            syscall_read_bytes,
            syscall_write_bytes,
            page_faults_cached,
            page_faults_disk,
            sys_net_rx_bytes,
            sys_net_tx_bytes,
            thread_count,
            uptime_secs,
            cpu_core: Self::get_process_cpu_core(self.pid),
            gpu: gpu_metrics,
            psi_mem,
            perf,
        })
    }

    pub fn is_running(&mut self) -> bool {
        // If we have a child process, use try_wait to check its status
        if let Some(child) = &mut self.child {
            match child.try_wait() {
                Ok(Some(_)) => false,
                Ok(None) => true,
                Err(_) => false,
            }
        } else {
            // For existing processes, check if it still exists
            let pid = Pid::from_u32(self.pid as u32);

            // First try with specific process refresh
            self.sys.refresh_processes_specifics(
                ProcessesToUpdate::Some(&[pid]),
                false,
                process_refresh_kind(),
            );

            // If specific refresh doesn't work, try refreshing all processes
            if self.sys.process(pid).is_none() {
                self.sys.refresh_processes_specifics(
                    ProcessesToUpdate::All,
                    true,
                    process_refresh_kind(),
                );

                // Give a small amount of time for the process to be detected
                // This helps with the test reliability
                std::thread::sleep(system::PROCESS_DETECTION);
            }

            self.sys.process(pid).is_some()
        }
    }

    // Get the process ID
    pub fn get_pid(&self) -> usize {
        self.pid
    }

    /// Set whether to include children processes in monitoring
    pub fn set_include_children(&mut self, include_children: bool) -> &mut Self {
        self.include_children = include_children;
        self
    }

    /// Get whether children processes are included in monitoring
    pub fn get_include_children(&self) -> bool {
        self.include_children
    }

    /// Snapshot host/NUMA/affinity/governor state for the monitored PID.
    /// One-shot, suitable for writing as the first JSONL line.
    pub fn get_env(&self) -> crate::monitor::EnvRecord {
        crate::monitor::EnvRecord::collect(self.pid as u32)
    }

    /// Returns metadata about the monitored process
    // Get process metadata (static information)
    pub fn get_metadata(&mut self) -> Option<ProcessMetadata> {
        let pid = Pid::from_u32(self.pid as u32);
        self.sys.refresh_processes_specifics(
            ProcessesToUpdate::Some(&[pid]),
            false,
            process_refresh_kind(),
        );

        if let Some(proc) = self.sys.process(pid) {
            // Convert OsString to String with potential data loss on invalid UTF-8
            let cmd: Vec<String> = proc
                .cmd()
                .iter()
                .map(|os_str| os_str.to_string_lossy().to_string())
                .collect();

            // Handle exe which is now Option<&Path>
            let executable = proc
                .exe()
                .map(|path| path.to_string_lossy().to_string())
                .unwrap_or_default();

            Some(ProcessMetadata {
                pid: self.pid,
                cmd,
                executable,
                t0_ms: self.t0_ms,
                capabilities: Some(self.capabilities.clone()),
            })
        } else {
            None
        }
    }

    // Get all child processes recursively
    pub fn get_child_pids(&mut self) -> Vec<usize> {
        self.sys
            .refresh_processes_specifics(ProcessesToUpdate::All, true, process_refresh_kind());
        let mut children = Vec::new();
        self.find_children_recursive(self.pid, &mut children);
        children
    }

    // Recursively find all descendants of a process
    fn find_children_recursive(&self, parent_pid: usize, children: &mut Vec<usize>) {
        let parent_pid_sys = Pid::from_u32(parent_pid as u32);
        for (pid, process) in self.sys.processes() {
            if let Some(ppid) = process.parent() {
                if ppid == parent_pid_sys {
                    let child_pid = pid.as_u32() as usize;
                    children.push(child_pid);
                    // Recursively find grandchildren
                    self.find_children_recursive(child_pid, children);
                }
            }
        }
    }

    // Sample metrics including child processes
    pub fn sample_tree_metrics(&mut self) -> ProcessTreeMetrics {
        let tree_ts_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as u64;

        // Get parent metrics
        let parent_metrics = self.sample_metrics();

        // Get child PIDs and their metrics
        let child_pids = self.get_child_pids();
        let mut child_metrics = Vec::new();

        for child_pid in child_pids.iter() {
            // We no longer need delays between child measurements for Linux with our new CPU sampler
            // But we still need to refresh process info for other metrics
            let pid = Pid::from_u32(*child_pid as u32);
            self.sys.refresh_processes_specifics(
                ProcessesToUpdate::Some(&[pid]),
                false,
                process_refresh_kind(),
            );

            if let Some(proc) = self.sys.process(pid) {
                let command = proc.name().to_string_lossy().to_string();

                // Get I/O stats for child
                let current_disk_read = proc.disk_usage().total_read_bytes;
                let current_disk_write = proc.disk_usage().total_written_bytes;
                let current_syscall_io = read_syscall_io_bytes(*child_pid);
                let current_faults = read_page_faults(*child_pid);
                let cur_rchar = current_syscall_io.map(|(r, _)| r);
                let cur_wchar = current_syscall_io.map(|(_, w)| w);
                let cur_minflt = current_faults.map(|(m, _)| m);
                let cur_majflt = current_faults.map(|(_, m)| m);
                let current_net_rx = 0; // TODO: Implement for children
                let current_net_tx = 0;

                // Handle I/O baseline for child processes
                let (
                    disk_read_bytes,
                    disk_write_bytes,
                    syscall_read_bytes,
                    syscall_write_bytes,
                    page_faults_cached,
                    page_faults_disk,
                    sys_net_rx_bytes,
                    sys_net_tx_bytes,
                ) = if self.since_process_start {
                    (
                        current_disk_read,
                        current_disk_write,
                        cur_rchar,
                        cur_wchar,
                        cur_minflt,
                        cur_majflt,
                        current_net_rx,
                        current_net_tx,
                    )
                } else {
                    match self.child_io_baselines.entry(*child_pid) {
                        std::collections::hash_map::Entry::Vacant(e) => {
                            e.insert(ChildIoBaseline {
                                pid: *child_pid,
                                disk_read_bytes: current_disk_read,
                                disk_write_bytes: current_disk_write,
                                syscall_read_bytes: cur_rchar,
                                syscall_write_bytes: cur_wchar,
                                page_faults_cached: cur_minflt,
                                page_faults_disk: cur_majflt,
                                sys_net_rx_bytes: current_net_rx,
                                sys_net_tx_bytes: current_net_tx,
                            });
                            (
                                0,
                                0,
                                cur_rchar.map(|_| 0),
                                cur_wchar.map(|_| 0),
                                cur_minflt.map(|_| 0),
                                cur_majflt.map(|_| 0),
                                0,
                                0,
                            )
                        }
                        std::collections::hash_map::Entry::Occupied(e) => {
                            let baseline = e.get();
                            (
                                current_disk_read.saturating_sub(baseline.disk_read_bytes),
                                current_disk_write.saturating_sub(baseline.disk_write_bytes),
                                option_sub(cur_rchar, baseline.syscall_read_bytes),
                                option_sub(cur_wchar, baseline.syscall_write_bytes),
                                option_sub(cur_minflt, baseline.page_faults_cached),
                                option_sub(cur_majflt, baseline.page_faults_disk),
                                current_net_rx.saturating_sub(baseline.sys_net_rx_bytes),
                                current_net_tx.saturating_sub(baseline.sys_net_tx_bytes),
                            )
                        }
                    }
                };

                let child_ts_ms = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .expect("Time went backwards")
                    .as_millis() as u64;

                // Use different CPU measurement methods based on platform
                #[cfg(target_os = "linux")]
                let cpu_usage = self.cpu_sampler.get_cpu_usage(*child_pid).unwrap_or(0.0);

                #[cfg(not(target_os = "linux"))]
                let cpu_usage = proc.cpu_usage();

                let metrics = Metrics {
                    ts_ms: child_ts_ms,
                    cpu_usage,
                    mem_rss_kb: proc.memory() / 1024,
                    mem_vms_kb: proc.virtual_memory() / 1024,
                    disk_read_bytes,
                    disk_write_bytes,
                    syscall_read_bytes,
                    syscall_write_bytes,
                    page_faults_cached,
                    page_faults_disk,
                    sys_net_rx_bytes,
                    sys_net_tx_bytes,
                    thread_count: get_thread_count(*child_pid),
                    uptime_secs: proc.run_time(),
                    cpu_core: Self::get_process_cpu_core(*child_pid),
                    gpu: None,     // Child processes don't get individual GPU metrics
                    psi_mem: None, // PSI is per-tree, captured on the parent
                    perf: None,    // Per-child perf groups not opened (parent uses inherit=1)
                };

                child_metrics.push(ChildProcessMetrics {
                    pid: *child_pid,
                    command,
                    metrics,
                });
            }
        }

        // Cleanup stale entries in the CPU sampler
        #[cfg(target_os = "linux")]
        {
            let all_pids = std::iter::once(self.pid)
                .chain(child_pids.iter().copied())
                .collect::<Vec<_>>();
            self.cpu_sampler.cleanup_stale_entries(&all_pids);
        }

        // Create aggregated metrics
        let aggregated = if let Some(ref parent) = parent_metrics {
            let mut agg = AggregatedMetrics {
                ts_ms: tree_ts_ms,
                cpu_usage: parent.cpu_usage,
                mem_rss_kb: parent.mem_rss_kb,
                mem_vms_kb: parent.mem_vms_kb,
                disk_read_bytes: parent.disk_read_bytes,
                disk_write_bytes: parent.disk_write_bytes,
                syscall_read_bytes: parent.syscall_read_bytes,
                syscall_write_bytes: parent.syscall_write_bytes,
                page_faults_cached: parent.page_faults_cached,
                page_faults_disk: parent.page_faults_disk,
                sys_net_rx_bytes: parent.sys_net_rx_bytes,
                sys_net_tx_bytes: parent.sys_net_tx_bytes,
                thread_count: parent.thread_count,
                process_count: 1, // Parent
                uptime_secs: parent.uptime_secs,
                ebpf: None, // Will be populated below if eBPF is enabled
                gpu: None,  // Will be populated below if GPU is enabled
                psi_mem: parent.psi_mem,
                // On Linux `perf` is `Option<PerfCounters>` (Copy); on non-Linux
                // it's `Option<serde_json::Value>` (not Copy). `.clone()` is the
                // portable choice; clippy's lint fires only on the Linux build.
                #[cfg_attr(target_os = "linux", allow(clippy::clone_on_copy))]
                perf: parent.perf.clone(),
            };

            // Add child metrics
            for child in &child_metrics {
                agg.cpu_usage += child.metrics.cpu_usage;
                agg.mem_rss_kb += child.metrics.mem_rss_kb;
                agg.mem_vms_kb += child.metrics.mem_vms_kb;
                agg.disk_read_bytes += child.metrics.disk_read_bytes;
                agg.disk_write_bytes += child.metrics.disk_write_bytes;
                if let Some(v) = child.metrics.syscall_read_bytes {
                    agg.syscall_read_bytes = Some(agg.syscall_read_bytes.unwrap_or(0) + v);
                }
                if let Some(v) = child.metrics.syscall_write_bytes {
                    agg.syscall_write_bytes = Some(agg.syscall_write_bytes.unwrap_or(0) + v);
                }
                if let Some(v) = child.metrics.page_faults_cached {
                    agg.page_faults_cached = Some(agg.page_faults_cached.unwrap_or(0) + v);
                }
                if let Some(v) = child.metrics.page_faults_disk {
                    agg.page_faults_disk = Some(agg.page_faults_disk.unwrap_or(0) + v);
                }
                agg.sys_net_rx_bytes += child.metrics.sys_net_rx_bytes;
                agg.sys_net_tx_bytes += child.metrics.sys_net_tx_bytes;
                agg.thread_count += child.metrics.thread_count;
                agg.process_count += 1;
            }

            // Collect eBPF metrics if enabled
            #[cfg(feature = "ebpf")]
            if self.enable_ebpf {
                if let Some(ref mut tracker) = self.ebpf_tracker {
                    // Update PIDs in case the process tree changed
                    let all_pids: Vec<u32> = std::iter::once(self.pid as u32)
                        .chain(child_pids.iter().map(|&pid| pid as u32))
                        .collect();

                    if let Err(e) = tracker.update_pids(all_pids.clone()) {
                        log::warn!("Failed to update eBPF PIDs: {}", e);
                    }

                    // Get eBPF metrics with enhanced analysis
                    let mut ebpf_metrics = tracker.get_metrics();

                    // Add enhanced analysis if we have syscall data
                    #[cfg(feature = "ebpf")]
                    if let Some(ref mut syscalls) = ebpf_metrics.syscalls {
                        let elapsed_time = (tree_ts_ms - self.t0_ms) as f64 / 1000.0;
                        syscalls.analysis = Some(crate::ebpf::metrics::generate_syscall_analysis(
                            syscalls,
                            elapsed_time,
                        ));
                    }

                    // Collect off-CPU profiling data
                    if let Some(ref mut profiler) = self.offcpu_profiler {
                        profiler.update_pids(all_pids.clone());
                        let stats = profiler.get_stats();
                        if !stats.is_empty() {
                            ebpf_metrics.offcpu = Some(build_offcpu_metrics(&stats));
                        }
                    }

                    agg.ebpf = Some(ebpf_metrics);
                }
            }

            #[cfg(not(feature = "ebpf"))]
            {
                // eBPF is already None from initialization
            }

            // Add GPU metrics if enabled
            #[cfg(feature = "gpu")]
            if self.gpu_monitor.is_enabled() {
                let all_pids: Vec<u32> = std::iter::once(self.pid as u32)
                    .chain(child_pids.iter().map(|&pid| pid as u32))
                    .collect();
                agg.gpu = Some(self.gpu_monitor.sample_metrics(&all_pids));
            }

            #[cfg(not(feature = "gpu"))]
            {
                // GPU is already None from initialization
            }

            Some(agg)
        } else {
            None
        };

        ProcessTreeMetrics {
            ts_ms: tree_ts_ms,
            parent: parent_metrics,
            children: child_metrics,
            aggregated,
        }
    }

    // Get network receive bytes for the process
    fn get_process_sys_net_rx_bytes(&self) -> u64 {
        #[cfg(target_os = "linux")]
        {
            self.get_linux_process_net_stats().0
        }
        #[cfg(not(target_os = "linux"))]
        {
            0 // Not implemented for non-Linux platforms yet
        }
    }

    // Get network transmit bytes for the process
    fn get_process_sys_net_tx_bytes(&self) -> u64 {
        #[cfg(target_os = "linux")]
        {
            self.get_linux_process_net_stats().1
        }
        #[cfg(not(target_os = "linux"))]
        {
            0 // Not implemented for non-Linux platforms yet
        }
    }

    #[cfg(target_os = "linux")]
    fn get_linux_process_net_stats(&self) -> (u64, u64) {
        // Parse /proc/[pid]/net/dev if it exists (in network namespaces)
        // Fall back to system-wide /proc/net/dev as approximation

        let net_dev_path = format!("/proc/{}/net/dev", self.pid);
        let net_stats = if std::path::Path::new(&net_dev_path).exists() {
            self.parse_net_dev(&net_dev_path)
        } else {
            // Fall back to system-wide stats
            // This is less accurate but better than nothing
            self.parse_net_dev("/proc/net/dev")
        };

        // Get interface statistics (sum all interfaces except loopback)
        let mut total_rx = 0u64;
        let mut total_tx = 0u64;

        for (interface, (rx, tx)) in net_stats {
            if interface != "lo" {
                // Skip loopback
                total_rx += rx;
                total_tx += tx;
            }
        }

        (total_rx, total_tx)
    }

    #[cfg(target_os = "linux")]
    fn parse_net_dev(&self, path: &str) -> std::collections::HashMap<String, (u64, u64)> {
        let mut stats = std::collections::HashMap::new();

        if let Ok(mut file) = std::fs::File::open(path) {
            let mut contents = String::new();
            if std::io::Read::read_to_string(&mut file, &mut contents).is_ok() {
                for line in contents.lines().skip(2) {
                    // Skip header lines
                    let parts: Vec<&str> = line.split_whitespace().collect();
                    if parts.len() >= 10 {
                        if let Some(interface) = parts[0].strip_suffix(':') {
                            if let (Ok(rx_bytes), Ok(tx_bytes)) =
                                (parts[1].parse::<u64>(), parts[9].parse::<u64>())
                            {
                                stats.insert(interface.to_string(), (rx_bytes, tx_bytes));
                            }
                        }
                    }
                }
            }
        }

        stats
    }

    /// Get the CPU core a process is currently running on (Linux only)
    #[cfg(target_os = "linux")]
    fn get_process_cpu_core(pid: usize) -> Option<u32> {
        // Read /proc/[pid]/stat to get the last CPU the process ran on
        let stat_path = format!("/proc/{pid}/stat");
        if let Ok(contents) = std::fs::read_to_string(&stat_path) {
            // The CPU field is the 39th field in /proc/[pid]/stat
            // Format: pid (comm) state ppid pgrp session tty_nr tpgid flags...
            // We need to handle the command field which can contain spaces and parentheses
            if let Some(last_paren) = contents.rfind(')') {
                let after_comm = &contents[last_paren + 1..];
                let fields: Vec<&str> = after_comm.split_whitespace().collect();
                // CPU is the 37th field after the command (0-indexed)
                if fields.len() > 36 {
                    if let Ok(cpu) = fields[36].parse::<u32>() {
                        return Some(cpu);
                    }
                }
            }
        }
        None
    }

    #[cfg(not(target_os = "linux"))]
    fn get_process_cpu_core(_pid: usize) -> Option<u32> {
        None // Not implemented for non-Linux platforms
    }

    /// Get GPU monitoring summary
    #[cfg(feature = "gpu")]
    pub fn get_gpu_summary(&self) -> crate::gpu::GpuSummary {
        // For a simple summary, we'll just use current metrics
        let current_metrics = self.gpu_monitor.sample_metrics(&[self.pid as u32]);
        self.gpu_monitor.get_summary(&[current_metrics])
    }

    /// Check if GPU monitoring is enabled
    #[cfg(feature = "gpu")]
    pub fn is_gpu_enabled(&self) -> bool {
        self.gpu_monitor.is_enabled()
    }

    /// Get the number of GPU devices
    #[cfg(feature = "gpu")]
    pub fn gpu_device_count(&self) -> u32 {
        self.gpu_monitor.device_count()
    }
}

/// Build `OffCpuMetrics` from the raw per-thread stats map.
#[cfg(feature = "ebpf")]
fn build_offcpu_metrics(
    stats: &std::collections::HashMap<(u32, u32), crate::ebpf::OffCpuStats>,
) -> crate::ebpf::metrics::OffCpuMetrics {
    use crate::ebpf::metrics::{OffCpuMetrics, ThreadOffCpuInfo, ThreadOffCpuStats};

    let mut total_time_ns: u64 = 0;
    let mut total_events: u64 = 0;
    let mut max_time_ns: u64 = 0;
    let mut min_time_ns: u64 = u64::MAX;
    let mut thread_stats = std::collections::HashMap::new();

    for ((pid, tid), s) in stats {
        total_time_ns = total_time_ns.saturating_add(s.total_time_ns);
        total_events = total_events.saturating_add(s.count);
        if s.max_time_ns > max_time_ns {
            max_time_ns = s.max_time_ns;
        }
        if s.min_time_ns > 0 && s.min_time_ns < min_time_ns {
            min_time_ns = s.min_time_ns;
        }
        thread_stats.insert(
            format!("{pid}:{tid}"),
            ThreadOffCpuStats {
                tid: *tid,
                total_time_ns: s.total_time_ns,
                count: s.count,
                avg_time_ns: s.avg_time_ns,
                max_time_ns: s.max_time_ns,
                min_time_ns: s.min_time_ns,
            },
        );
    }

    let avg_time_ns = if total_events > 0 {
        total_time_ns / total_events
    } else {
        0
    };
    let min_time_ns = if min_time_ns == u64::MAX {
        0
    } else {
        min_time_ns
    };

    // Build top-blocking-threads list (sorted by total off-CPU time, descending)
    let mut top_blocking_threads: Vec<ThreadOffCpuInfo> = stats
        .iter()
        .map(|((pid, tid), s)| ThreadOffCpuInfo {
            tid: *tid,
            pid: *pid,
            total_time_ms: s.total_time_ns as f64 / 1_000_000.0,
            percentage: if total_time_ns > 0 {
                s.total_time_ns as f64 / total_time_ns as f64 * 100.0
            } else {
                0.0
            },
        })
        .collect();
    top_blocking_threads.sort_by(|a, b| {
        b.total_time_ms
            .partial_cmp(&a.total_time_ms)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    top_blocking_threads.truncate(10);

    OffCpuMetrics {
        total_time_ns,
        total_events,
        avg_time_ns,
        max_time_ns,
        min_time_ns,
        thread_stats,
        top_blocking_threads,
        bottlenecks: vec![],
        stack_traces: vec![],
        stacks: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::constants::{defaults, delays, sampling};
    use std::thread;

    // Helper function for creating a test monitor with standard parameters
    // Test fixture for process monitoring tests
    struct ProcessTestFixture {
        cmd: Vec<String>,
        base_interval: Duration,
        max_interval: Duration,
        ready_timeout: Duration,
    }

    impl ProcessTestFixture {
        fn new(cmd: Vec<String>) -> Self {
            Self {
                cmd,
                base_interval: defaults::BASE_INTERVAL,
                max_interval: defaults::MAX_INTERVAL,
                ready_timeout: delays::STARTUP,
            }
        }

        fn create_monitor(&self) -> Result<ProcessMonitor, std::io::Error> {
            ProcessMonitor::new(self.cmd.clone(), self.base_interval, self.max_interval)
        }

        fn create_monitor_from_pid(&self, pid: usize) -> Result<ProcessMonitor, std::io::Error> {
            ProcessMonitor::from_pid(pid, self.base_interval, self.max_interval)
        }

        // Create a monitor and wait until the process is reliably detected
        fn create_and_verify_running(&self) -> Result<(ProcessMonitor, usize), std::io::Error> {
            let mut monitor = self.create_monitor()?;
            let pid = monitor.get_pid();

            // Give the process a small amount of time to start
            std::thread::sleep(delays::STANDARD);

            // Verify the process is running using a retry strategy
            if !self.wait_for_condition(|| monitor.is_running()) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "Process did not start or was not detected",
                ));
            }

            Ok((monitor, pid))
        }

        // Utility method for waiting with exponential backoff
        // Wait for a condition to become true with exponential backoff
        // This approach is more reliable than fixed sleeps and handles
        // timing variations in test environments
        fn wait_for_condition<F>(&self, mut condition: F) -> bool
        where
            F: FnMut() -> bool,
        {
            let start = std::time::Instant::now();
            let mut delay_ms = 1;

            while start.elapsed() < self.ready_timeout {
                if condition() {
                    return true;
                }

                // Exponential backoff with a maximum delay
                std::thread::sleep(Duration::from_millis(delay_ms));
                delay_ms = std::cmp::min(delay_ms * 2, 50);
            }

            false
        }
    }

    // Helper function for creating a test monitor
    fn create_test_monitor(cmd: Vec<String>) -> Result<ProcessMonitor, std::io::Error> {
        ProcessTestFixture::new(cmd).create_monitor()
    }

    // This function is intentionally left in place for future reference, but is currently
    // not used directly as the fixture pattern provides better test isolation
    #[allow(dead_code)]
    fn create_test_monitor_from_pid(pid: usize) -> Result<ProcessMonitor, std::io::Error> {
        let fixture = ProcessTestFixture {
            cmd: vec![],
            base_interval: defaults::BASE_INTERVAL,
            max_interval: defaults::MAX_INTERVAL,
            ready_timeout: delays::STARTUP,
        };
        fixture.create_monitor_from_pid(pid)
    }

    // Test attaching to existing process
    #[test]
    fn test_from_pid() {
        // Create a test fixture with a longer-running process
        let cmd = if cfg!(target_os = "windows") {
            vec![
                "powershell".to_string(),
                "-Command".to_string(),
                "Start-Sleep -Seconds 5".to_string(),
            ]
        } else {
            vec!["sleep".to_string(), "5".to_string()]
        };

        let fixture = ProcessTestFixture::new(cmd);

        // Create and verify the direct monitor is running
        let (_, pid) = fixture.create_and_verify_running().unwrap();

        // Create a monitor for the existing process
        let pid_monitor = fixture.create_monitor_from_pid(pid);
        assert!(
            pid_monitor.is_ok(),
            "Should be able to attach to running process"
        );

        let mut pid_monitor = pid_monitor.unwrap();

        // Verify the PID monitor can detect the process
        assert!(
            fixture.wait_for_condition(|| pid_monitor.is_running()),
            "PID monitor should detect the running process"
        );
    }

    #[test]
    fn test_adaptive_interval() {
        let cmd = vec!["sleep".to_string(), "10".to_string()];
        let monitor = create_test_monitor(cmd).unwrap();

        let base_interval = monitor.base_interval;

        // Initial interval should be close to base_interval
        let initial = monitor.adaptive_interval();
        assert!(initial >= base_interval);
        assert!(initial <= base_interval * 2); // Allow for some time passing during test

        // After waiting, interval should increase but not exceed max
        thread::sleep(Duration::from_secs(2));
        let later = monitor.adaptive_interval();
        assert!(later > initial); // Should increase
        assert!(later <= monitor.max_interval); // Should not exceed max
    }

    #[test]
    fn test_is_running() {
        // Test with a short-lived process
        let fixture = ProcessTestFixture::new(vec!["echo".to_string(), "hello".to_string()]);
        let mut monitor = fixture.create_monitor().unwrap();

        // Wait for the process to terminate
        assert!(
            fixture.wait_for_condition(|| !monitor.is_running()),
            "Short-lived process should terminate"
        );

        // Test with a longer running process
        let fixture = ProcessTestFixture {
            cmd: vec!["sleep".to_string(), "2".to_string()], // Increased sleep time for reliability
            base_interval: defaults::BASE_INTERVAL,
            max_interval: defaults::MAX_INTERVAL,
            ready_timeout: Duration::from_secs(5), // Longer timeout for this test
        };
        let (mut monitor, _) = fixture.create_and_verify_running().unwrap();

        // Verify it's running (this is already done by create_and_verify_running, but we're being explicit)
        assert!(monitor.is_running(), "Process should be running initially");

        // Now wait for it to terminate
        assert!(
            fixture.wait_for_condition(|| !monitor.is_running()),
            "Process should terminate within the timeout period"
        );
    }

    #[test]
    fn test_metrics_collection() {
        // Start a simple CPU-bound process
        let cmd = if cfg!(target_os = "windows") {
            vec![
                "powershell".to_string(),
                "-Command".to_string(),
                "Start-Sleep -Seconds 3".to_string(),
            ]
        } else {
            vec!["sleep".to_string(), "3".to_string()]
        };

        let mut monitor = create_test_monitor(cmd).unwrap();

        // Allow more time for the process to start and register uptime
        thread::sleep(delays::STARTUP);

        // Sample metrics
        let metrics = monitor.sample_metrics();
        assert!(
            metrics.is_some(),
            "Should collect metrics from running process"
        );

        if let Some(m) = metrics {
            // Check thread count first
            assert!(
                m.thread_count > 0,
                "Process should have at least one thread"
            );

            // Handle uptime which might be platform-dependent
            if m.uptime_secs == 0 {
                // On some platforms (especially macOS), uptime might not be reliably reported
                // If uptime is 0, wait a bit and check again to see if it increases
                thread::sleep(Duration::from_secs(1));
                if let Some(m2) = monitor.sample_metrics() {
                    // We don't assert here - just log the value to debug
                    println!("Process uptime after delay: {} seconds", m2.uptime_secs);

                    // On macOS, uptime might still be 0 - that's OK
                    #[cfg(target_os = "linux")]
                    {
                        // On Linux specifically, we expect uptime to work reliably
                        assert!(
                            m2.uptime_secs > 0,
                            "Process uptime should increase after delay on Linux"
                        );
                    }
                }
            } else {
                // Uptime is already positive, which is good on any platform
                println!("Process uptime: {} seconds", m.uptime_secs);
            }
        }
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test relies on Linux-specific process detection behavior"
    )]
    fn test_child_process_detection() {
        // Start a process that spawns children
        let cmd = if cfg!(target_os = "windows") {
            vec![
                "cmd".to_string(),
                "/C".to_string(),
                "timeout 2 >nul & echo child".to_string(),
            ]
        } else {
            vec![
                "sh".to_string(),
                "-c".to_string(),
                "sleep 2 & echo child".to_string(),
            ]
        };

        let mut monitor = create_test_monitor(cmd).unwrap();

        // Allow time for child processes to start
        thread::sleep(sampling::SLOW);

        // Get child PIDs
        let children = monitor.get_child_pids();

        // We might not always detect children due to timing, so just verify the method works
        // The assertion here is mainly to document that the method should return a Vec
        assert!(
            children.is_empty() || !children.is_empty(),
            "Should return a list of child PIDs (possibly empty)"
        );
    }

    #[test]
    fn test_tree_metrics_structure() {
        // Test the tree metrics structure with a simple process
        let cmd = vec!["sleep".to_string(), "1".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        // Allow time for process to start
        thread::sleep(sampling::STANDARD);

        // Sample tree metrics
        let tree_metrics = monitor.sample_tree_metrics();

        // Should have parent metrics
        assert!(tree_metrics.parent.is_some(), "Should have parent metrics");

        // Should have aggregated metrics
        assert!(
            tree_metrics.aggregated.is_some(),
            "Should have aggregated metrics"
        );

        #[cfg(not(target_os = "linux"))]
        println!("Note: On non-Linux platforms, some process metrics may be limited");

        if let Some(agg) = tree_metrics.aggregated {
            assert!(
                agg.process_count >= 1,
                "Should count at least the parent process"
            );
            assert!(agg.thread_count > 0, "Should have at least one thread");
        }
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test relies on Linux-specific process aggregation behavior"
    )]
    fn test_child_process_aggregation() {
        // This test is hard to make deterministic since we can't guarantee child processes
        // But we can test the aggregation logic with the structure
        let cmd = vec!["sleep".to_string(), "1".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(100));

        let tree_metrics = monitor.sample_tree_metrics();

        if let (Some(parent), Some(agg)) = (tree_metrics.parent, tree_metrics.aggregated) {
            // Aggregated metrics should include at least the parent
            assert!(
                agg.cpu_usage >= parent.cpu_usage,
                "Aggregated CPU should be >= parent CPU"
            );
            assert!(
                agg.mem_rss_kb >= parent.mem_rss_kb,
                "Aggregated memory should be >= parent memory"
            );
            assert!(
                agg.thread_count >= parent.thread_count,
                "Aggregated threads should be >= parent threads"
            );

            // Process count should be at least 1 (the parent)
            assert!(
                agg.process_count >= 1,
                "Should count at least the parent process"
            );
        }
    }

    #[test]
    fn test_empty_process_tree() {
        // Test behavior when monitoring a process with no children
        let cmd = vec!["sleep".to_string(), "1".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(50));

        let tree_metrics = monitor.sample_tree_metrics();

        // Should have parent metrics
        assert!(
            tree_metrics.parent.is_some(),
            "Should have parent metrics even with no children"
        );

        // Children list might be empty (which is fine)
        // Length is always non-negative, so just verify it's accessible

        // Aggregated should exist and equal parent (since no children)
        if let (Some(parent), Some(agg)) = (tree_metrics.parent, tree_metrics.aggregated) {
            assert_eq!(
                agg.process_count,
                1 + tree_metrics.children.len(),
                "Process count should be parent + actual children"
            );

            if tree_metrics.children.is_empty() {
                // If no children, aggregated should equal parent
                assert_eq!(
                    agg.cpu_usage, parent.cpu_usage,
                    "CPU should match parent when no children"
                );
                assert_eq!(
                    agg.mem_rss_kb, parent.mem_rss_kb,
                    "Memory should match parent when no children"
                );
                assert_eq!(
                    agg.thread_count, parent.thread_count,
                    "Threads should match parent when no children"
                );
            }
        }
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test relies on Linux-specific process tree detection"
    )]
    fn test_recursive_child_detection() {
        // Test that we can find children recursively in a more complex process tree
        let cmd = if cfg!(target_os = "windows") {
            vec![
                "cmd".to_string(),
                "/C".to_string(),
                "timeout 3 >nul & (timeout 2 >nul & timeout 1 >nul)".to_string(),
            ]
        } else {
            vec![
                "sh".to_string(),
                "-c".to_string(),
                "sleep 3 & (sleep 2 & sleep 1 &)".to_string(),
            ]
        };

        let mut monitor = create_test_monitor(cmd).unwrap();

        // Allow time for the process tree to establish
        thread::sleep(Duration::from_millis(300));

        let _children = monitor.get_child_pids();

        // We might detect children (timing dependent), but the method should work
        // Just verify the method returns successfully (length is always valid)

        // Test that repeated calls work
        let _children2 = monitor.get_child_pids();
        // Both calls should succeed and return valid vectors
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test relies on Linux-specific process monitoring behavior"
    )]
    fn test_child_process_lifecycle() {
        // Test monitoring during child process lifecycle changes
        let cmd = if cfg!(target_os = "windows") {
            vec![
                "cmd".to_string(),
                "/C".to_string(),
                "start /b ping 127.0.0.1 -n 3 >nul".to_string(),
            ]
        } else {
            vec![
                "sh".to_string(),
                "-c".to_string(),
                // Create multiple child processes that run long enough to be detected
                "for i in 1 2 3; do sleep $i & done; sleep 0.5; wait".to_string(),
            ]
        };

        let mut monitor = create_test_monitor(cmd).unwrap();

        // Enable child process monitoring explicitly
        monitor.set_include_children(true);

        // First, take multiple initial samples and find the stable baseline
        // (since environment might have background processes that come and go)
        println!("Measuring baseline process count...");
        let mut baseline_samples = Vec::new();
        for i in 0..5 {
            let metrics = monitor.sample_tree_metrics();
            let count = metrics
                .aggregated
                .as_ref()
                .map(|a| a.process_count)
                .unwrap_or(1);
            baseline_samples.push(count);
            println!("Baseline sample {}: process count: {}", i + 1, count);
            thread::sleep(Duration::from_millis(100));
        }

        // Calculate mode (most common value) as our baseline
        let mut counts = std::collections::HashMap::new();
        for &count in &baseline_samples {
            *counts.entry(count).or_insert(0) += 1;
        }
        let baseline_count = counts
            .into_iter()
            .max_by_key(|&(_, count)| count)
            .map(|(val, _)| val)
            .unwrap_or(1);

        println!("Established baseline process count: {}", baseline_count);

        // Now create our command which should spawn child processes
        // Sample multiple times to catch process count changes
        let mut max_count = baseline_count;
        let mut min_count_after_max = usize::MAX;
        let mut saw_increase = false;
        let mut saw_decrease = false;

        println!("Starting sampling to detect process lifecycle...");
        for i in 0..15 {
            thread::sleep(Duration::from_millis(200));

            let metrics = monitor.sample_tree_metrics();
            let count = metrics
                .aggregated
                .as_ref()
                .map(|a| a.process_count)
                .unwrap_or(1);

            println!("Sample {}: process count: {}", i + 1, count);

            // If we see an increase from baseline, note it
            if count > baseline_count && !saw_increase {
                saw_increase = true;
                println!(
                    "Detected process count increase: {} -> {}",
                    baseline_count, count
                );
            }

            // Update maximum count observed
            if count > max_count {
                max_count = count;
            }

            // If we've seen an increase and now count is decreasing, note it
            if saw_increase && count < max_count {
                saw_decrease = true;
                min_count_after_max = min_count_after_max.min(count);
                println!(
                    "Detected process count decrease: {} -> {}",
                    max_count, count
                );
            }
        }

        // Final sample after waiting for processes to finish
        thread::sleep(Duration::from_millis(1000));

        let final_metrics = monitor.sample_tree_metrics();
        let final_count = final_metrics
            .aggregated
            .as_ref()
            .map(|a| a.process_count)
            .unwrap_or(1);

        println!("Final process count: {}", final_count);
        println!(
            "Test summary: baseline={}, max={}, min_after_max={}, final={}",
            baseline_count, max_count, min_count_after_max, final_count
        );

        // Assert proper functioning
        if saw_increase {
            println!("✓ Successfully detected process count increase");
        } else {
            println!("âš  Did not detect any process count increase");
        }

        if saw_decrease {
            println!("✓ Successfully detected process count decrease");
        } else {
            println!("âš  Did not detect any process count decrease");
        }

        // Make a loose assertion - the test mainly provides diagnostic output
        // We don't want it to fail in CI with timing differences
        assert!(
            max_count >= baseline_count,
            "Process monitoring should detect at least the baseline count"
        );

        // All samples should have valid structure
        assert!(
            final_metrics.aggregated.is_some(),
            "Final aggregated metrics should exist"
        );

        // Note: This test is designed for Linux process monitoring.
        // On other platforms, we may not detect child processes in the same way.
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test relies on Linux-specific network I/O monitoring behavior"
    )]
    fn test_network_io_limitation_for_children() {
        // Test that the current limitation of network I/O for children is handled properly
        let cmd = if cfg!(target_os = "windows") {
            vec![
                "cmd".to_string(),
                "/C".to_string(),
                "timeout 1 >nul & echo test".to_string(),
            ]
        } else {
            vec![
                "sh".to_string(),
                "-c".to_string(),
                "sleep 1 & echo test".to_string(),
            ]
        };

        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(200));

        let tree_metrics = monitor.sample_tree_metrics();

        // Check that all children have 0 network I/O (current limitation)
        for child in &tree_metrics.children {
            assert_eq!(
                child.metrics.sys_net_rx_bytes, 0,
                "Child network RX should be 0 (known limitation)"
            );
            assert_eq!(
                child.metrics.sys_net_tx_bytes, 0,
                "Child network TX should be 0 (known limitation)"
            );
        }

        // Parent might have network I/O, children should not
        if let Some(parent) = tree_metrics.parent {
            // Parent could have network activity, that's fine
            if let Some(agg) = tree_metrics.aggregated {
                // Aggregated network should equal parent network (since children are 0)
                assert_eq!(
                    agg.sys_net_rx_bytes, parent.sys_net_rx_bytes,
                    "Aggregated network RX should equal parent (children are 0)"
                );
                assert_eq!(
                    agg.sys_net_tx_bytes, parent.sys_net_tx_bytes,
                    "Aggregated network TX should equal parent (children are 0)"
                );
            }
        }
    }

    #[test]
    fn test_aggregation_arithmetic() {
        // Test that aggregation arithmetic is correct when we have known values
        let cmd = vec!["sleep".to_string(), "2".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(100));

        let tree_metrics = monitor.sample_tree_metrics();

        if let (Some(parent), Some(agg)) = (tree_metrics.parent, tree_metrics.aggregated) {
            // Calculate expected values
            let expected_mem = parent.mem_rss_kb
                + tree_metrics
                    .children
                    .iter()
                    .map(|c| c.metrics.mem_rss_kb)
                    .sum::<u64>();
            let expected_threads = parent.thread_count
                + tree_metrics
                    .children
                    .iter()
                    .map(|c| c.metrics.thread_count)
                    .sum::<usize>();
            let expected_cpu = parent.cpu_usage
                + tree_metrics
                    .children
                    .iter()
                    .map(|c| c.metrics.cpu_usage)
                    .sum::<f32>();
            let expected_processes = 1 + tree_metrics.children.len();

            assert_eq!(
                agg.mem_rss_kb, expected_mem,
                "Memory aggregation should sum parent + children"
            );
            assert_eq!(
                agg.thread_count, expected_threads,
                "Thread aggregation should sum parent + children"
            );
            assert_eq!(
                agg.process_count, expected_processes,
                "Process count should be parent + children"
            );

            // CPU might have floating point precision issues, use approximate equality
            assert!(
                (agg.cpu_usage - expected_cpu).abs() < 0.01,
                "CPU aggregation should approximately sum parent + children"
            );
        }
    }

    #[test]
    fn test_timestamp_functionality() {
        use std::thread;
        use std::time::{SystemTime, UNIX_EPOCH};

        let cmd = vec!["sleep".to_string(), "2".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(100));

        // Collect multiple samples
        let sample1 = monitor.sample_metrics().unwrap();
        thread::sleep(Duration::from_millis(50));
        let sample2 = monitor.sample_metrics().unwrap();

        // Verify timestamps are reasonable (within last minute)
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        assert!(
            sample1.ts_ms <= now_ms,
            "Sample1 timestamp should not be in future"
        );
        assert!(
            sample2.ts_ms <= now_ms,
            "Sample2 timestamp should not be in future"
        );
        assert!(
            now_ms - sample1.ts_ms < 60000,
            "Sample1 timestamp should be recent"
        );
        assert!(
            now_ms - sample2.ts_ms < 60000,
            "Sample2 timestamp should be recent"
        );

        // Verify timestamps are monotonic
        assert!(
            sample2.ts_ms >= sample1.ts_ms,
            "Timestamps should be monotonic"
        );

        // Test tree metrics timestamps (allow small timing differences)
        let tree_metrics = monitor.sample_tree_metrics();
        let now_ms2 = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        assert!(
            tree_metrics.ts_ms <= now_ms2 + 1000,
            "Tree timestamp should be reasonable"
        );

        if let Some(parent) = tree_metrics.parent {
            assert!(
                parent.ts_ms <= now_ms2 + 1000,
                "Parent timestamp should be reasonable"
            );
        }

        if let Some(agg) = tree_metrics.aggregated {
            assert!(
                agg.ts_ms <= now_ms2 + 1000,
                "Aggregated timestamp should be reasonable"
            );
        }
    }

    #[test]
    fn test_enhanced_memory_metrics() {
        use std::thread;
        use std::time::{SystemTime, UNIX_EPOCH};

        let cmd = vec!["sleep".to_string(), "2".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(200));

        // Try multiple times in case initial memory reporting is delayed
        let mut metrics = monitor.sample_metrics().unwrap();
        for _ in 0..5 {
            if metrics.mem_rss_kb > 0 {
                break;
            }
            thread::sleep(Duration::from_millis(100));
            metrics = monitor.sample_metrics().unwrap();
        }

        // Test that new memory fields exist and are reasonable
        // Note: Memory reporting can be unreliable in test environments
        // Allow for zero values in case of very fast processes or system limitations
        if metrics.mem_rss_kb > 0 && metrics.mem_vms_kb > 0 {
            assert!(
                metrics.mem_vms_kb >= metrics.mem_rss_kb,
                "Virtual memory should be >= RSS when both > 0"
            );
        }

        // At least one memory metric should be available, but allow for system variations
        let has_memory_data = metrics.mem_rss_kb > 0 || metrics.mem_vms_kb > 0;
        if !has_memory_data {
            println!("Warning: No memory data available from sysinfo - this can happen in test environments");
        }

        // Test metadata separately
        let metadata = monitor.get_metadata().unwrap();
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as u64;

        assert!(
            metadata.t0_ms <= now_ms,
            "Start time should not be in future"
        );
        assert!(
            now_ms - metadata.t0_ms < 60000,
            "Start time should be recent (within 60 seconds)"
        );

        // Test tree metrics also have enhanced fields
        let tree_metrics = monitor.sample_tree_metrics();

        if let Some(parent) = tree_metrics.parent {
            assert!(
                parent.mem_vms_kb >= parent.mem_rss_kb,
                "Parent VMS should be >= RSS"
            );
        }

        if let Some(agg) = tree_metrics.aggregated {
            assert!(
                agg.mem_vms_kb >= agg.mem_rss_kb,
                "Aggregated VMS should be >= RSS"
            );
        }
    }

    #[test]
    fn test_get_env_returns_record_for_running_process() {
        // get_env is a one-shot wrapper; just verify it returns a record
        // whose ts_ms is populated and host/kernel are non-empty on Linux.
        let cmd = vec!["sleep".to_string(), "1".to_string()];
        let monitor = create_test_monitor(cmd).unwrap();
        let env = monitor.get_env();
        assert!(env.ts_ms > 0);
        #[cfg(target_os = "linux")]
        {
            assert!(!env.host.is_empty());
            assert!(!env.kernel.is_empty());
        }
    }

    #[test]
    fn test_process_metadata() {
        use std::thread;
        use std::time::{SystemTime, UNIX_EPOCH};

        let cmd = vec!["sleep".to_string(), "2".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        thread::sleep(Duration::from_millis(100));

        // Test metadata collection
        let metadata = monitor.get_metadata().unwrap();

        // Verify basic metadata fields
        assert!(metadata.pid > 0, "PID should be positive");
        assert!(!metadata.cmd.is_empty(), "Command should not be empty");
        assert_eq!(
            metadata.cmd[0], "sleep",
            "First command arg should be 'sleep'"
        );
        assert!(
            !metadata.executable.is_empty(),
            "Executable path should not be empty"
        );

        // Test start time is reasonable
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as u64;

        assert!(
            metadata.t0_ms <= now_ms,
            "Start time should not be in future"
        );
        assert!(
            now_ms - metadata.t0_ms < 60000,
            "Start time should be recent (within 60 seconds)"
        );

        // Test that t0_ms has millisecond precision (not just seconds * 1000)
        // The value should not be a round thousand (which would indicate second precision)
        let remainder = metadata.t0_ms % 1000;
        // Allow some tolerance for processes that might start exactly on second boundaries
        // but most of the time it should have non-zero millisecond component
        println!("t0_ms: {}, remainder: {}", metadata.t0_ms, remainder);

        // Test tree metrics work without embedded metadata
        let tree_metrics = monitor.sample_tree_metrics();
        assert!(
            tree_metrics.parent.is_some(),
            "Tree should have parent metrics"
        );
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test may be flaky on non-Linux platforms due to process timing"
    )]
    fn test_t0_ms_precision() {
        use std::thread;
        use std::time::{SystemTime, UNIX_EPOCH};

        // Capture time before creating monitor
        let before_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as u64;

        // Use a longer sleep to ensure the process stays alive for the test
        let cmd = vec!["sleep".to_string(), "1".to_string()];
        let mut monitor = create_test_monitor(cmd).unwrap();

        // Capture time after creating monitor
        let after_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as u64;

        // Wait a small amount to let process start
        thread::sleep(Duration::from_millis(50));

        // Get metadata - if process has exited (race condition), skip the test
        let metadata = match monitor.get_metadata() {
            Some(md) => md,
            None => {
                println!("Process exited before metadata could be collected, skipping test");
                return;
            }
        };

        // Verify t0_ms is in milliseconds and reasonable
        assert!(
            metadata.t0_ms > 1000000000000,
            "t0_ms should be a reasonable Unix timestamp in milliseconds"
        );
        assert!(
            metadata.t0_ms >= before_ms,
            "t0_ms should be after we started creating the monitor"
        );
        assert!(
            metadata.t0_ms <= after_ms,
            "t0_ms should be before we finished creating the monitor"
        );

        // Test precision by checking that we have millisecond information
        // t0_ms should have millisecond precision, not just seconds * 1000
        let remainder = metadata.t0_ms % 1000;
        println!("t0_ms: {}, remainder: {}", metadata.t0_ms, remainder);

        // The value should be a proper millisecond timestamp
        // Allow some tolerance for timing variations and clock resolution
        assert!(
            metadata.t0_ms <= after_ms + 1000,
            "t0_ms should be close to creation time (within 1 second tolerance)"
        );

        // Verify we have reasonable millisecond precision
        // On some systems, clocks may have lower resolution, so we just verify
        // it's a valid timestamp format
        assert!(
            metadata.t0_ms > 0,
            "t0_ms should be a valid positive timestamp"
        );
    }

    #[test]
    fn test_summary_from_json_file_function() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        // Test with valid aggregated metrics
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(
            temp_file,
            r#"{{"ts_ms":1000,"cpu_usage":25.0,"mem_rss_kb":1024,"mem_vms_kb":2048,"disk_read_bytes":0,"disk_write_bytes":0,"sys_net_rx_bytes":0,"sys_net_tx_bytes":0,"thread_count":2,"process_count":1,"uptime_secs":10,"ebpf":null}}"#
        ).unwrap();
        writeln!(
            temp_file,
            r#"{{"ts_ms":2000,"cpu_usage":50.0,"mem_rss_kb":1536,"mem_vms_kb":3072,"disk_read_bytes":100,"disk_write_bytes":200,"sys_net_rx_bytes":50,"sys_net_tx_bytes":75,"thread_count":3,"process_count":2,"uptime_secs":15,"ebpf":null}}"#
        ).unwrap();
        temp_file.flush().unwrap();

        let summary = summary_from_json_file(temp_file.path()).unwrap();
        assert_eq!(summary.sample_count, 2);
        assert_eq!(summary.total_time_secs, 1.0); // 2000-1000 = 1000ms = 1s
    }

    #[test]
    fn test_summary_from_json_file_with_tree_metrics() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(
            temp_file,
            r#"{{"ts_ms":1000,"parent":null,"children":[],"aggregated":{{"ts_ms":1000,"cpu_usage":30.0,"mem_rss_kb":1024,"mem_vms_kb":2048,"disk_read_bytes":0,"disk_write_bytes":0,"sys_net_rx_bytes":0,"sys_net_tx_bytes":0,"thread_count":1,"process_count":1,"uptime_secs":5,"ebpf":null}}}}"#
        ).unwrap();
        temp_file.flush().unwrap();

        let summary = summary_from_json_file(temp_file.path()).unwrap();
        assert_eq!(summary.sample_count, 1);
        assert_eq!(summary.avg_cpu_usage, 30.0);
    }

    #[test]
    fn test_summary_from_json_file_with_regular_metrics() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(
            temp_file,
            r#"{{"ts_ms":1000,"cpu_usage":40.0,"mem_rss_kb":512,"mem_vms_kb":1024,"disk_read_bytes":0,"disk_write_bytes":0,"sys_net_rx_bytes":0,"sys_net_tx_bytes":0,"thread_count":1,"uptime_secs":8,"cpu_core":null}}"#
        ).unwrap();
        temp_file.flush().unwrap();

        let summary = summary_from_json_file(temp_file.path()).unwrap();
        assert_eq!(summary.sample_count, 1);
        assert_eq!(summary.avg_cpu_usage, 40.0);
    }

    #[test]
    fn test_summary_from_json_file_empty() {
        use tempfile::NamedTempFile;

        let temp_file = NamedTempFile::new().unwrap();
        let summary = summary_from_json_file(temp_file.path()).unwrap();
        assert_eq!(summary.sample_count, 0);
        assert_eq!(summary.total_time_secs, 0.0);
    }

    #[test]
    fn test_summary_from_json_file_with_empty_lines() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file).unwrap(); // Empty line
        writeln!(temp_file, "   ").unwrap(); // Whitespace only
        writeln!(
            temp_file,
            r#"{{"ts_ms":1000,"cpu_usage":35.0,"mem_rss_kb":768,"mem_vms_kb":1536,"disk_read_bytes":0,"disk_write_bytes":0,"sys_net_rx_bytes":0,"sys_net_tx_bytes":0,"thread_count":1,"uptime_secs":12,"cpu_core":null}}"#
        ).unwrap();
        writeln!(temp_file, "invalid json line").unwrap(); // Invalid JSON
        temp_file.flush().unwrap();

        let summary = summary_from_json_file(temp_file.path()).unwrap();
        assert_eq!(summary.sample_count, 1);
        assert_eq!(summary.avg_cpu_usage, 35.0);
    }

    #[test]
    fn test_get_thread_count_functions() {
        let current_pid = std::process::id() as usize;
        let thread_count = get_thread_count(current_pid);
        assert!(thread_count >= 1);

        // Test with invalid PID
        let invalid_thread_count = get_thread_count(999999);
        assert_eq!(invalid_thread_count, DEFAULT_THREAD_COUNT);
    }

    #[test]
    fn test_io_baseline_and_child_io_baseline() {
        let baseline = IoBaseline {
            disk_read_bytes: 100,
            disk_write_bytes: 200,
            syscall_read_bytes: None,
            syscall_write_bytes: None,
            page_faults_cached: None,
            page_faults_disk: None,
            sys_net_rx_bytes: 50,
            sys_net_tx_bytes: 75,
        };

        let child_baseline = ChildIoBaseline {
            pid: 123,
            disk_read_bytes: 300,
            disk_write_bytes: 400,
            syscall_read_bytes: None,
            syscall_write_bytes: None,
            page_faults_cached: None,
            page_faults_disk: None,
            sys_net_rx_bytes: 150,
            sys_net_tx_bytes: 175,
        };

        // Test Clone and Debug traits
        let baseline_clone = baseline.clone();
        let child_baseline_clone = child_baseline.clone();

        assert_eq!(baseline.disk_read_bytes, baseline_clone.disk_read_bytes);
        assert_eq!(child_baseline.pid, child_baseline_clone.pid);

        let debug_str = format!("{:?}", baseline);
        assert!(debug_str.contains("IoBaseline"));

        let _child_debug_str = format!("{:?}", child_baseline);
        assert!(debug_str.contains("IoBaseline"));
    }

    #[test]
    fn test_process_monitor_from_pid() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor =
            ProcessMonitor::from_pid(current_pid, sampling::STANDARD, sampling::MAX_ADAPTIVE)
                .unwrap();

        assert_eq!(monitor.get_pid(), current_pid);
        assert!(monitor.is_running());
        assert!(monitor.child.is_none()); // Should be None when attaching to existing process
    }

    #[test]
    fn test_process_monitor_from_pid_with_options() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor = ProcessMonitor::from_pid_with_options(
            current_pid,
            sampling::STANDARD,
            sampling::MAX_ADAPTIVE,
            true, // since_process_start
        )
        .unwrap();

        assert_eq!(monitor.get_pid(), current_pid);
        assert!(monitor.since_process_start);
        assert!(monitor.is_running());
    }

    #[test]
    fn test_process_monitor_new_with_empty_command() {
        use crate::core::constants::sampling;
        let result = ProcessMonitor::new(vec![], sampling::STANDARD, sampling::MAX_ADAPTIVE);
        assert!(result.is_err());
    }

    #[test]
    fn test_process_monitor_new_with_options_empty_command() {
        use crate::core::constants::sampling;
        let result = ProcessMonitor::new_with_options(
            vec![],
            sampling::STANDARD,
            sampling::MAX_ADAPTIVE,
            false,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_process_monitor_setters() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor = ProcessMonitor::from_pid_with_options(
            current_pid,
            sampling::STANDARD,
            sampling::MAX_ADAPTIVE,
            false,
        )
        .unwrap();

        // Test setters
        monitor.set_include_children(false);
        monitor.set_debug_mode(true);
        let _result = monitor.enable_ebpf();

        // These don't have getters, but we can verify they don't panic
        assert_eq!(monitor.get_pid(), current_pid);
    }

    #[test]
    fn test_process_monitor_invalid_pid() {
        use crate::core::constants::sampling;
        let result = ProcessMonitor::from_pid(
            999999, // Invalid PID
            sampling::STANDARD,
            sampling::MAX_ADAPTIVE,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_process_monitor_sample_metrics_invalid_process() {
        use crate::core::constants::sampling;

        // Create a process that will exit quickly
        let mut monitor =
            ProcessMonitor::new(vec!["true".to_string()], sampling::FAST, sampling::STANDARD)
                .unwrap();

        // Wait for process to exit
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Try to sample metrics from dead process
        let _metrics = monitor.sample_metrics();
        // Should handle gracefully (may return None or valid final metrics)
        // The exact behavior depends on timing, so we just verify it doesn't panic
    }

    #[test]
    fn test_process_monitor_debug_traits() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let monitor =
            ProcessMonitor::from_pid(current_pid, sampling::STANDARD, sampling::MAX_ADAPTIVE)
                .unwrap();

        // Test Debug trait
        let debug_str = format!("{:?}", monitor);
        assert!(debug_str.contains("ProcessMonitor"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_get_linux_thread_count() {
        let current_pid = std::process::id() as usize;
        let thread_count = get_linux_thread_count(current_pid);
        assert!(thread_count.is_some());
        assert!(thread_count.unwrap() >= 1);

        // Test with invalid PID
        let invalid_thread_count = get_linux_thread_count(999999);
        assert!(invalid_thread_count.is_none());
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn test_get_linux_thread_count_non_linux() {
        let current_pid = std::process::id() as usize;
        let thread_count = get_linux_thread_count(current_pid);
        assert!(thread_count.is_none());
    }

    #[test]
    fn test_process_result_type_alias() {
        // Test that ProcessResult works correctly
        let success: ProcessResult<i32> = Ok(42);
        match success {
            Ok(v) => assert_eq!(v, 42),
            Err(_) => panic!("Expected Ok but got Err"),
        }

        let error: ProcessResult<i32> = Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "test error",
        ));
        assert!(error.is_err());
    }

    #[test]
    fn test_constants() {
        assert_eq!(DEFAULT_THREAD_COUNT, 1);
        assert_eq!(LINUX_PROC_DIR, "/proc");
        assert_eq!(LINUX_TASK_SUBDIR, "/task");
    }

    #[test]
    fn test_summary_from_json_file_nonexistent() {
        let result = summary_from_json_file("/nonexistent/path/file.json");
        assert!(result.is_err());
    }

    #[test]
    fn test_process_monitor_with_short_lived_process() {
        use crate::core::constants::sampling;

        // Create a process that runs briefly (sleep for 0.1 seconds)
        let mut monitor = ProcessMonitor::new(
            vec!["sleep".to_string(), "0.1".to_string()],
            sampling::FAST,
            sampling::STANDARD,
        )
        .unwrap();

        // Give the process a moment to start
        std::thread::sleep(std::time::Duration::from_millis(20));

        // Process should be running initially
        let _initial_state = monitor.is_running();
        // May or may not be running depending on system timing, but shouldn't panic

        // Wait for process to complete
        std::thread::sleep(std::time::Duration::from_millis(150));

        // Process should have exited by now
        let _still_running = monitor.is_running();
        // May or may not be running depending on timing, but shouldn't panic

        // Try to get final metrics
        let _final_metrics = monitor.sample_metrics();
        // Should handle gracefully regardless of process state

        // Just ensure we don't crash - timing is unpredictable in CI environments
    }

    #[test]
    fn test_get_include_children_functionality() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor = ProcessMonitor::from_pid_with_options(
            current_pid,
            sampling::STANDARD,
            sampling::MAX_ADAPTIVE,
            false,
        )
        .unwrap();

        // Test default value (should be true by default)
        assert!(monitor.get_include_children());

        // Test setter and getter
        monitor.set_include_children(true);
        assert!(monitor.get_include_children());

        monitor.set_include_children(false);
        assert!(!monitor.get_include_children());
    }

    #[test]
    fn test_debug_logging_functionality() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor = ProcessMonitor::from_pid_with_options(
            current_pid,
            sampling::STANDARD,
            sampling::MAX_ADAPTIVE,
            false,
        )
        .unwrap();

        // Test debug mode setting
        monitor.set_debug_mode(false);
        monitor.set_debug_mode(true);

        // This should execute the debug logging paths
        let _result = monitor.enable_ebpf();
        // Should handle gracefully regardless of eBPF support
    }

    #[test]
    fn test_process_attachment_scenarios() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        // Test attaching to current process
        let mut monitor =
            ProcessMonitor::from_pid(current_pid, sampling::FAST, sampling::STANDARD).unwrap();

        // This should exercise the existing process branch in is_running()
        assert!(monitor.is_running());

        // Test multiple is_running calls to exercise different code paths
        assert!(monitor.is_running());
        assert!(monitor.is_running());

        // Test sampling metrics from attached process
        let _metrics = monitor.sample_metrics();
    }

    #[test]
    fn test_summary_from_json_file_regular_metrics() {
        use std::fs::File;
        use std::io::Write;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let file_path = dir.path().join("regular_metrics.json");

        // Create a file with regular metrics (not tree metrics)
        let mut file = File::create(&file_path).unwrap();
        writeln!(
            file,
            r#"{{"ts_ms":1000000,"cpu_usage":50.0,"mem_rss_kb":102400,"mem_vms_kb":204800,"disk_read_bytes":0,"disk_write_bytes":0,"sys_net_rx_bytes":0,"sys_net_tx_bytes":0,"thread_count":1,"uptime_secs":10,"cpu_core":0}}"#
        ).unwrap();
        writeln!(
            file,
            r#"{{"ts_ms":1005000,"cpu_usage":60.0,"mem_rss_kb":112640,"mem_vms_kb":225280,"disk_read_bytes":100,"disk_write_bytes":200,"sys_net_rx_bytes":50,"sys_net_tx_bytes":75,"thread_count":2,"uptime_secs":15,"cpu_core":1}}"#
        ).unwrap();

        let summary = summary_from_json_file(&file_path).unwrap();
        assert!(summary.total_time_secs >= 5.0); // Should be at least 5 seconds
        assert!(summary.sample_count > 0);
        // Note: peak_mem_rss_kb might be 0 depending on how Summary::from_metrics works
    }

    #[test]
    fn test_adaptive_interval_edge_cases() {
        use crate::core::constants::sampling;
        let mut monitor = ProcessMonitor::new(
            vec!["echo".to_string(), "test".to_string()],
            sampling::FAST,
            sampling::STANDARD,
        )
        .unwrap();

        // Test adaptive interval calculation
        let interval1 = monitor.adaptive_interval();
        assert!(interval1.as_millis() > 0);

        // Simulate time passage by updating start_time to test different branches
        monitor.start_time = std::time::Instant::now() - std::time::Duration::from_secs(15);
        let interval2 = monitor.adaptive_interval();
        assert!(interval2.as_millis() > 0);

        // Test with very long elapsed time (should use max interval)
        monitor.start_time = std::time::Instant::now() - std::time::Duration::from_secs(100);
        let interval3 = monitor.adaptive_interval();
        assert_eq!(interval3, sampling::STANDARD);
    }

    #[test]
    fn test_process_metadata_edge_cases() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor =
            ProcessMonitor::from_pid(current_pid, sampling::STANDARD, sampling::MAX_ADAPTIVE)
                .unwrap();

        // Test metadata collection
        let metadata = monitor.get_metadata();
        assert!(metadata.is_some());

        if let Some(meta) = metadata {
            assert!(meta.pid > 0);
            assert!(!meta.cmd.is_empty());
            assert!(!meta.executable.is_empty());
        }
    }

    #[test]
    fn test_tree_metrics_collection_edge_cases() {
        use crate::core::constants::sampling;
        let mut monitor = ProcessMonitor::new(
            vec!["sleep".to_string(), "0.1".to_string()],
            sampling::FAST,
            sampling::STANDARD,
        )
        .unwrap();

        monitor.set_include_children(true);

        // Wait for process to start
        std::thread::sleep(std::time::Duration::from_millis(50));

        // Sample tree metrics - this should exercise various edge cases
        let _tree_metrics = monitor.sample_tree_metrics();

        // Test with process that might have exited
        std::thread::sleep(std::time::Duration::from_millis(200));
        let _tree_metrics2 = monitor.sample_tree_metrics();
    }

    #[test]
    #[cfg_attr(
        not(target_os = "linux"),
        ignore = "This test relies on Linux-specific process discovery behavior"
    )]
    fn test_child_process_discovery() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let mut monitor =
            ProcessMonitor::from_pid(current_pid, sampling::STANDARD, sampling::MAX_ADAPTIVE)
                .unwrap();

        // Test child PID discovery
        let child_pids = monitor.get_child_pids();
        // Current process might not have children, but function should not panic
        // Just verify we get a valid vector
        assert!(child_pids.is_empty() || !child_pids.is_empty());
    }

    #[test]
    fn test_network_io_functions() {
        use crate::core::constants::sampling;
        let current_pid = std::process::id() as usize;

        let monitor =
            ProcessMonitor::from_pid(current_pid, sampling::STANDARD, sampling::MAX_ADAPTIVE)
                .unwrap();

        // Test network I/O measurement functions
        let _rx_bytes = monitor.get_process_sys_net_rx_bytes();
        let _tx_bytes = monitor.get_process_sys_net_tx_bytes();

        // These functions should handle cases gracefully
        let _rx_bytes_again = monitor.get_process_sys_net_rx_bytes();
        let _tx_bytes_again = monitor.get_process_sys_net_tx_bytes();
    }

    #[test]
    fn test_process_monitor_comprehensive_functionality() {
        use crate::core::constants::sampling;

        // Test creating monitor with various options
        let mut monitor = ProcessMonitor::new_with_options(
            vec!["echo".to_string(), "comprehensive_test".to_string()],
            sampling::FAST,
            sampling::STANDARD,
            true, // since_process_start
        )
        .unwrap();

        // Test all setter functions
        monitor.set_include_children(true);
        monitor.set_debug_mode(true);
        let _ebpf_result = monitor.enable_ebpf();

        // Test getter functions
        assert!(monitor.get_include_children());
        let pid = monitor.get_pid();
        assert!(pid > 0);

        // Wait for process to potentially start
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Test monitoring functions
        let _is_running = monitor.is_running();
        let _metrics = monitor.sample_metrics();
        let _tree_metrics = monitor.sample_tree_metrics();
        let _child_pids = monitor.get_child_pids();
        let _metadata = monitor.get_metadata();

        // Test adaptive interval
        let _interval = monitor.adaptive_interval();
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_is_running_pid_monitor_after_process_exits() {
        // Exercise the fallback refresh path in is_running(): a pid-based
        // monitor (self.child == None) calls is_running() after the process
        // has exited.
        //
        // sysinfo's targeted refresh (remove_dead_processes = false) keeps
        // stale cache entries, so we must first flush them by calling
        // get_child_pids(), which uses ProcessesToUpdate::All with
        // remove_dead_processes = true.  After that flush, the targeted
        // refresh in is_running() finds nothing and enters the full-tree
        // ProcessesToUpdate::All fallback branch.
        let mut child = std::process::Command::new("sleep")
            .arg("10")
            .spawn()
            .expect("failed to spawn sleep");
        let pid = child.id() as usize;

        let mut monitor =
            ProcessMonitor::from_pid(pid, Duration::from_millis(100), Duration::from_millis(500))
                .expect("failed to create pid-based monitor");

        let _ = child.kill();
        let _ = child.wait();
        std::thread::sleep(Duration::from_millis(50));

        // Flush the stale sysinfo entry: get_child_pids() does an All refresh
        // with remove_dead_processes = true, which removes the dead pid.
        let _ = monitor.get_child_pids();

        // Now the targeted refresh in is_running() finds no entry and hits
        // the ProcessesToUpdate::All fallback.
        assert!(
            !monitor.is_running(),
            "pid-based monitor must report process as not running after exit"
        );
    }
}