sysprims-proc 0.3.0

Process inspection and enumeration utilities
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
//! sysprims-proc: Process inspection and enumeration utilities
//!
//! This crate provides cross-platform process inspection capabilities with a stable
//! JSON schema for automation. It supports listing all processes, filtering by various
//! criteria, and getting details for a specific PID.
//!
//! ## Features
//!
//! - **Process enumeration**: List all running processes
//! - **Process inspection**: Get details for a single process by PID
//! - **Filtering**: Filter by name, state, CPU, memory, user
//! - **Stable JSON output**: Schema-versioned output for automation
//!
//! ## Platform Support
//!
//! | Feature | Linux | macOS | Windows |
//! |---------|-------|-------|---------|
//! | PID enumeration | /proc | proc_listpids | Toolhelp32 |
//! | Process info | /proc/[pid]/* | proc_pidinfo | OpenProcess |
//! | CPU usage | /proc/[pid]/stat | proc_pidinfo | GetProcessTimes |
//! | Memory usage | /proc/[pid]/statm | proc_pidinfo | GetProcessMemoryInfo |
//!
//! ## Examples
//!
//! ```rust,no_run
//! use sysprims_proc::{snapshot, get_process, ProcessFilter};
//!
//! // Get all processes
//! let snap = snapshot().unwrap();
//! println!("Found {} processes", snap.processes.len());
//!
//! // Get current process
//! let self_info = get_process(std::process::id()).unwrap();
//! println!("Current process: {} (PID {})", self_info.name, self_info.pid);
//!
//! // Filter processes by name
//! let filter = ProcessFilter {
//!     name_contains: Some("rust".into()),
//!     ..Default::default()
//! };
//! let filtered = sysprims_proc::snapshot_filtered(&filter).unwrap();
//! ```

use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use sysprims_core::schema::{
    ANCESTORS_RESULT_V1, DESCENDANTS_RESULT_SAMPLED_V1, DESCENDANTS_RESULT_V1, FD_SNAPSHOT_V1,
    GUARD_EVENT_V1, PORT_BINDINGS_V1, PORT_FILTER_V1, PROCESS_INFO_SAMPLED_V1, PROCESS_INFO_V1,
    WAIT_PID_RESULT_V1,
};
use sysprims_core::time::now_rfc3339;
use sysprims_core::{get_platform, guard_signals, time, SysprimsError, SysprimsResult};

// Platform-specific implementations
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;

// Re-export the platform implementation
#[cfg(target_os = "linux")]
use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
#[cfg(windows)]
use windows as platform;

// ============================================================================
// Core Types
// ============================================================================

/// Snapshot of all processes at a point in time.
///
/// Contains a list of process information with a timestamp and schema identifier.
#[derive(Debug, Clone, Serialize)]
pub struct ProcessSnapshot {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,

    /// Timestamp of snapshot (ISO 8601).
    pub timestamp: String,

    /// List of processes.
    pub processes: Vec<ProcessInfo>,
}

/// Result of waiting for a PID to exit.
///
/// Best-effort cross-platform semantics:
/// - On Unix, this uses a polling strategy (we are not necessarily the parent).
/// - On Windows, this uses process wait APIs when available.
#[derive(Debug, Clone, Serialize)]
pub struct WaitPidResult {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,

    /// Timestamp of result creation (ISO 8601).
    pub timestamp: String,

    /// Current platform (e.g., "linux", "macos", "windows").
    pub platform: &'static str,

    /// PID waited on.
    pub pid: u32,

    /// True if the process was observed to have exited.
    pub exited: bool,

    /// True if the wait timed out before exit was observed.
    pub timed_out: bool,

    /// Exit code when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,

    /// Warnings about degraded visibility.
    pub warnings: Vec<String>,
}

/// Snapshot of listening ports at a point in time.
#[derive(Debug, Clone, Serialize)]
pub struct PortBindingsSnapshot {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,

    /// Timestamp of snapshot (ISO 8601).
    pub timestamp: String,

    /// Current platform (e.g., "linux", "macos", "windows").
    pub platform: &'static str,

    /// List of socket bindings.
    pub bindings: Vec<PortBinding>,

    /// Warnings about partial visibility or skipped entries.
    pub warnings: Vec<String>,
}

/// Listening socket binding information.
#[derive(Debug, Clone, Serialize)]
pub struct PortBinding {
    /// Protocol for the socket.
    pub protocol: Protocol,

    /// Local address (None if unknown).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_addr: Option<IpAddr>,

    /// Local port for the socket.
    pub local_port: u16,

    /// Socket state (e.g., "listen" for TCP).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,

    /// Owning process ID (None if attribution not available).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,

    /// Owning process info (best-effort).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub process: Option<ProcessInfo>,

    /// Socket inode when available (Linux-only).
    #[serde(skip)]
    pub inode: Option<u64>,
}

/// Protocol for a socket binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Protocol {
    Tcp,
    Udp,
}

/// Filter for port queries.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortFilter {
    /// Filter by protocol (tcp/udp).
    pub protocol: Option<Protocol>,

    /// Filter by local port.
    pub local_port: Option<u16>,
}

/// File descriptor kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FdKind {
    File,
    Socket,
    Pipe,
    Unknown,
}

/// Filter for fd queries.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FdFilter {
    /// Filter by fd kind.
    pub kind: Option<FdKind>,
}

impl FdFilter {
    pub fn validate(&self) -> SysprimsResult<()> {
        // No numeric ranges for now.
        Ok(())
    }
}

/// Information about a single file descriptor.
#[derive(Debug, Clone, Serialize)]
pub struct FdInfo {
    /// File descriptor number.
    pub fd: u32,

    /// Best-effort fd classification.
    pub kind: FdKind,

    /// Best-effort resolved path/target.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

/// Snapshot of open file descriptors for a process.
#[derive(Debug, Clone, Serialize)]
pub struct FdSnapshot {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,

    /// Timestamp of snapshot (ISO 8601).
    pub timestamp: String,

    /// Current platform (e.g., "linux", "macos", "windows").
    pub platform: &'static str,

    /// Target PID.
    pub pid: u32,

    /// List of open file descriptors.
    pub fds: Vec<FdInfo>,

    /// Warnings about partial visibility.
    pub warnings: Vec<String>,
}

/// Options controlling optional process detail collection.
///
/// These options are additive and opt-in. Existing APIs default to both values
/// disabled to avoid extra syscall/parse overhead.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProcessOptions {
    /// Include environment variables in `ProcessInfo.env`.
    ///
    /// Platform notes:
    /// - Linux/macOS: best-effort for visible processes.
    /// - Windows: currently unsupported in v0.1.14 (`env` remains `None`).
    pub include_env: bool,

    /// Include thread count in `ProcessInfo.thread_count`.
    pub include_threads: bool,
}

impl ProcessOptions {
    /// Enable environment variable collection.
    pub fn with_env(mut self) -> Self {
        self.include_env = true;
        self
    }

    /// Enable thread count collection.
    pub fn with_threads(mut self) -> Self {
        self.include_threads = true;
        self
    }
}

/// Safety caps for environment collection when proc_ext is enabled.
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_ENTRIES: usize = 1024;
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_KEY_BYTES: usize = 1024;
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_VALUE_BYTES: usize = 4096;
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_TOTAL_BYTES: usize = 1_048_576;

/// Information about a single process.
///
/// All fields are populated on a best-effort basis. Fields that cannot be read
/// (e.g., due to permissions) are set to default values or `None`.
#[derive(Debug, Clone, Serialize)]
pub struct ProcessInfo {
    /// Process ID.
    pub pid: u32,

    /// Parent process ID.
    pub ppid: u32,

    /// Process name (executable name, max 255 chars).
    pub name: String,

    /// Owner username (None if unavailable due to permissions).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,

    /// CPU usage normalized 0-100 across all cores.
    ///
    /// Note: This is an instantaneous value and may be 0 for short-lived
    /// processes or processes that were just started.
    pub cpu_percent: f64,

    /// Memory usage in kilobytes.
    pub memory_kb: u64,

    /// Seconds since process start.
    pub elapsed_seconds: u64,

    /// Process start time (Unix epoch milliseconds), when available.
    ///
    /// Best-effort: omitted if the platform cannot provide it or access is denied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time_unix_ms: Option<u64>,

    /// Executable path (absolute), when available.
    ///
    /// Best-effort: omitted if the platform cannot provide it or access is denied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exe_path: Option<String>,

    /// Process state.
    pub state: ProcessState,

    /// Command line arguments.
    ///
    /// May be empty if command line cannot be read (permissions, zombie process).
    pub cmdline: Vec<String>,

    /// Process environment variables (best-effort, opt-in via `ProcessOptions`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<BTreeMap<String, String>>,

    /// Thread count (best-effort, opt-in via `ProcessOptions`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_count: Option<u32>,
}

/// Process state.
///
/// Maps platform-specific states to a common enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessState {
    /// Process is running or runnable.
    Running,
    /// Process is sleeping (interruptible or uninterruptible).
    Sleeping,
    /// Process is stopped (e.g., by a signal).
    Stopped,
    /// Process is a zombie (terminated but not reaped).
    Zombie,
    /// Process state could not be determined.
    Unknown,
}

/// Liveness classification of a PID.
///
/// Internal to the crate; the public surface is the [`is_live`] / [`is_fully_gone`]
/// predicates. Kept as a three-state enum so a zombie is distinguishable from a
/// fully-reaped process on platforms where that distinction is observable.
///
/// `Zombie` has no analogue on Windows (a PID is either live or gone), so the
/// Windows probe never constructs it; `allow(dead_code)` there keeps the shared
/// enum intact without tripping `-D warnings`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(windows, allow(dead_code))]
pub(crate) enum Liveness {
    /// The process exists and is in a live (non-zombie) state.
    Live,
    /// The process has exited but has not yet been reaped (Unix zombie).
    Zombie,
    /// No process record exists for the PID (never existed, or fully reaped).
    Gone,
}

/// Filter for process queries.
///
/// All fields are optional. Processes must match ALL specified criteria (AND logic).
/// Unknown fields in JSON input will result in `InvalidArgument` error.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessFilter {
    /// Filter by process name substring (case-insensitive).
    pub name_contains: Option<String>,

    /// Filter by exact process name (case-sensitive).
    pub name_equals: Option<String>,

    /// Filter by owner username (exact match).
    pub user_equals: Option<String>,

    /// Filter to specific PIDs.
    pub pid_in: Option<Vec<u32>>,

    /// Filter by parent PID.
    pub ppid: Option<u32>,

    /// Filter by process state.
    pub state_in: Option<Vec<ProcessState>>,

    /// Filter by minimum CPU usage (0-100).
    pub cpu_above: Option<f64>,

    /// Filter by minimum memory usage in KB.
    pub memory_above_kb: Option<u64>,

    /// Filter by minimum process age in seconds.
    ///
    /// Uses `elapsed_seconds` (best-effort, already cross-platform).
    pub running_for_at_least_secs: Option<u64>,
}

impl ProcessFilter {
    /// Validate filter values.
    ///
    /// Returns an error if any values are out of range.
    pub fn validate(&self) -> SysprimsResult<()> {
        if let Some(cpu) = self.cpu_above {
            if !(0.0..=100.0).contains(&cpu) {
                return Err(SysprimsError::invalid_argument(
                    "cpu_above must be between 0 and 100",
                ));
            }
        }
        Ok(())
    }
}

fn validate_process_options(options: &ProcessOptions) -> SysprimsResult<()> {
    #[cfg(feature = "proc_ext")]
    {
        let _ = options;
    }

    #[cfg(not(feature = "proc_ext"))]
    {
        if options.include_env || options.include_threads {
            return Err(SysprimsError::invalid_argument(
                "include_env/include_threads require the proc_ext feature",
            ));
        }
    }

    Ok(())
}

impl PortFilter {
    /// Validate filter values.
    pub fn validate(&self) -> SysprimsResult<()> {
        if let Some(port) = self.local_port {
            if port == 0 {
                return Err(SysprimsError::invalid_argument(
                    "local_port must be between 1 and 65535",
                ));
            }
        }
        Ok(())
    }

    pub fn schema_id() -> &'static str {
        PORT_FILTER_V1
    }
}

impl FdInfo {
    fn matches(&self, filter: &FdFilter) -> bool {
        if let Some(kind) = filter.kind {
            if self.kind != kind {
                return false;
            }
        }

        true
    }
}

impl PortBinding {
    fn matches(&self, filter: &PortFilter) -> bool {
        if let Some(protocol) = filter.protocol {
            if self.protocol != protocol {
                return false;
            }
        }

        if let Some(port) = filter.local_port {
            if self.local_port != port {
                return false;
            }
        }

        true
    }
}

impl ProcessFilter {
    /// Check if a process matches this filter.
    fn matches(&self, proc: &ProcessInfo) -> bool {
        // Name contains (case-insensitive)
        if let Some(ref pattern) = self.name_contains {
            if !proc.name.to_lowercase().contains(&pattern.to_lowercase()) {
                return false;
            }
        }

        // Name equals (exact)
        if let Some(ref name) = self.name_equals {
            if proc.name != *name {
                return false;
            }
        }

        // User equals
        if let Some(ref user) = self.user_equals {
            match &proc.user {
                Some(proc_user) if proc_user == user => {}
                _ => return false,
            }
        }

        // PID in list
        if let Some(ref pids) = self.pid_in {
            if !pids.contains(&proc.pid) {
                return false;
            }
        }

        // Parent PID
        if let Some(ppid) = self.ppid {
            if proc.ppid != ppid {
                return false;
            }
        }

        // State in list
        if let Some(ref states) = self.state_in {
            if !states.contains(&proc.state) {
                return false;
            }
        }

        // CPU above threshold
        if let Some(threshold) = self.cpu_above {
            if proc.cpu_percent < threshold {
                return false;
            }
        }

        // Memory above threshold
        if let Some(threshold) = self.memory_above_kb {
            if proc.memory_kb < threshold {
                return false;
            }
        }

        // Process age (minimum elapsed seconds)
        if let Some(min_secs) = self.running_for_at_least_secs {
            if proc.elapsed_seconds < min_secs {
                return false;
            }
        }

        true
    }
}

// ============================================================================
// Public API
// ============================================================================

/// Get a snapshot of all processes.
///
/// Returns a list of all processes visible to the current user. Processes that
/// cannot be read (e.g., due to permissions) are silently skipped.
///
/// # Examples
///
/// ```rust,no_run
/// // Replaces: ps -eo pid,comm
/// let snap = sysprims_proc::snapshot().unwrap();
/// for proc in &snap.processes {
///     println!("{}: {}", proc.pid, proc.name);
/// }
/// ```
pub fn snapshot() -> SysprimsResult<ProcessSnapshot> {
    snapshot_with_options(ProcessOptions::default())
}

/// Get a snapshot of all processes with optional extended fields.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::ProcessOptions;
///
/// // Replaces: ps -M -p <pid> plus line counting
/// let snap = sysprims_proc::snapshot_with_options(ProcessOptions::default().with_threads()).unwrap();
/// println!("{} processes", snap.processes.len());
/// ```
pub fn snapshot_with_options(options: ProcessOptions) -> SysprimsResult<ProcessSnapshot> {
    validate_process_options(&options)?;
    platform::snapshot_impl(&options)
}

/// Get total CPU time consumed by a process (kernel + user) in nanoseconds.
///
/// This is a best-effort value used for sampling-based CPU calculations.
///
/// Notes:
/// - The existing `ProcessInfo.cpu_percent` is a lifetime-average estimate.
/// - For near-instant CPU usage, callers should sample this value twice and
///   compute a rate over an interval.
///
/// # Examples
///
/// ```rust,no_run
/// let pid = std::process::id();
/// // Replaces: parsing top/ps CPU time columns
/// let total_ns = sysprims_proc::cpu_total_time_ns(pid).unwrap();
/// println!("cpu total ns: {}", total_ns);
/// ```
pub fn cpu_total_time_ns(pid: u32) -> SysprimsResult<u64> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }
    platform::cpu_total_time_ns_impl(pid)
}

/// Get a snapshot of listening ports.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::{listening_ports, PortFilter, Protocol};
///
/// // Replaces: lsof -nP -iTCP -sTCP:LISTEN
/// let filter = PortFilter {
///     protocol: Some(Protocol::Tcp),
///     local_port: Some(8080),
/// };
/// let snap = listening_ports(Some(&filter)).unwrap();
/// println!("bindings: {}", snap.bindings.len());
/// ```
pub fn listening_ports(filter: Option<&PortFilter>) -> SysprimsResult<PortBindingsSnapshot> {
    let filter = filter.cloned().unwrap_or_default();
    filter.validate()?;

    let mut snapshot = platform::listening_ports_impl()?;
    if filter.protocol.is_some() || filter.local_port.is_some() {
        snapshot.bindings.retain(|binding| binding.matches(&filter));
    }

    if snapshot.bindings.is_empty() && snapshot.warnings.is_empty() {
        let platform = get_platform();
        return Err(SysprimsError::not_supported("port bindings", platform));
    }

    Ok(snapshot)
}

/// List open file descriptors for a PID.
///
/// Best-effort cross-platform behavior:
/// - Linux: enumerates `/proc/<pid>/fd` symlinks.
/// - macOS: enumerates via libproc (`proc_pidinfo(PROC_PIDLISTFDS)`) and attempts path recovery.
/// - Windows: returns NotSupported.
///
/// # Examples
///
/// ```rust,no_run
/// let pid = std::process::id();
/// // Replaces: lsof -p <pid>
/// let snap = sysprims_proc::list_fds(pid, None).unwrap();
/// println!("fd count: {}", snap.fds.len());
/// ```
pub fn list_fds(pid: u32, filter: Option<&FdFilter>) -> SysprimsResult<FdSnapshot> {
    // Safety: avoid negative pid_t casting semantics on Unix.
    const MAX_SAFE_PID: u32 = i32::MAX as u32;
    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }

    let filter = filter.cloned().unwrap_or_default();
    filter.validate()?;

    let (mut fds, mut warnings) = platform::list_fds_impl(pid)?;
    if filter.kind.is_some() {
        fds.retain(|fd| fd.matches(&filter));
    }

    // Best-effort: provide a helpful warning if nothing visible.
    if fds.is_empty() {
        warnings.push("No file descriptors visible".to_string());
    }

    Ok(make_fd_snapshot(pid, fds, warnings))
}

/// Resolve a process by port and protocol.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::Protocol;
///
/// // Replaces: lsof -nP -iTCP:8080 -sTCP:LISTEN
/// let proc = sysprims_proc::process_by_port(8080, Protocol::Tcp).unwrap();
/// println!("{} {}", proc.pid, proc.name);
/// ```
pub fn process_by_port(port: u16, protocol: Protocol) -> SysprimsResult<ProcessInfo> {
    if port == 0 {
        return Err(SysprimsError::invalid_argument(
            "port must be between 1 and 65535",
        ));
    }

    let filter = PortFilter {
        protocol: Some(protocol),
        local_port: Some(port),
    };
    let snapshot = listening_ports(Some(&filter))?;
    let binding = snapshot
        .bindings
        .into_iter()
        .find(|binding| binding.pid.is_some())
        .ok_or_else(|| SysprimsError::not_found(port as u32))?;

    match binding.process {
        Some(process) => Ok(process),
        None => binding
            .pid
            .map(get_process)
            .unwrap_or_else(|| Err(SysprimsError::not_found(port as u32))),
    }
}

#[cfg(unix)]
fn aggregate_permission_warning(skipped: usize, label: &str) -> Option<String> {
    if skipped == 0 {
        None
    } else {
        Some(format!(
            "Skipped {} {} due to permission errors",
            skipped, label
        ))
    }
}

fn aggregate_error_warning(skipped: usize, label: &str) -> Option<String> {
    if skipped == 0 {
        None
    } else {
        Some(format!("Skipped {} {} due to read errors", skipped, label))
    }
}

/// Get a snapshot with filter applied.
///
/// Filters are applied after enumeration. All filter criteria must match (AND logic).
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::ProcessFilter;
///
/// // Replaces: ps output grep/awk pipelines
/// let filter = ProcessFilter {
///     name_contains: Some("nginx".into()),
///     cpu_above: Some(1.0),
///     ..Default::default()
/// };
/// let snap = sysprims_proc::snapshot_filtered(&filter).unwrap();
/// ```
pub fn snapshot_filtered(filter: &ProcessFilter) -> SysprimsResult<ProcessSnapshot> {
    snapshot_filtered_with_options(filter, ProcessOptions::default())
}

/// Get a snapshot with filter applied and optional extended fields.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::{ProcessFilter, ProcessOptions};
///
/// // Replaces: ps filters that require brittle grep/awk chains
/// let filter = ProcessFilter {
///     name_contains: Some("worker".into()),
///     ..Default::default()
/// };
/// let snap = sysprims_proc::snapshot_filtered_with_options(
///     &filter,
///     ProcessOptions::default().with_threads(),
/// )
/// .unwrap();
/// println!("{}", snap.processes.len());
/// ```
pub fn snapshot_filtered_with_options(
    filter: &ProcessFilter,
    options: ProcessOptions,
) -> SysprimsResult<ProcessSnapshot> {
    filter.validate()?;
    validate_process_options(&options)?;

    let mut snap = snapshot_with_options(options)?;
    snap.processes.retain(|p| filter.matches(p));
    Ok(snap)
}

/// Get information for a single process.
///
/// # Errors
///
/// Returns `NotFound` if the process does not exist.
/// Returns `PermissionDenied` if the process cannot be read.
///
/// # Liveness and zombies (cross-platform note)
///
/// This function reports a process's *record*, not a normalized liveness answer,
/// and the two platforms diverge for an exited-but-unreaped child. On Linux the
/// kernel keeps the PID in the process table with state
/// [`ProcessState::Zombie`] until the parent reaps it, so `get_process` returns
/// `Ok(_)` with `state == Zombie`. On macOS the same PID typically becomes
/// unreadable almost immediately, so `get_process` returns `Err(NotFound)`.
///
/// Treating `Ok(_)` as "alive" is therefore not portable. When you need "is this
/// process actually still running?" use [`is_live`] (returns `false` for zombies
/// on every platform); for "is every trace of it gone?" use [`is_fully_gone`]; to
/// block until exit, use [`wait_pid`]. If you keep using `get_process`, inspect
/// [`ProcessInfo::state`] and treat [`ProcessState::Zombie`] as not-running.
///
/// # Examples
///
/// ```rust,no_run
/// // Replaces: ps -p <pid> -o ... plus parsing
/// let self_info = sysprims_proc::get_process(std::process::id()).unwrap();
/// println!("Current process: {}", self_info.name);
/// ```
pub fn get_process(pid: u32) -> SysprimsResult<ProcessInfo> {
    get_process_with_options(pid, ProcessOptions::default())
}

/// Get information for a single process with optional extended fields.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::ProcessOptions;
///
/// // Replaces: ps eww -p <pid> when you need env/threads
/// let pid = std::process::id();
/// let proc = sysprims_proc::get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
/// println!("threads: {:?}", proc.thread_count);
/// ```
pub fn get_process_with_options(pid: u32, options: ProcessOptions) -> SysprimsResult<ProcessInfo> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }
    validate_process_options(&options)?;
    platform::get_process_impl(pid, &options)
}

// ============================================================================
// Descendants API
// ============================================================================

/// A single level in a descendants result.
#[derive(Debug, Clone, Serialize)]
pub struct DescendantsLevel {
    /// Depth level (1 = direct children, 2 = grandchildren, etc.).
    pub level: u32,

    /// Processes at this level.
    pub processes: Vec<ProcessInfo>,
}

/// Result of a descendants traversal.
#[derive(Debug, Clone, Serialize)]
pub struct DescendantsResult {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,

    /// Root PID that was traversed from.
    pub root_pid: u32,

    /// Maximum depth that was requested.
    pub max_levels: u32,

    /// Processes grouped by depth level.
    pub levels: Vec<DescendantsLevel>,

    /// Total number of descendant processes found (before filtering).
    pub total_found: usize,

    /// Number of processes matching the filter (after filtering).
    pub matched_by_filter: usize,

    /// Timestamp (ISO 8601).
    pub timestamp: String,

    /// Platform identifier.
    pub platform: &'static str,
}

/// CPU measurement mode for descendants traversal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum CpuMode {
    /// Lifetime-average CPU usage (best-effort), normalized to 0-100.
    #[default]
    Lifetime,

    /// Sampled CPU usage over an interval (Activity Monitor / top style).
    ///
    /// Sampled values may exceed 100 when a process uses multiple cores.
    Monitor,
}

/// Configuration for descendants traversal.
#[derive(Debug, Clone)]
pub struct DescendantsConfig {
    /// PID to start traversal from.
    pub root_pid: u32,

    /// Maximum depth (1 = children only). `None` means traverse all levels.
    pub max_levels: Option<u32>,

    /// Optional process filter applied after traversal.
    pub filter: Option<ProcessFilter>,

    /// CPU measurement mode used before applying `cpu_above` filters.
    pub cpu_mode: CpuMode,

    /// Optional sample interval used when `cpu_mode = Monitor`.
    ///
    /// Defaults to 1 second when omitted.
    pub sample_duration: Option<Duration>,
}

/// Get descendants of a process using BFS traversal.
///
/// Performs a single snapshot and builds a parent→children map, then traverses
/// from `root_pid` up to `max_levels` deep. An optional filter is applied to
/// the results after traversal.
///
/// # Arguments
///
/// * `root_pid` - PID to start traversal from (must exist).
/// * `max_levels` - Maximum depth (1 = children only, u32::MAX = all).
/// * `filter` - Optional filter applied to descendant processes.
///
/// # Safety
///
/// Validates `root_pid` against ADR-0011 forbidden values (0, > i32::MAX).
///
/// # Examples
///
/// ```rust,no_run
/// // Replaces: pstree/ps --ppid traversal and text parsing
/// let root = std::process::id();
/// let result = sysprims_proc::descendants(root, 1, None).unwrap();
/// println!("matched: {}", result.matched_by_filter);
/// ```
pub fn descendants(
    root_pid: u32,
    max_levels: u32,
    filter: Option<&ProcessFilter>,
) -> SysprimsResult<DescendantsResult> {
    descendants_with_options(root_pid, max_levels, filter, ProcessOptions::default())
}

/// Get descendants of a process using BFS traversal with optional extended fields.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::{ProcessOptions, ProcessFilter};
///
/// // Replaces: pstree + ad hoc enrichment for thread/env fields
/// let root = std::process::id();
/// let filter = ProcessFilter {
///     cpu_above: Some(1.0),
///     ..Default::default()
/// };
/// let result = sysprims_proc::descendants_with_options(
///     root,
///     2,
///     Some(&filter),
///     ProcessOptions::default().with_threads(),
/// )
/// .unwrap();
/// println!("levels: {}", result.levels.len());
/// ```
pub fn descendants_with_options(
    root_pid: u32,
    max_levels: u32,
    filter: Option<&ProcessFilter>,
    options: ProcessOptions,
) -> SysprimsResult<DescendantsResult> {
    descendants_with_config_and_options(
        DescendantsConfig {
            root_pid,
            max_levels: Some(max_levels),
            filter: filter.cloned(),
            cpu_mode: CpuMode::Lifetime,
            sample_duration: None,
        },
        options,
    )
}

/// Get descendants using explicit traversal configuration.
///
/// # Examples
///
/// ```rust,no_run
/// use std::time::Duration;
/// use sysprims_proc::{CpuMode, DescendantsConfig};
///
/// // Replaces: repeated ps sampling loops for active CPU trees
/// let result = sysprims_proc::descendants_with_config(DescendantsConfig {
///     root_pid: std::process::id(),
///     max_levels: Some(2),
///     filter: None,
///     cpu_mode: CpuMode::Monitor,
///     sample_duration: Some(Duration::from_millis(500)),
/// })
/// .unwrap();
/// println!("total: {}", result.total_found);
/// ```
pub fn descendants_with_config(config: DescendantsConfig) -> SysprimsResult<DescendantsResult> {
    descendants_with_config_and_options(config, ProcessOptions::default())
}

/// Select descendant target PIDs from a traversal result.
///
/// This helper is intended for remediation workflows (for example,
/// `kill-descendants` and `guard_step`) that need to compute a deterministic
/// target set from one traversal snapshot.
///
/// When `cascade` is `false`, the result contains only matched descendant PIDs.
/// When `cascade` is `true`, each matched PID is expanded to include its
/// descendants within the already traversed tree.
///
/// Returned PIDs are sorted, deduplicated, and never include `root_pid`.
pub fn select_descendant_targets(
    result: &DescendantsResult,
    filter: Option<&ProcessFilter>,
    cascade: bool,
) -> Vec<u32> {
    let all_procs: Vec<&ProcessInfo> = result
        .levels
        .iter()
        .flat_map(|l| l.processes.iter())
        .collect();

    let matched_roots: Vec<u32> = all_procs
        .iter()
        .filter(|p| filter.map(|f| f.matches(p)).unwrap_or(true))
        .map(|p| p.pid)
        .collect();

    if !cascade {
        let mut out = matched_roots;
        out.sort_unstable();
        out.dedup();
        out.retain(|&pid| pid != result.root_pid);
        return out;
    }

    let mut children_map: HashMap<u32, Vec<u32>> = HashMap::new();
    for proc in all_procs {
        children_map.entry(proc.ppid).or_default().push(proc.pid);
    }

    let mut expanded: HashSet<u32> = HashSet::new();
    for root in matched_roots {
        let mut stack = vec![root];
        while let Some(pid) = stack.pop() {
            if !expanded.insert(pid) {
                continue;
            }
            if let Some(children) = children_map.get(&pid) {
                stack.extend(children.iter().copied());
            }
        }
    }

    let mut out: Vec<u32> = expanded.into_iter().collect();
    out.sort_unstable();
    out.retain(|&pid| pid != result.root_pid);
    out
}

/// Rule configuration for one guard evaluation cycle.
#[derive(Debug, Clone)]
pub struct GuardRule {
    /// Root PID used for descendants traversal.
    pub root_pid: u32,

    /// Maximum descendants traversal depth.
    pub max_levels: u32,

    /// Optional descendants filter.
    pub filter: Option<ProcessFilter>,

    /// CPU measurement mode used for `cpu_above` filtering.
    pub cpu_mode: CpuMode,

    /// Optional sampling interval used when `cpu_mode = Monitor`.
    pub sample_duration: Option<Duration>,
}

/// Action configuration for one guard evaluation cycle.
#[derive(Debug, Clone)]
pub enum GuardAction {
    /// Kill descendant processes matching the rule.
    KillDescendants {
        /// Signal number to send.
        signal: i32,
        /// Expand each matched PID to include its descendant subtree.
        cascade: bool,
    },
}

/// Configuration for one guard evaluation cycle.
#[derive(Debug, Clone)]
pub struct GuardConfig {
    /// Rule used to evaluate descendants.
    pub rule: GuardRule,
    /// Action to run after evaluation.
    pub action: GuardAction,
    /// Explicit action gate. Defaults should be false at call sites.
    pub action_enabled: bool,
    /// Hard cap on number of signaled targets when action is enabled.
    pub max_targets: u32,
}

/// Structured output for one guard evaluation cycle.
#[derive(Debug, Clone, Serialize)]
pub struct GuardEvent {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,
    /// Event timestamp (ISO 8601).
    pub timestamp: String,
    /// Platform identifier.
    pub platform: &'static str,
    /// Number of descendants matching the rule filter.
    pub matched: u32,
    /// Number of targets selected for action after safety/cap checks.
    pub targeted: u32,
    /// Number of successful kills in this cycle.
    pub killed: u32,
    /// Number of failed kills in this cycle.
    pub failed: u32,
    /// Number of targets skipped by safety exclusions.
    pub skipped_safety: u32,
    /// Non-fatal warnings.
    pub warnings: Vec<String>,
}

/// Execute one guard evaluation cycle.
///
/// This function performs descendants evaluation and optional remediation behind
/// an explicit action gate (`action_enabled`).
pub fn guard_step(config: GuardConfig) -> SysprimsResult<GuardEvent> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if config.rule.root_pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if config.rule.root_pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            config.rule.root_pid, MAX_SAFE_PID
        )));
    }
    if config.max_targets == 0 {
        return Err(SysprimsError::invalid_argument("max_targets must be >= 1"));
    }
    if let Some(f) = config.rule.filter.as_ref() {
        f.validate()?;
    }

    let desc = descendants_with_config_and_options(
        DescendantsConfig {
            root_pid: config.rule.root_pid,
            max_levels: Some(config.rule.max_levels),
            filter: None,
            cpu_mode: config.rule.cpu_mode,
            sample_duration: config.rule.sample_duration,
        },
        ProcessOptions::default(),
    )?;

    let matched_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), false);
    let matched = matched_pids.len() as u32;

    let (signal, cascade) = match config.action {
        GuardAction::KillDescendants { signal, cascade } => (signal, cascade),
    };

    let mut warnings = Vec::new();
    if !config.action_enabled {
        warnings.push("action disabled; no signals sent".to_string());
        return Ok(GuardEvent {
            schema_id: GUARD_EVENT_V1,
            timestamp: now_rfc3339(),
            platform: get_platform(),
            matched,
            targeted: 0,
            killed: 0,
            failed: 0,
            skipped_safety: 0,
            warnings,
        });
    }

    let mut target_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), cascade);

    if target_pids.len() > config.max_targets as usize {
        target_pids.truncate(config.max_targets as usize);
        warnings.push(format!(
            "target count capped at max_targets={} for this cycle",
            config.max_targets
        ));
    }

    let self_pid = std::process::id();
    let parent_pid = get_process(self_pid).ok().map(|p| p.ppid);

    let before = target_pids.len();
    target_pids.retain(|&pid| pid != self_pid && pid != 1 && pid != config.rule.root_pid);
    if let Some(ppid) = parent_pid {
        target_pids.retain(|&pid| pid != ppid);
    }
    let skipped_safety = before.saturating_sub(target_pids.len()) as u32;
    if skipped_safety > 0 {
        warnings.push(format!(
            "skipped {} unsafe target(s) (self/PID1/parent/root)",
            skipped_safety
        ));
    }

    if target_pids.is_empty() {
        return Ok(GuardEvent {
            schema_id: GUARD_EVENT_V1,
            timestamp: now_rfc3339(),
            platform: get_platform(),
            matched,
            targeted: 0,
            killed: 0,
            failed: 0,
            skipped_safety,
            warnings,
        });
    }

    let batch = sysprims_signal::kill_many(&target_pids, signal)?;

    Ok(GuardEvent {
        schema_id: GUARD_EVENT_V1,
        timestamp: now_rfc3339(),
        platform: get_platform(),
        matched,
        targeted: target_pids.len() as u32,
        killed: batch.succeeded.len() as u32,
        failed: batch.failed.len() as u32,
        skipped_safety,
        warnings,
    })
}

#[cfg(any(test, target_os = "linux", target_os = "macos"))]
fn is_sysprims_binary_name(name: &str) -> bool {
    name == "sysprims" || name.starts_with("sysprims-")
}

#[cfg(any(test, target_os = "linux", target_os = "macos"))]
fn guard_discovery_name(cmdline: &[String], fallback_name: &str) -> Option<String> {
    let binary = cmdline.first()?.rsplit('/').next().unwrap_or(fallback_name);
    if !is_sysprims_binary_name(binary) {
        return None;
    }

    let guard_index = cmdline.iter().position(|arg| arg == "guard")?;
    let root_pid = cmdline.get(guard_index + 1)?;
    if root_pid.parse::<u32>().ok()? == 0 {
        return None;
    }

    Some(format!("sysprims-guard:{root_pid}"))
}

#[cfg(target_os = "linux")]
fn set_guard_process_title(root_pid: u32) {
    let title = format!("sysprims-guard:{root_pid}");
    let truncated = title.bytes().take(15).collect::<Vec<_>>();
    if let Ok(c_title) = std::ffi::CString::new(truncated) {
        unsafe {
            libc::prctl(
                libc::PR_SET_NAME,
                c_title.as_ptr() as libc::c_ulong,
                0,
                0,
                0,
            );
        }
    }
}

#[cfg(target_os = "macos")]
fn set_guard_process_title(root_pid: u32) {
    unsafe extern "C" {
        fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
    }

    let title = format!("sysprims-guard:{root_pid}");
    let thread_title = std::ffi::CString::new(title.bytes().take(63).collect::<Vec<_>>()).ok();

    unsafe {
        if let Some(name) = thread_title.as_ref() {
            let _ = pthread_setname_np(name.as_ptr());
        }
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn set_guard_process_title(_root_pid: u32) {}

// ============================================================================
// GuardRunner: Managed Guard Loop
// ============================================================================

/// Preset configurations for common guard use cases.
///
/// Presets provide sensible defaults for interval and sample duration.
/// Explicit values always override preset defaults.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuardPreset {
    /// Short interval for interactive debugging (3s interval, 2s sample).
    Interactive,
    /// Moderate interval for background monitoring (3m interval, 3s sample).
    Background,
    /// Long interval for lightweight watchdog (5m interval, 5s sample).
    Watchdog,
}

impl GuardPreset {
    /// Default tick interval for this preset.
    pub fn interval(&self) -> Duration {
        match self {
            Self::Interactive => Duration::from_secs(3),
            Self::Background => Duration::from_secs(180),
            Self::Watchdog => Duration::from_secs(300),
        }
    }

    /// Default CPU sample duration for this preset.
    pub fn sample_duration(&self) -> Duration {
        match self {
            Self::Interactive => Duration::from_secs(2),
            Self::Background => Duration::from_secs(3),
            Self::Watchdog => Duration::from_secs(5),
        }
    }
}

/// Configuration for a managed guard loop.
#[derive(Debug, Clone)]
pub struct GuardRunnerConfig {
    /// Per-tick evaluation configuration.
    pub guard: GuardConfig,
    /// Tick interval between evaluations.
    pub interval: Duration,
    /// Maximum number of ticks before auto-stop (None = unlimited).
    pub max_iterations: Option<u64>,
}

/// Summary returned after a guard loop completes.
#[derive(Debug, Clone)]
pub struct GuardRunnerSummary {
    /// Total number of ticks executed.
    pub ticks: u64,
    /// Reason the loop stopped.
    pub stop_reason: StopReason,
}

/// Why the guard loop stopped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StopReason {
    /// Received SIGINT or SIGTERM.
    Signal,
    /// Reached max_iterations limit.
    MaxIterations,
    /// Stopped via [`GuardStopHandle::stop()`].
    Requested,
}

/// Cloneable, thread-safe handle for stopping a running guard loop.
///
/// Obtain via [`GuardRunner::stop_handle()`] before calling [`GuardRunner::run()`].
/// Can be sent to another thread, stored in a signal handler, or used from
/// an async runtime to request graceful shutdown.
///
/// # Example
///
/// ```no_run
/// use std::time::Duration;
/// use sysprims_proc::{
///     GuardRunnerConfig, GuardRunner, GuardConfig, GuardRule, GuardAction,
///     CpuMode,
/// };
///
/// let config = GuardRunnerConfig {
///     guard: GuardConfig {
///         rule: GuardRule {
///             root_pid: 12345,
///             max_levels: u32::MAX,
///             filter: None,
///             cpu_mode: CpuMode::Lifetime,
///             sample_duration: None,
///         },
///         action: GuardAction::KillDescendants { signal: 15, cascade: false },
///         action_enabled: false,
///         max_targets: 8,
///     },
///     interval: Duration::from_secs(5),
///     max_iterations: None,
/// };
///
/// let mut runner = GuardRunner::new(config).unwrap();
/// let handle = runner.stop_handle();
///
/// // Stop from another thread after 30 seconds
/// std::thread::spawn(move || {
///     std::thread::sleep(Duration::from_secs(30));
///     handle.stop();
/// });
///
/// let summary = runner.run(|event| {
///     println!("matched={}", event.matched);
/// }, |_tick, err| {
///     eprintln!("error: {err}");
/// }).unwrap();
/// // summary.stop_reason == StopReason::Requested
/// ```
#[derive(Clone)]
pub struct GuardStopHandle {
    /// Programmatic stop flag — set by stop(), distinct from signal flag.
    requested: Arc<std::sync::atomic::AtomicBool>,
    /// Write-only handle to GuardSignals' stop flag.
    signals_flag: guard_signals::StopFlagHandle,
    /// Clone of SignalManager — calling stop() unblocks listen().
    manager: guard_signals::SignalManager,
}

impl GuardStopHandle {
    /// Request the guard loop to stop gracefully.
    ///
    /// The loop will finish the current tick and then exit with
    /// [`StopReason::Requested`].
    pub fn stop(&self) {
        self.requested
            .store(true, std::sync::atomic::Ordering::SeqCst);
        // Set the GuardSignals stop flag so should_stop() returns true
        self.signals_flag.set();
        // Unblock the signal listener thread
        self.manager.stop();
    }
}

impl std::fmt::Debug for GuardStopHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GuardStopHandle")
            .field(
                "requested",
                &self.requested.load(std::sync::atomic::Ordering::SeqCst),
            )
            .finish()
    }
}

/// Managed guard loop with signal handling and drift-free scheduling.
///
/// `GuardRunner` wraps `guard_step()` in a tick loop with `GuardSignals`
/// for clean shutdown and `Tick` for drift-free scheduling.
///
/// # Usage
///
/// 1. Create with [`GuardRunner::new()`]
/// 2. Obtain a [`GuardStopHandle`] via [`stop_handle()`](Self::stop_handle)
///    (optional — only needed for programmatic stop from another thread)
/// 3. Call [`run()`](Self::run) — blocks until signal, max_iterations, or stop handle
///
/// # Example
///
/// ```no_run
/// use std::time::Duration;
/// use sysprims_proc::{
///     GuardRunnerConfig, GuardRunner, GuardConfig, GuardRule, GuardAction,
///     CpuMode,
/// };
///
/// let config = GuardRunnerConfig {
///     guard: GuardConfig {
///         rule: GuardRule {
///             root_pid: 12345,
///             max_levels: u32::MAX,
///             filter: None,
///             cpu_mode: CpuMode::Lifetime,
///             sample_duration: None,
///         },
///         action: GuardAction::KillDescendants { signal: 15, cascade: false },
///         action_enabled: false,
///         max_targets: 8,
///     },
///     interval: Duration::from_secs(60),
///     max_iterations: Some(10),
/// };
///
/// let mut runner = GuardRunner::new(config).unwrap();
/// let summary = runner.run(|event| {
///     println!("matched={}", event.matched);
/// }, |_tick, err| {
///     eprintln!("error: {err}");
/// }).unwrap();
/// println!("stopped after {} ticks: {:?}", summary.ticks, summary.stop_reason);
/// ```
pub struct GuardRunner {
    config: GuardRunnerConfig,
    signals: guard_signals::GuardSignals,
    tick: time::Tick,
    /// Tracks whether stop was requested programmatically (vs signal).
    stop_requested: Arc<std::sync::atomic::AtomicBool>,
}

impl GuardRunner {
    /// Create a new runner. Sets up signal handlers and tick scheduler.
    ///
    /// Does not start the loop — call [`run()`](Self::run) to begin.
    pub fn new(config: GuardRunnerConfig) -> SysprimsResult<Self> {
        let signals = guard_signals::GuardSignals::start()?;
        let tick = time::Tick::new(config.interval)?;
        Ok(Self {
            config,
            signals,
            tick,
            stop_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        })
    }

    /// Get a cloneable stop handle for this runner.
    ///
    /// The handle can be sent to another thread and used to request
    /// graceful shutdown while [`run()`](Self::run) is active.
    pub fn stop_handle(&self) -> GuardStopHandle {
        GuardStopHandle {
            requested: Arc::clone(&self.stop_requested),
            signals_flag: self.signals.stop_flag_handle(),
            manager: self.signals.manager().clone(),
        }
    }

    /// Run the guard loop, calling `on_event` after each tick.
    ///
    /// Blocks until a shutdown signal, `max_iterations`, or
    /// [`GuardStopHandle::stop()`].
    ///
    /// Errors from individual `guard_step()` calls are passed to `on_error`;
    /// the loop continues unless stopped.
    pub fn run<F, E>(
        &mut self,
        mut on_event: F,
        mut on_error: E,
    ) -> SysprimsResult<GuardRunnerSummary>
    where
        F: FnMut(&GuardEvent),
        E: FnMut(u64, &SysprimsError),
    {
        let mut tick_count: u64 = 0;

        set_guard_process_title(self.config.guard.rule.root_pid);

        while !self.signals.should_stop() {
            match guard_step(self.config.guard.clone()) {
                Ok(event) => {
                    tick_count += 1;
                    on_event(&event);
                }
                Err(e) => {
                    tick_count += 1;
                    on_error(tick_count, &e);
                }
            }

            // Check max_iterations
            if let Some(max) = self.config.max_iterations {
                if tick_count >= max {
                    return Ok(GuardRunnerSummary {
                        ticks: tick_count,
                        stop_reason: StopReason::MaxIterations,
                    });
                }
            }

            // Check stop flag before sleeping (signal may arrive during tick)
            if self.signals.should_stop() {
                break;
            }

            self.tick.sleep_until_next();
        }

        let reason = if self
            .stop_requested
            .load(std::sync::atomic::Ordering::SeqCst)
        {
            StopReason::Requested
        } else {
            StopReason::Signal
        };

        Ok(GuardRunnerSummary {
            ticks: tick_count,
            stop_reason: reason,
        })
    }

    /// Access the underlying signal controller (for testing).
    pub fn signals(&self) -> &guard_signals::GuardSignals {
        &self.signals
    }
}

// ============================================================================
// Ancestors API
// ============================================================================

/// Result of an ancestors traversal.
#[derive(Debug, Clone, Serialize)]
pub struct AncestorsResult {
    /// Schema identifier for version detection.
    pub schema_id: &'static str,

    /// ISO 8601 timestamp.
    pub timestamp: String,

    /// Platform identifier.
    pub platform: &'static str,

    /// Starting PID that was queried.
    pub pid: u32,

    /// Ancestor chain from the starting PID upward (pid -> parent -> grandparent -> ...).
    pub chain: Vec<ProcessInfo>,

    /// Non-fatal warnings (loop detected, permission denied, etc.).
    pub warnings: Vec<String>,
}

/// Walk the parent chain from `pid` upward, collecting process info at each step.
///
/// Stops when:
/// - PID becomes 0 or 1 (init/launchd)
/// - `max_depth` is reached
/// - A process is not found or permission is denied (recorded as warning)
/// - A loop is detected (PID repeats)
///
/// The starting PID itself is included as the first element of the chain.
///
/// # Errors
///
/// - `InvalidArgument` if `pid` is 0 or exceeds `i32::MAX`
/// - `NotFound` if the starting PID does not exist
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::{ancestors, ProcessOptions};
///
/// let result = sysprims_proc::ancestors(std::process::id(), 10, ProcessOptions::default()).unwrap();
/// for p in &result.chain {
///     println!("PID {} ({})", p.pid, p.name);
/// }
/// ```
pub fn ancestors(
    pid: u32,
    max_depth: u32,
    options: ProcessOptions,
) -> SysprimsResult<AncestorsResult> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }
    validate_process_options(&options)?;

    let mut chain = Vec::new();
    let mut warnings = Vec::new();
    let mut seen = HashSet::new();
    let mut current_pid = pid;

    for depth in 0..=max_depth {
        if !seen.insert(current_pid) {
            warnings.push(format!(
                "loop detected: PID {} already visited at depth {}",
                current_pid, depth
            ));
            break;
        }

        match get_process_with_options(current_pid, options) {
            Ok(info) => {
                let next_pid = info.ppid;
                chain.push(info);

                // Stop at init/launchd (PID 0 or 1) or if ppid == self (root process)
                if next_pid == 0 || next_pid == 1 || next_pid == current_pid {
                    // Include PID 1 in chain if we can read it
                    if next_pid == 1 && current_pid != 1 {
                        match get_process_with_options(1, options) {
                            Ok(init_info) => chain.push(init_info),
                            Err(_) => {
                                warnings.push("could not read init/launchd (PID 1)".to_string());
                            }
                        }
                    }
                    break;
                }

                current_pid = next_pid;
            }
            Err(e) => {
                if depth == 0 {
                    // Starting PID must exist
                    return Err(e);
                }
                warnings.push(format!(
                    "ancestor walk stopped at PID {}: {}",
                    current_pid, e
                ));
                break;
            }
        }
    }

    Ok(AncestorsResult {
        schema_id: ANCESTORS_RESULT_V1,
        timestamp: now_rfc3339(),
        platform: get_platform(),
        pid,
        chain,
        warnings,
    })
}

/// Get descendants using explicit traversal configuration and optional extended fields.
///
/// # Examples
///
/// ```rust,no_run
/// use sysprims_proc::{CpuMode, DescendantsConfig, ProcessOptions};
///
/// // Replaces: custom parent-child map logic plus ps parsing
/// let result = sysprims_proc::descendants_with_config_and_options(
///     DescendantsConfig {
///         root_pid: std::process::id(),
///         max_levels: Some(1),
///         filter: None,
///         cpu_mode: CpuMode::Lifetime,
///         sample_duration: None,
///     },
///     ProcessOptions::default().with_threads(),
/// )
/// .unwrap();
/// println!("{}", result.matched_by_filter);
/// ```
pub fn descendants_with_config_and_options(
    config: DescendantsConfig,
    options: ProcessOptions,
) -> SysprimsResult<DescendantsResult> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if config.root_pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if config.root_pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            config.root_pid, MAX_SAFE_PID
        )));
    }

    validate_process_options(&options)?;

    if let Some(f) = config.filter.as_ref() {
        f.validate()?;
    }

    // Verify root exists before any traversal/sampling work.
    let _ = get_process_with_options(config.root_pid, options)?;

    // Snapshot for consistent traversal; monitor mode samples at the snapshot level.
    let snap = snapshot_for_descendants(options, config.cpu_mode, config.sample_duration)?;

    // Build parent → children map.
    let mut children_map: HashMap<u32, Vec<ProcessInfo>> = HashMap::new();
    for proc in snap.processes {
        children_map.entry(proc.ppid).or_default().push(proc);
    }

    // BFS traversal.
    let mut levels: Vec<DescendantsLevel> = Vec::new();
    let mut current_pids = vec![config.root_pid];
    let mut total_found: usize = 0;
    let max_levels = config.max_levels.unwrap_or(u32::MAX);

    for depth in 1..=max_levels {
        let mut level_procs = Vec::new();
        let mut next_pids = Vec::new();

        for &pid in &current_pids {
            if let Some(children) = children_map.get(&pid) {
                for child in children {
                    level_procs.push(child.clone());
                    next_pids.push(child.pid);
                }
            }
        }

        if level_procs.is_empty() {
            break;
        }

        total_found += level_procs.len();
        levels.push(DescendantsLevel {
            level: depth,
            processes: level_procs,
        });
        current_pids = next_pids;
    }

    // Apply filter if provided.
    let mut matched_by_filter = total_found;
    if let Some(f) = config.filter.as_ref() {
        for level in &mut levels {
            level.processes.retain(|p| f.matches(p));
        }
        matched_by_filter = levels.iter().map(|l| l.processes.len()).sum();
        // Remove empty levels after filtering.
        levels.retain(|l| !l.processes.is_empty());
    }

    Ok(DescendantsResult {
        schema_id: match config.cpu_mode {
            CpuMode::Lifetime => DESCENDANTS_RESULT_V1,
            CpuMode::Monitor => DESCENDANTS_RESULT_SAMPLED_V1,
        },
        root_pid: config.root_pid,
        max_levels,
        levels,
        total_found,
        matched_by_filter,
        timestamp: now_rfc3339(),
        platform: get_platform(),
    })
}

fn snapshot_for_descendants(
    options: ProcessOptions,
    cpu_mode: CpuMode,
    sample_duration: Option<Duration>,
) -> SysprimsResult<ProcessSnapshot> {
    match cpu_mode {
        CpuMode::Lifetime => snapshot_with_options(options),
        CpuMode::Monitor => {
            let sample = sample_duration.unwrap_or_else(|| Duration::from_secs(1));
            snapshot_with_sampled_cpu(options, sample)
        }
    }
}

fn snapshot_with_sampled_cpu(
    options: ProcessOptions,
    sample_duration: Duration,
) -> SysprimsResult<ProcessSnapshot> {
    if sample_duration.is_zero() {
        return Err(SysprimsError::invalid_argument(
            "sample duration must be > 0",
        ));
    }

    let snap0 = snapshot_with_options(options)?;
    let mut t0 = HashMap::<u32, (Option<u64>, u64)>::new();
    for p in &snap0.processes {
        if let Ok(cpu_ns) = cpu_total_time_ns(p.pid) {
            t0.insert(p.pid, (p.start_time_unix_ms, cpu_ns));
        }
    }

    std::thread::sleep(sample_duration);

    let mut snap1 = snapshot_with_options(options)?;
    let dt_ns = sample_duration.as_nanos() as f64;
    if dt_ns > 0.0 {
        for p in &mut snap1.processes {
            if let Some((start0, cpu0)) = t0.get(&p.pid) {
                // PID reuse guard: only compute if start time matches.
                if start0.is_some()
                    && p.start_time_unix_ms.is_some()
                    && start0 != &p.start_time_unix_ms
                {
                    continue;
                }

                if let Ok(cpu1) = cpu_total_time_ns(p.pid) {
                    let delta = cpu1.saturating_sub(*cpu0) as f64;
                    p.cpu_percent = (delta / dt_ns) * 100.0;
                }
            }
        }
    }

    // Sampled CPU semantics can exceed 100 on multi-core.
    snap1.schema_id = PROCESS_INFO_SAMPLED_V1;
    Ok(snap1)
}

/// Wait for a PID to exit, up to the provided timeout.
///
/// Returns:
/// - `Ok` with `timed_out=true` if the process did not exit in time.
/// - `Ok` with `exited=true` if the process was observed to have exited.
/// - `Err(NotFound)` if the PID does not exist at the time of the first check.
/// - `Err(PermissionDenied)` if the platform forbids even querying liveness.
///
/// # Examples
///
/// ```rust,no_run
/// use std::time::Duration;
///
/// // Replaces: while kill -0 <pid>; do sleep ...; done
/// let res = sysprims_proc::wait_pid(std::process::id(), Duration::from_millis(1)).unwrap();
/// println!("timed_out: {}", res.timed_out);
/// ```
pub fn wait_pid(pid: u32, timeout: Duration) -> SysprimsResult<WaitPidResult> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }
    platform::wait_pid_impl(pid, timeout)
}

/// Report whether a PID refers to a live (non-zombie) process.
///
/// This is the portable answer to "did the process I just signalled actually
/// stop running?". It normalizes a divergence that [`get_process`] exposes: an
/// exited-but-unreaped child is a *zombie* still present in the process table on
/// Linux but is typically already unreadable on macOS. `is_live` returns `false`
/// for a zombie on every platform. Windows has no Unix-style zombie, so a PID is
/// simply live or gone.
///
/// To keep that answer portable, this predicate treats a present-but-unreadable
/// PID (the state a killed-but-unreaped child reaches on macOS) as *not live*.
/// That is a deliberate liveness bias for the kill-then-check pattern, not a
/// diagnostic: when you need a process's full record, use [`get_process`] and
/// inspect [`ProcessInfo::state`] directly.
///
/// This is a single-shot probe (no waiting). To block until exit, use
/// [`wait_pid`]; for "is every trace of the process gone?" use [`is_fully_gone`].
///
/// This answers liveness at a PID *slot*, not process *identity*: PIDs are
/// reused, so this is not a security or identity boundary. It is safe for the
/// "did the child I just signalled stop?" pattern because the parent holds the
/// unreaped slot until it reaps, so the PID cannot recycle underneath the check.
///
/// # Errors
///
/// - `InvalidArgument` for PID 0 or a PID above `i32::MAX` (rejected before any
///   platform probe, per the PID-safety rule in ADR-0011).
/// - `PermissionDenied` if the platform forbids querying the PID. This is rare
///   for caller-owned children (the primary use case), which are always
///   queryable by their parent.
///
/// # Examples
///
/// ```rust,no_run
/// // Replaces: kill -0 <pid> plus a zombie-state check
/// assert!(sysprims_proc::is_live(std::process::id()).unwrap());
/// ```
pub fn is_live(pid: u32) -> SysprimsResult<bool> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }
    Ok(platform::liveness_impl(pid)? == Liveness::Live)
}

/// Report whether a PID has no observable process record (fully gone).
///
/// Unlike [`is_live`], this distinguishes a *zombie* (exited but not yet reaped)
/// from a *fully reaped* process: a zombie is neither live nor fully gone, so
/// `is_fully_gone` returns `false` for it. Use this when a test or supervisor
/// needs to assert that cleanup has completed and the PID slot is free.
///
/// This is a single-shot probe (no waiting).
///
/// # Errors
///
/// - `InvalidArgument` for PID 0 or a PID above `i32::MAX` (rejected before any
///   platform probe, per the PID-safety rule in ADR-0011).
/// - `PermissionDenied` if the platform forbids querying the PID (the process
///   exists but cannot be classified).
///
/// # Examples
///
/// ```rust,no_run
/// let pid = std::process::id();
/// assert!(!sysprims_proc::is_fully_gone(pid).unwrap());
/// ```
pub fn is_fully_gone(pid: u32) -> SysprimsResult<bool> {
    const MAX_SAFE_PID: u32 = i32::MAX as u32;

    if pid == 0 {
        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
    }
    if pid > MAX_SAFE_PID {
        return Err(SysprimsError::invalid_argument(format!(
            "PID {} exceeds maximum safe value {}",
            pid, MAX_SAFE_PID
        )));
    }
    Ok(platform::liveness_impl(pid)? == Liveness::Gone)
}

// ============================================================================
// Helpers
// ============================================================================

fn make_port_snapshot(bindings: Vec<PortBinding>, warnings: Vec<String>) -> PortBindingsSnapshot {
    let mut warnings = warnings;
    if bindings.is_empty() {
        warnings.push("No listening ports found".to_string());
    }

    PortBindingsSnapshot {
        schema_id: PORT_BINDINGS_V1,
        timestamp: now_rfc3339(),
        platform: get_platform(),
        bindings,
        warnings,
    }
}

fn make_fd_snapshot(pid: u32, fds: Vec<FdInfo>, warnings: Vec<String>) -> FdSnapshot {
    FdSnapshot {
        schema_id: FD_SNAPSHOT_V1,
        timestamp: now_rfc3339(),
        platform: get_platform(),
        pid,
        fds,
        warnings,
    }
}

// Timestamp generation consolidated in sysprims_core::time::now_rfc3339()

/// Create a ProcessSnapshot with the standard schema ID.
fn make_snapshot(processes: Vec<ProcessInfo>) -> ProcessSnapshot {
    ProcessSnapshot {
        schema_id: PROCESS_INFO_V1,
        timestamp: now_rfc3339(),
        processes,
    }
}

fn make_wait_pid_result(
    pid: u32,
    exited: bool,
    timed_out: bool,
    exit_code: Option<i32>,
    warnings: Vec<String>,
) -> WaitPidResult {
    WaitPidResult {
        schema_id: WAIT_PID_RESULT_V1,
        timestamp: now_rfc3339(),
        platform: get_platform(),
        pid,
        exited,
        timed_out,
        exit_code,
        warnings,
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::process::{Child, Command, Stdio};
    use std::thread;

    #[test]
    fn test_snapshot_not_empty() {
        let snap = snapshot().unwrap();
        assert!(
            !snap.processes.is_empty(),
            "Snapshot should contain processes"
        );
    }

    #[test]
    fn test_snapshot_has_schema_id() {
        let snap = snapshot().unwrap();
        assert_eq!(snap.schema_id, PROCESS_INFO_V1);
        assert!(snap.schema_id.contains("process-info"));
    }

    #[test]
    fn test_snapshot_has_timestamp() {
        let snap = snapshot().unwrap();
        assert!(!snap.timestamp.is_empty());
        // Should be RFC3339 format
        assert!(snap.timestamp.contains('T'));
        assert!(snap.timestamp.contains('Z') || snap.timestamp.contains('+'));
    }

    #[test]
    #[cfg(unix)]
    fn test_snapshot_has_processes() {
        // On macOS with SIP, we may only see user-owned processes
        // On Linux without root, we may also be restricted
        // Just verify we get a reasonable number of processes
        let snap = snapshot().unwrap();

        // We should at least see our own process
        let own_pid = std::process::id();
        let has_self = snap.processes.iter().any(|p| p.pid == own_pid);
        assert!(has_self, "Snapshot should include our own process");

        // We should see at least a few processes
        assert!(
            snap.processes.len() >= 3,
            "Should have at least a few visible processes, got {}",
            snap.processes.len()
        );
    }

    #[test]
    fn test_get_self() {
        let pid = std::process::id();
        let info = get_process(pid).unwrap();
        assert_eq!(info.pid, pid);
        assert!(!info.name.is_empty(), "Process should have a name");
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_own_process_has_cmdline() {
        let snap = snapshot().unwrap();
        let own_pid = std::process::id();
        let own_proc = snap
            .processes
            .iter()
            .find(|p| p.pid == own_pid)
            .expect("Should find own process in snapshot");
        assert!(
            !own_proc.cmdline.is_empty(),
            "Own process should have cmdline, got empty"
        );
    }

    #[test]
    fn test_get_self_has_valid_fields() {
        let pid = std::process::id();
        let info = get_process(pid).unwrap();

        // CPU percent should be in valid range
        assert!(info.cpu_percent >= 0.0);
        assert!(info.cpu_percent <= 100.0);

        // Memory should be non-zero for running process
        // Note: Don't require this as some systems may report 0
        assert!(info.memory_kb < u64::MAX);

        // Identity fields are best-effort; if present, they should be reasonable.
        if let Some(ms) = info.start_time_unix_ms {
            assert!(ms > 0);
        }
        if let Some(ref exe) = info.exe_path {
            assert!(!exe.is_empty());
        }

        // State should be running (we're executing)
        // Note: Windows reports Unknown as it doesn't expose process state simply
        assert!(
            info.state == ProcessState::Running
                || info.state == ProcessState::Sleeping
                || info.state == ProcessState::Unknown,
            "Test process should be running, sleeping, or unknown (Windows)"
        );
    }

    #[test]
    fn test_wait_pid_self_times_out() {
        let pid = std::process::id();
        let r = wait_pid(pid, Duration::from_millis(1)).unwrap();
        assert_eq!(r.pid, pid);
        assert!(r.timed_out);
        assert!(!r.exited);
    }

    /// ADR-0011: every public pid-taking entrypoint must reject PID 0 and PIDs
    /// above `i32::MAX` *before* any `pid as pid_t` cast could produce a
    /// negative/broadcast PID. These inputs must never reach a syscall.
    #[test]
    fn pid_taking_entrypoints_reject_unsafe_pids() {
        let over_max = (i32::MAX as u32) + 1;
        for &pid in &[0u32, over_max, u32::MAX] {
            assert!(
                matches!(get_process(pid), Err(SysprimsError::InvalidArgument { .. })),
                "get_process must reject unsafe PID {pid}"
            );
            assert!(
                matches!(
                    wait_pid(pid, Duration::from_millis(1)),
                    Err(SysprimsError::InvalidArgument { .. })
                ),
                "wait_pid must reject unsafe PID {pid}"
            );
            assert!(
                matches!(
                    cpu_total_time_ns(pid),
                    Err(SysprimsError::InvalidArgument { .. })
                ),
                "cpu_total_time_ns must reject unsafe PID {pid}"
            );
        }
    }

    #[test]
    fn test_filter_by_name_contains() {
        // Filter for our own test process
        let filter = ProcessFilter {
            name_contains: Some("sysprims".into()),
            ..Default::default()
        };
        let snap = snapshot_filtered(&filter).unwrap();

        for proc in &snap.processes {
            assert!(
                proc.name.to_lowercase().contains("sysprims"),
                "Filtered process '{}' should contain 'sysprims'",
                proc.name
            );
        }
    }

    #[test]
    fn test_guard_discovery_name_matches_guard_cmdline() {
        let cmdline = vec![
            "/usr/local/bin/sysprims".to_string(),
            "guard".to_string(),
            "27776".to_string(),
            "--preset".to_string(),
            "watchdog".to_string(),
        ];

        assert_eq!(
            guard_discovery_name(&cmdline, "sysprims"),
            Some("sysprims-guard:27776".to_string())
        );
    }

    #[test]
    fn test_guard_discovery_name_ignores_non_guard_cmdline() {
        let cmdline = vec![
            "/usr/local/bin/sysprims".to_string(),
            "pstat".to_string(),
            "--json".to_string(),
        ];

        assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
    }

    #[test]
    fn test_guard_discovery_name_rejects_invalid_root_pid() {
        let cmdline = vec![
            "/usr/local/bin/sysprims".to_string(),
            "guard".to_string(),
            "not-a-pid".to_string(),
        ];

        assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
    }

    #[test]
    fn test_filter_by_pid() {
        let my_pid = std::process::id();
        let filter = ProcessFilter {
            pid_in: Some(vec![my_pid]),
            ..Default::default()
        };
        let snap = snapshot_filtered(&filter).unwrap();

        assert_eq!(snap.processes.len(), 1);
        assert_eq!(snap.processes[0].pid, my_pid);
    }

    #[test]
    fn test_filter_validation_cpu_range() {
        let filter = ProcessFilter {
            cpu_above: Some(150.0),
            ..Default::default()
        };
        let result = filter.validate();
        assert!(result.is_err());

        let filter = ProcessFilter {
            cpu_above: Some(-1.0),
            ..Default::default()
        };
        let result = filter.validate();
        assert!(result.is_err());

        let filter = ProcessFilter {
            cpu_above: Some(50.0),
            ..Default::default()
        };
        let result = filter.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_nonexistent_pid() {
        // Use a very high PID that shouldn't exist
        let result = get_process(99999999);
        assert!(
            matches!(result, Err(SysprimsError::NotFound { .. })),
            "Should return NotFound for nonexistent PID"
        );
    }

    #[test]
    fn test_invalid_pid_zero() {
        let result = get_process(0);
        assert!(
            matches!(result, Err(SysprimsError::InvalidArgument { .. })),
            "PID 0 should be invalid"
        );
    }

    #[test]
    fn test_cpu_normalized() {
        let snap = snapshot().unwrap();
        for proc in &snap.processes {
            assert!(
                proc.cpu_percent >= 0.0,
                "CPU percent for PID {} should be >= 0",
                proc.pid
            );
            assert!(
                proc.cpu_percent <= 100.0,
                "CPU percent for PID {} should be <= 100, got {}",
                proc.pid,
                proc.cpu_percent
            );
        }
    }

    #[test]
    fn test_process_state_serialization() {
        // Test that states serialize to snake_case
        let json = serde_json::to_string(&ProcessState::Running).unwrap();
        assert_eq!(json, "\"running\"");

        let json = serde_json::to_string(&ProcessState::Sleeping).unwrap();
        assert_eq!(json, "\"sleeping\"");

        let json = serde_json::to_string(&ProcessState::Zombie).unwrap();
        assert_eq!(json, "\"zombie\"");
    }

    #[test]
    fn test_filter_deserialization() {
        let json = r#"{"name_contains": "test", "cpu_above": 5.0}"#;
        let filter: ProcessFilter = serde_json::from_str(json).unwrap();
        assert_eq!(filter.name_contains, Some("test".to_string()));
        assert_eq!(filter.cpu_above, Some(5.0));
    }

    #[test]
    fn test_filter_unknown_field_rejected() {
        let json = r#"{"unknown_field": "value"}"#;
        let result: Result<ProcessFilter, _> = serde_json::from_str(json);
        assert!(result.is_err(), "Unknown fields should be rejected");
    }

    #[test]
    fn test_port_filter_unknown_field_rejected() {
        let json = r#"{"unknown_field": true}"#;
        let result: Result<PortFilter, _> = serde_json::from_str(json);
        assert!(result.is_err(), "Unknown fields should be rejected");
    }

    #[test]
    fn test_port_filter_schema_id() {
        assert!(PortFilter::schema_id().contains("port-filter"));
    }

    #[test]
    fn test_process_options_builder() {
        let opts = ProcessOptions::default();
        assert!(!opts.include_env);
        assert!(!opts.include_threads);

        let opts = ProcessOptions::default().with_env().with_threads();
        assert!(opts.include_env);
        assert!(opts.include_threads);
    }

    #[test]
    fn test_get_process_with_default_options_has_no_proc_ext_fields() {
        let pid = std::process::id();
        let info = get_process_with_options(pid, ProcessOptions::default()).unwrap();
        assert!(info.env.is_none());
        assert!(info.thread_count.is_none());
    }

    #[test]
    #[cfg(feature = "proc_ext")]
    fn test_get_process_with_threads_populates_thread_count() {
        let pid = std::process::id();
        let info = get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
        assert!(info.thread_count.is_some());
    }

    #[test]
    #[cfg(all(feature = "proc_ext", unix))]
    fn test_get_process_with_env_populates_env_map() {
        let pid = std::process::id();
        let info = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap();
        assert!(info.env.is_some());
    }

    #[test]
    #[cfg(not(feature = "proc_ext"))]
    fn test_proc_ext_options_rejected_when_feature_disabled() {
        let pid = std::process::id();
        let err = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap_err();
        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
    }

    #[test]
    fn test_descendants_with_config_lifetime_self() {
        let pid = std::process::id();
        let config = DescendantsConfig {
            root_pid: pid,
            max_levels: Some(1),
            filter: None,
            cpu_mode: CpuMode::Lifetime,
            sample_duration: None,
        };

        let result = descendants_with_config(config).unwrap();
        assert_eq!(result.root_pid, pid);
        assert_eq!(result.max_levels, 1);
    }

    #[test]
    fn test_descendants_with_config_monitor_self() {
        let pid = std::process::id();
        let config = DescendantsConfig {
            root_pid: pid,
            max_levels: Some(1),
            filter: None,
            cpu_mode: CpuMode::Monitor,
            sample_duration: Some(Duration::from_millis(1)),
        };

        let result = descendants_with_config(config).unwrap();
        assert_eq!(result.schema_id, DESCENDANTS_RESULT_SAMPLED_V1);
        assert_eq!(result.root_pid, pid);
        assert_eq!(result.max_levels, 1);
    }

    #[test]
    fn test_descendants_with_config_monitor_zero_sample_rejected() {
        let config = DescendantsConfig {
            root_pid: std::process::id(),
            max_levels: Some(1),
            filter: None,
            cpu_mode: CpuMode::Monitor,
            sample_duration: Some(Duration::ZERO),
        };

        let err = descendants_with_config(config).unwrap_err();
        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
    }

    #[test]
    fn test_descendants_with_config_invalid_pid_zero_rejected_before_sampling() {
        let config = DescendantsConfig {
            root_pid: 0,
            max_levels: Some(1),
            filter: None,
            cpu_mode: CpuMode::Monitor,
            sample_duration: Some(Duration::from_secs(1)),
        };

        let err = descendants_with_config(config).unwrap_err();
        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
    }

    #[test]
    fn test_snapshot_json_output() {
        let snap = snapshot().unwrap();
        let json = serde_json::to_string_pretty(&snap).unwrap();

        // Verify JSON structure
        assert!(json.contains("\"schema_id\""));
        assert!(json.contains("\"timestamp\""));
        assert!(json.contains("\"processes\""));
        assert!(json.contains(PROCESS_INFO_V1));
    }

    fn test_process(pid: u32, ppid: u32, name: &str) -> ProcessInfo {
        ProcessInfo {
            pid,
            ppid,
            name: name.to_string(),
            user: None,
            cpu_percent: 0.0,
            memory_kb: 0,
            elapsed_seconds: 0,
            start_time_unix_ms: None,
            exe_path: None,
            state: ProcessState::Running,
            cmdline: vec![],
            env: None,
            thread_count: None,
        }
    }

    fn test_descendants_tree() -> DescendantsResult {
        DescendantsResult {
            schema_id: DESCENDANTS_RESULT_V1,
            root_pid: 10,
            max_levels: 10,
            levels: vec![
                DescendantsLevel {
                    level: 1,
                    processes: vec![test_process(11, 10, "helper"), test_process(12, 10, "db")],
                },
                DescendantsLevel {
                    level: 2,
                    processes: vec![
                        test_process(13, 11, "child-a"),
                        test_process(14, 12, "child-b"),
                    ],
                },
            ],
            total_found: 4,
            matched_by_filter: 4,
            timestamp: "1970-01-01T00:00:00Z".to_string(),
            platform: get_platform(),
        }
    }

    fn spawn_sleep_child() -> Child {
        #[cfg(unix)]
        {
            Command::new("sleep")
                .arg("30")
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .expect("spawn sleep child")
        }

        #[cfg(windows)]
        {
            Command::new("cmd")
                .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .expect("spawn ping child")
        }
    }

    fn guard_step_retry(config: &GuardConfig, attempts: usize, delay_ms: u64) -> GuardEvent {
        let mut last = None;
        for attempt in 0..attempts {
            let event = guard_step(config.clone()).expect("guard_step should succeed");
            let ready = if config.action_enabled {
                event.targeted > 0 && (event.killed > 0 || event.failed > 0)
            } else {
                true
            };
            if ready {
                return event;
            }
            last = Some(event);
            if attempt + 1 < attempts {
                thread::sleep(Duration::from_millis(delay_ms));
            }
        }
        last.expect("guard_step retry should record an event")
    }

    #[test]
    fn test_select_descendant_targets_non_cascade() {
        let result = test_descendants_tree();
        let filter = ProcessFilter {
            name_contains: Some("helper".to_string()),
            ..Default::default()
        };

        let targets = select_descendant_targets(&result, Some(&filter), false);
        assert_eq!(targets, vec![11]);
    }

    #[test]
    fn test_select_descendant_targets_cascade() {
        let result = test_descendants_tree();
        let filter = ProcessFilter {
            name_contains: Some("helper".to_string()),
            ..Default::default()
        };

        let targets = select_descendant_targets(&result, Some(&filter), true);
        assert_eq!(targets, vec![11, 13]);
    }

    #[test]
    fn test_guard_step_action_disabled_emits_event() {
        let cfg = GuardConfig {
            rule: GuardRule {
                root_pid: std::process::id(),
                max_levels: 1,
                filter: None,
                cpu_mode: CpuMode::Lifetime,
                sample_duration: None,
            },
            action: GuardAction::KillDescendants {
                signal: 15,
                cascade: false,
            },
            action_enabled: false,
            max_targets: 32,
        };

        let event = guard_step(cfg).unwrap();
        assert_eq!(event.schema_id, GUARD_EVENT_V1);
        assert_eq!(event.targeted, 0);
        assert_eq!(event.killed, 0);
        assert_eq!(event.failed, 0);
        assert!(event.warnings.iter().any(|w| w.contains("action disabled")));
    }

    #[test]
    fn test_guard_step_rejects_zero_max_targets() {
        let cfg = GuardConfig {
            rule: GuardRule {
                root_pid: std::process::id(),
                max_levels: 1,
                filter: None,
                cpu_mode: CpuMode::Lifetime,
                sample_duration: None,
            },
            action: GuardAction::KillDescendants {
                signal: 15,
                cascade: false,
            },
            action_enabled: false,
            max_targets: 0,
        };

        let err = guard_step(cfg).unwrap_err();
        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
    }

    #[test]
    fn test_guard_step_action_enabled_kills_targeted_child() {
        let mut child = spawn_sleep_child();
        let child_pid = child.id();

        let mut child_visible = false;
        for _ in 0..20 {
            let desc = descendants_with_config(DescendantsConfig {
                root_pid: std::process::id(),
                max_levels: Some(1),
                filter: Some(ProcessFilter {
                    pid_in: Some(vec![child_pid]),
                    ..Default::default()
                }),
                cpu_mode: CpuMode::Lifetime,
                sample_duration: None,
            })
            .unwrap();
            if desc.matched_by_filter >= 1 {
                child_visible = true;
                break;
            }
            thread::sleep(Duration::from_millis(50));
        }
        assert!(child_visible, "expected spawned child to be visible");

        let cfg = GuardConfig {
            rule: GuardRule {
                root_pid: std::process::id(),
                max_levels: 1,
                filter: Some(ProcessFilter {
                    pid_in: Some(vec![child_pid]),
                    ..Default::default()
                }),
                cpu_mode: CpuMode::Lifetime,
                sample_duration: None,
            },
            action: GuardAction::KillDescendants {
                signal: 15,
                cascade: false,
            },
            action_enabled: true,
            max_targets: 8,
        };

        let event = guard_step_retry(&cfg, 10, 100);
        assert_eq!(event.targeted, 1);
        assert_eq!(event.killed, 1);
        assert_eq!(event.failed, 0);

        let mut exited = false;
        for _ in 0..20 {
            if let Some(_status) = child.try_wait().expect("poll child exit") {
                exited = true;
                break;
            }
            thread::sleep(Duration::from_millis(100));
        }
        if !exited {
            let _ = child.kill();
            let _ = child.wait();
        }
        assert!(exited, "guard_step should terminate targeted child");
    }

    #[test]
    fn test_guard_step_action_enabled_applies_max_targets_cap() {
        let mut child_a = spawn_sleep_child();
        let mut child_b = spawn_sleep_child();
        let pids = vec![child_a.id(), child_b.id()];

        // Wait until both children are discoverable as direct descendants.
        let mut both_visible = false;
        for _ in 0..20 {
            let desc = descendants_with_config(DescendantsConfig {
                root_pid: std::process::id(),
                max_levels: Some(1),
                filter: Some(ProcessFilter {
                    pid_in: Some(pids.clone()),
                    ..Default::default()
                }),
                cpu_mode: CpuMode::Lifetime,
                sample_duration: None,
            })
            .unwrap();
            if desc.matched_by_filter >= 2 {
                both_visible = true;
                break;
            }
            thread::sleep(Duration::from_millis(50));
        }
        assert!(both_visible, "expected both spawned children to be visible");

        let cfg = GuardConfig {
            rule: GuardRule {
                root_pid: std::process::id(),
                max_levels: 1,
                filter: Some(ProcessFilter {
                    pid_in: Some(pids.clone()),
                    ..Default::default()
                }),
                cpu_mode: CpuMode::Lifetime,
                sample_duration: None,
            },
            action: GuardAction::KillDescendants {
                signal: 15,
                cascade: false,
            },
            action_enabled: true,
            max_targets: 1,
        };

        let event = guard_step_retry(&cfg, 10, 100);

        assert_eq!(event.matched, 2);
        assert_eq!(event.targeted, 1);
        assert_eq!(event.killed, 1);
        assert_eq!(event.failed, 0);
        assert!(
            event
                .warnings
                .iter()
                .any(|w| w.contains("target count capped at max_targets=1")),
            "expected max_targets cap warning, got: {:?}",
            event.warnings
        );

        // Exactly one process should exit quickly; the other remains until cleanup.
        let mut exited_count = 0;
        for _ in 0..20 {
            exited_count = 0;
            if child_a.try_wait().expect("poll child A").is_some() {
                exited_count += 1;
            }
            if child_b.try_wait().expect("poll child B").is_some() {
                exited_count += 1;
            }
            if exited_count >= 1 {
                break;
            }
            thread::sleep(Duration::from_millis(100));
        }
        assert!(
            exited_count >= 1,
            "expected at least one child to exit after capped guard_step kill"
        );

        for child in [&mut child_a, &mut child_b] {
            if child.try_wait().expect("final poll").is_none() {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
    }

    #[test]
    fn test_ancestors_self() {
        let pid = std::process::id();
        let result = ancestors(pid, 64, ProcessOptions::default()).unwrap();

        assert_eq!(result.schema_id, ANCESTORS_RESULT_V1);
        assert_eq!(result.pid, pid);
        assert!(
            !result.chain.is_empty(),
            "chain should include at least self"
        );
        assert_eq!(
            result.chain[0].pid, pid,
            "first element should be starting PID"
        );

        // Chain should have at least 2 elements (self + parent)
        assert!(
            result.chain.len() >= 2,
            "chain should include at least self and parent, got {}",
            result.chain.len()
        );
    }

    #[test]
    fn test_ancestors_rejects_pid_zero() {
        let err = ancestors(0, 10, ProcessOptions::default()).unwrap_err();
        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
    }

    #[test]
    fn test_ancestors_nonexistent_pid() {
        let err = ancestors(99999999, 10, ProcessOptions::default()).unwrap_err();
        assert!(matches!(err, SysprimsError::NotFound { .. }));
    }

    #[test]
    fn test_ancestors_max_depth_zero() {
        let pid = std::process::id();
        let result = ancestors(pid, 0, ProcessOptions::default()).unwrap();

        // max_depth=0 means just the starting PID
        assert_eq!(result.chain.len(), 1);
        assert_eq!(result.chain[0].pid, pid);
    }
}