irontide-session 1.0.1

BitTorrent session management: peers, torrents, and piece selection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::unchecked_time_subtraction,
    reason = "M175: session-level counters/rates bounded by torrent count; time deltas use post-init Instants"
)]

//! `SessionHandle` / `SessionActor` — multi-torrent session manager.
//!
//! Actor model: `SessionHandle` is the cloneable public API (mpsc sender),
//! `SessionActor` is the single-owner event loop (internal).

use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use dashmap::DashMap;
use tokio::sync::{broadcast, mpsc, oneshot};

use tracing::{debug, info, warn};

use irontide_core::{DEFAULT_CHUNK_SIZE, Id20, Lengths, Magnet};
use irontide_dht::DhtHandle;
use irontide_storage::TorrentStorage;

use crate::alert::{Alert, AlertCategory, AlertKind, AlertStream, post_alert};
use crate::settings::Settings;
use crate::torrent::TorrentHandle;
use crate::types::{
    FileInfo, SessionStats, TorrentConfig, TorrentInfo, TorrentState, TorrentStats, TorrentSummary,
};

/// Shared global rate limiter bucket.
type SharedBucket = Arc<parking_lot::Mutex<crate::rate_limiter::TokenBucket>>;

/// Function signature for queue move operations (`move_up`, `move_down`, etc.).
type QueueMoveFn = fn(&mut [crate::queue::QueueEntry], Id20) -> Vec<(Id20, i32, i32)>;

/// Shared session-wide ban manager, accessed by `TorrentActors` via `Arc`.
pub(crate) type SharedBanManager = Arc<parking_lot::RwLock<crate::ban::BanManager>>;

/// Shared session-wide IP filter, accessed by `TorrentActors` via `Arc`.
pub(crate) type SharedIpFilter = Arc<parking_lot::RwLock<crate::ip_filter::IpFilter>>;

/// Result of loading resume state from disk (M161 Phase 4).
#[derive(Debug, Clone)]
pub struct ResumeLoadResult {
    /// Number of torrents successfully restored.
    pub restored: usize,
    /// Number of resume files skipped (duplicate, already exists).
    pub skipped: usize,
    /// Number of resume files that failed to load.
    pub failed: usize,
}

/// Source for a torrent add (M170).
///
/// Separated from [`AddTorrentParams`] so that the builder API can name
/// the source independently of the other knobs.
#[derive(Debug, Clone)]
pub enum AddSource {
    /// Magnet URI (BEP 9 metadata fetch required post-add).
    Magnet(String),
    /// Raw `.torrent` file bytes (auto-detects v1/v2/hybrid).
    Bytes(Vec<u8>),
}

/// Unified parameters for [`SessionHandle::add_torrent`] (M170).
///
/// Replaces the ad-hoc set of `add_magnet`, `add_magnet_uri`,
/// `add_torrent_bytes` call shapes with a single params struct. Callers
/// build the struct via the static constructors ([`magnet`] or [`bytes`])
/// and chain `.with_category()` / `.with_tags()` / `.with_download_dir()`
/// / `.paused()`.
///
/// Download-dir resolution (see `add_torrent`):
/// 1. `download_dir: Some(p)` wins, if set.
/// 2. Else, if `category: Some(name)` and the registry contains `name`,
///    the registry's `save_path` is used.
/// 3. Else, if `category: Some(name)` and the registry does NOT contain
///    `name`, the call fails with [`Error::CategoryNotFound`].
/// 4. Else, falls back to `Settings.download_dir`.
///
/// `skip_checking` is reserved for M171+ (qBt `skip_hash_check=true`).
///
/// [`magnet`]: Self::magnet
/// [`bytes`]: Self::bytes
#[derive(Debug, Clone)]
pub struct AddTorrentParams {
    /// The torrent source (magnet URI or raw .torrent bytes).
    pub source: AddSource,
    /// Optional qBt-compat category label resolved via the session's
    /// [`CategoryRegistry`](crate::CategoryRegistry) at add-time.
    pub category: Option<String>,
    /// M171: Per-torrent tags baked in at add time (qBt-compat). Multi-
    /// valued. An empty vec means "no tags" and is the default.
    pub tags: Vec<String>,
    /// Explicit download directory, overrides both category lookup and
    /// `Settings.download_dir` when `Some`.
    pub download_dir: Option<PathBuf>,
    /// Whether the torrent should be added in a paused state. `None` (the
    /// constructor default) means "use [`Settings::default_add_paused`]";
    /// `Some(v)` is an explicit per-call override. The resolution happens
    /// in `dispatch_add_torrent_m170` before the M170 post-add hooks run,
    /// so the actor sees a concrete `bool` either way.
    pub paused: Option<bool>,
    /// Reserved for M171+ — skip the initial re-hash on add.
    pub skip_checking: bool,
}

impl AddTorrentParams {
    /// Build a magnet-source add with default knobs.
    #[must_use]
    pub fn magnet(uri: impl Into<String>) -> Self {
        Self {
            source: AddSource::Magnet(uri.into()),
            category: None,
            tags: Vec::new(),
            download_dir: None,
            paused: None,
            skip_checking: false,
        }
    }

    /// Build a bytes-source add with default knobs.
    #[must_use]
    pub fn bytes(data: impl Into<Vec<u8>>) -> Self {
        Self {
            source: AddSource::Bytes(data.into()),
            category: None,
            tags: Vec::new(),
            download_dir: None,
            paused: None,
            skip_checking: false,
        }
    }

    /// Assign a category label to the torrent. The session resolves the
    /// name against its registry at add-time; unknown names error out.
    #[must_use]
    pub fn with_category(mut self, name: impl Into<String>) -> Self {
        self.category = Some(name.into());
        self
    }

    /// M171: Attach tags at add time. Tags are baked into the torrent's
    /// config before `TorrentActor::new`, so the first `stats()` call
    /// returns them — no post-add spawn race.
    #[must_use]
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Override the download directory for this torrent.
    #[must_use]
    pub fn with_download_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.download_dir = Some(dir.into());
        self
    }

    /// Toggle the paused-at-add flag. Wraps the explicit choice in `Some(_)`
    /// so the actor can distinguish "caller explicitly set this" from
    /// "caller did not touch it" (the latter falls back to
    /// [`Settings::default_add_paused`]).
    #[must_use]
    pub fn paused(mut self, paused: bool) -> Self {
        self.paused = Some(paused);
        self
    }

    /// Toggle the skip-initial-check flag (M171+).
    #[must_use]
    pub fn skip_checking(mut self, skip: bool) -> Self {
        self.skip_checking = skip;
        self
    }
}

/// Entry for a torrent managed by the session.
///
/// v0.173.1: the `meta: Option<TorrentMetaV1>` field was deleted. It was a
/// stale cache that was silently `None` forever for magnet-added torrents —
/// see the Class A archaeology in
/// `docs/plans/2026-04-22-irontide-v0.173.1-qbt-v2-bug-sweep.md`. Four reader
/// sites (`handle_torrent_info`, `handle_remove_torrent_with_files`, `is_private`,
/// `handle_ssl_incoming`) now query the `TorrentActor` via `handle.get_meta()`,
/// which is the single source of truth for torrent metadata.
struct TorrentEntry {
    handle: TorrentHandle,
    /// Queue position (-1 = not queued / not auto-managed).
    queue_position: i32,
    /// Whether the queue system controls this torrent.
    auto_managed: bool,
    /// When the torrent was last started/resumed (for startup grace period).
    started_at: Option<tokio::time::Instant>,
    /// EWMA-smoothed download rate for queue inactive classification.
    smoothed_download_rate: f64,
    /// EWMA-smoothed upload rate for queue inactive classification.
    smoothed_upload_rate: f64,
}

/// M223 — off-actor add-torrent result bundle.
///
/// `handle_add_torrent` (and the M170 path) split into two phases:
/// 1. **Prepare** — disk register, actor spawn. Runs in a `tokio::spawn`
///    task off the `SessionActor` recv loop, so concurrent adds do not
///    serialise the actor's per-command queue.
/// 2. **Commit** — mutating fixup on the actor: insert into
///    `self.torrents`, info-hash registry, queue position, alert, LSD
///    announce. Runs on the actor in response to a `CommitAddTorrent`
///    feedback command.
///
/// This bundle is the success-path payload of the prepare phase; the
/// commit phase consumes it and produces the caller-visible `Id20`.
/// `is_private` is precomputed from `meta.info.private` so the commit
/// arm needs no async query to honour BEP 27 (LSD must skip private
/// torrents).
struct PreparedAddTorrent {
    handle: TorrentHandle,
    info_hash: Id20,
    is_private: bool,
    /// M170 post-add hooks (category label + paused-on-add). `None` for
    /// the legacy `AddTorrent` path; `Some` only for the
    /// `AddTorrentM170` path which carries `AddTorrentParams`.
    m170_post: Option<M170PostAdd>,
}

/// M223 — M170 post-add side-effects deferred from the recv arm to the
/// commit arm. Both are applied via `apply_post_add_m170` after the
/// torrent is inserted into `self.torrents`.
struct M170PostAdd {
    category: Option<String>,
    paused: bool,
}

/// M223 — snapshot of session state needed by the off-actor add-torrent
/// prep phase. Built synchronously on the actor at the recv arm via
/// `SessionActor::build_add_torrent_prep_bundle`; consumed by the
/// spawned task that runs the heavy `disk_manager.register_torrent` +
/// `TorrentHandle::from_torrent` work without blocking the actor's
/// command queue.
struct AddTorrentPrepBundle {
    torrent_meta: irontide_core::TorrentMeta,
    storage_override: Option<Arc<dyn TorrentStorage>>,
    torrent_config: TorrentConfig,
    disk_manager: crate::disk::DiskManagerHandle,
    dht_v4_broadcast: irontide_dht::DhtBroadcast,
    dht_v6_broadcast: irontide_dht::DhtBroadcast,
    global_up: Option<SharedBucket>,
    global_down: Option<SharedBucket>,
    slot_tuner: crate::slot_tuner::SlotTuner,
    alert_tx: broadcast::Sender<Alert>,
    alert_mask: Arc<AtomicU32>,
    utp_socket: Option<irontide_utp::UtpSocket>,
    utp_socket_v6: Option<irontide_utp::UtpSocket>,
    ban_manager: SharedBanManager,
    ip_filter: SharedIpFilter,
    plugins: Arc<Vec<Box<dyn crate::extension::ExtensionPlugin>>>,
    sam_session: Option<Arc<crate::i2p::SamSession>>,
    ssl_manager: Option<Arc<crate::ssl_manager::SslManager>>,
    factory: Arc<crate::transport::NetworkFactory>,
    hash_pool: std::sync::Arc<crate::hash_pool::HashPool>,
    counters: Arc<crate::stats::SessionCounters>,
    m170_post: Option<M170PostAdd>,
}

impl TorrentEntry {
    /// Returns `true` if this torrent has the private flag set (BEP 27).
    ///
    /// v0.173.1: now queries the `TorrentActor` for current metadata. Magnet
    /// torrents previously silently returned `false` because the session
    /// cache (`TorrentEntry.meta`) was permanently `None` for them — BEP 27
    /// enforcement was bypassed and peer IPs leaked to DHT/LSD. This method
    /// returning `false` pre-metadata is still correct per the plan's
    /// Failure-Modes table: the info dict doesn't exist yet, so the flag
    /// cannot be enforced. Once metadata resolves, subsequent calls see the
    /// real `info.private` value.
    async fn is_private(&self) -> bool {
        match self.handle.get_meta().await {
            Ok(Some(meta)) => meta.info.private == Some(1),
            // Pre-metadata or actor shut down: treat as non-private. A magnet
            // that hasn't resolved yet can't enforce privacy per BEP 27 — the
            // flag lives in the info dict, which doesn't exist yet.
            _ => false,
        }
    }
}

/// Commands sent from `SessionHandle` to `SessionActor`.
enum SessionCommand {
    AddTorrent {
        meta: Box<irontide_core::TorrentMeta>,
        storage: Option<Arc<dyn TorrentStorage>>,
        download_dir: Option<PathBuf>,
        reply: oneshot::Sender<crate::Result<Id20>>,
    },
    /// M223 — internal feedback variant. Carries the result of off-actor
    /// `handle_add_torrent` work (TCP bind + disk register + actor spawn)
    /// back to the actor's recv loop for the mutating fixup
    /// (insert into `self.torrents` + queue position + alert + LSD).
    /// Decouples the actor recv loop from per-add latency so the
    /// parallel-7 POST tail does not stack linearly with already-added
    /// torrents. Not part of the public `SessionHandle` API — only
    /// `add_torrent_via_spawn` (the recv-arm helper) emits this variant.
    CommitAddTorrent {
        result: crate::Result<PreparedAddTorrent>,
        reply: oneshot::Sender<crate::Result<Id20>>,
    },
    AddMagnet {
        magnet: Magnet,
        download_dir: Option<PathBuf>,
        reply: oneshot::Sender<crate::Result<Id20>>,
    },
    RemoveTorrent {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    PauseTorrent {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    ResumeTorrent {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    ForceResumeTorrent {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    SetTorrentSeedRatio {
        info_hash: Id20,
        limit: Option<f64>,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    TorrentStats {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<TorrentStats>>,
    },
    TorrentInfo {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<TorrentInfo>>,
    },
    ListTorrents {
        reply: oneshot::Sender<Vec<Id20>>,
    },
    SessionStats {
        reply: oneshot::Sender<SessionStats>,
    },
    SaveTorrentResumeData {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<irontide_core::FastResumeData>>,
    },
    SaveSessionState {
        reply: oneshot::Sender<crate::Result<crate::persistence::SessionState>>,
    },
    /// Load and restore torrents from per-torrent resume files on disk (M161).
    LoadResumeState {
        reply: oneshot::Sender<crate::Result<ResumeLoadResult>>,
    },
    QueuePosition {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<i32>>,
    },
    SetQueuePosition {
        info_hash: Id20,
        pos: i32,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    QueuePositionUp {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    QueuePositionDown {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    QueuePositionTop {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    QueuePositionBottom {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    BanPeer {
        ip: IpAddr,
        reply: oneshot::Sender<()>,
    },
    UnbanPeer {
        ip: IpAddr,
        reply: oneshot::Sender<bool>,
    },
    BannedPeers {
        reply: oneshot::Sender<Vec<IpAddr>>,
    },
    SetIpFilter {
        filter: crate::ip_filter::IpFilter,
        reply: oneshot::Sender<()>,
    },
    GetIpFilter {
        reply: oneshot::Sender<crate::ip_filter::IpFilter>,
    },
    GetSettings {
        reply: oneshot::Sender<Settings>,
    },
    ApplySettings {
        settings: Box<Settings>,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    MoveTorrentStorage {
        info_hash: Id20,
        new_path: std::path::PathBuf,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    AddPeers {
        info_hash: Id20,
        peers: Vec<SocketAddr>,
        source: crate::peer_state::PeerSource,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    OpenFile {
        info_hash: Id20,
        file_index: usize,
        reply: oneshot::Sender<crate::Result<crate::streaming::FileStream>>,
    },
    ForceReannounce {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    TrackerList {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<crate::tracker_manager::TrackerInfo>>>,
    },
    /// M178 Lane B3 / TODO-2: `(pex_peer_count, lsd_peer_count)` for the
    /// given torrent. Used by qBt v2 trackers endpoint + GUI Trackers tab
    /// to populate the PeX/LSD pseudo-tracker rows with real counts.
    GetPeerSourceCounts {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<(usize, usize)>>,
    },
    /// Per-peer cumulative unchoke duration for a torrent. `None` reply
    /// when the torrent does not exist (explicit contract — distinguishes
    /// "torrent missing" from "torrent exists with empty map").
    QueryUnchokeDurations {
        info_hash: Id20,
        reply: oneshot::Sender<Option<std::collections::HashMap<SocketAddr, std::time::Duration>>>,
    },
    /// M178 Lane C: per-URL web-seed stats for the qBt v2 webseeds endpoint
    /// and the GUI HTTP Sources tab.
    GetWebSeedStats {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<irontide_core::WebSeedStats>>>,
    },
    Scrape {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Option<(String, irontide_tracker::ScrapeInfo)>>>,
    },
    SetFilePriority {
        info_hash: Id20,
        index: usize,
        priority: irontide_core::FilePriority,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    FilePriorities {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<irontide_core::FilePriority>>>,
    },
    SetDownloadLimit {
        info_hash: Id20,
        bytes_per_sec: u64,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    SetUploadLimit {
        info_hash: Id20,
        bytes_per_sec: u64,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    DownloadLimit {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<u64>>,
    },
    UploadLimit {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<u64>>,
    },
    SetSequentialDownload {
        info_hash: Id20,
        enabled: bool,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    IsSequentialDownload {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<bool>>,
    },
    SetSuperSeeding {
        info_hash: Id20,
        enabled: bool,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    IsSuperSeeding {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<bool>>,
    },
    /// Enable or disable user-requested seed-only mode for a torrent (M159).
    SetSeedMode {
        info_hash: Id20,
        enabled: bool,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    AddTracker {
        info_hash: Id20,
        url: String,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    ReplaceTrackers {
        info_hash: Id20,
        urls: Vec<String>,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Trigger a full piece verification (force recheck) for a torrent.
    ForceRecheck {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Rename a file within a torrent on disk.
    RenameFile {
        info_hash: Id20,
        file_index: usize,
        new_name: String,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Set per-torrent maximum connections (0 = use global default).
    SetMaxConnections {
        info_hash: Id20,
        limit: usize,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Get per-torrent maximum connection limit.
    MaxConnections {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<usize>>,
    },
    /// Set per-torrent maximum upload slots (unchoke slots).
    SetMaxUploads {
        info_hash: Id20,
        limit: usize,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Get per-torrent maximum upload slots (unchoke slots).
    MaxUploads {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<usize>>,
    },
    /// Get per-peer details for all connected peers of a torrent.
    GetPeerInfo {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<crate::types::PeerInfo>>>,
    },
    /// Get in-flight piece download status for a torrent.
    GetDownloadQueue {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<crate::types::PartialPieceInfo>>>,
    },
    /// Check whether a specific piece has been downloaded.
    HavePiece {
        info_hash: Id20,
        index: u32,
        reply: oneshot::Sender<crate::Result<bool>>,
    },
    /// Get per-piece availability counts from connected peers.
    PieceAvailability {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<u32>>>,
    },
    /// Get per-file bytes-downloaded progress.
    FileProgress {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<u64>>>,
    },
    /// Get the torrent's identity hashes (v1 and/or v2).
    InfoHashesQuery {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<irontide_core::InfoHashes>>,
    },
    /// Get the full v1 metainfo for a torrent.
    TorrentFile {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Option<irontide_core::TorrentMetaV1>>>,
    },
    /// Get the full v2 metainfo for a torrent.
    TorrentFileV2 {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Option<irontide_core::TorrentMetaV2>>>,
    },
    /// Force an immediate DHT announce for a torrent.
    ForceDhtAnnounce {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Force an immediate LSD announce for a torrent (session-level only).
    ForceLsdAnnounce {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Read all data for a specific piece from disk.
    ReadPiece {
        info_hash: Id20,
        index: u32,
        reply: oneshot::Sender<crate::Result<bytes::Bytes>>,
    },
    /// Flush the disk write cache for a torrent.
    FlushCache {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Check if a torrent handle is still valid (torrent exists and channel open).
    IsValid {
        info_hash: Id20,
        reply: oneshot::Sender<bool>,
    },
    /// Clear error state on a torrent.
    ClearError {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Get per-file open/mode status for a torrent.
    FileStatus {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<crate::types::FileStatus>>>,
    },
    /// Read the current torrent flags.
    Flags {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<crate::types::TorrentFlags>>,
    },
    /// Set (enable) the specified torrent flags.
    SetFlags {
        info_hash: Id20,
        flags: crate::types::TorrentFlags,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Unset (disable) the specified torrent flags.
    UnsetFlags {
        info_hash: Id20,
        flags: crate::types::TorrentFlags,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Immediately initiate a peer connection for a torrent.
    ConnectPeer {
        info_hash: Id20,
        addr: SocketAddr,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    DhtPutImmutable {
        value: Vec<u8>,
        reply: oneshot::Sender<crate::Result<Id20>>,
    },
    DhtGetImmutable {
        target: Id20,
        reply: oneshot::Sender<crate::Result<Option<Vec<u8>>>>,
    },
    DhtPutMutable {
        keypair_bytes: [u8; 32],
        value: Vec<u8>,
        seq: i64,
        salt: Vec<u8>,
        reply: oneshot::Sender<crate::Result<Id20>>,
    },
    #[allow(clippy::type_complexity)]
    DhtGetMutable {
        public_key: [u8; 32],
        salt: Vec<u8>,
        reply: oneshot::Sender<crate::Result<Option<(Vec<u8>, i64)>>>,
    },
    /// Save per-torrent resume files for all dirty torrents (M161).
    SaveResumeState {
        reply: oneshot::Sender<crate::Result<usize>>,
    },
    /// Trigger an immediate session stats snapshot and alert (M50).
    PostSessionStats,
    // ── M170: qBt v2 *arr-minimal surface ──
    /// Unified add entry (M170) — see `AddTorrentParams`.
    AddTorrentM170 {
        params: Box<AddTorrentParams>,
        reply: oneshot::Sender<crate::Result<Id20>>,
    },
    /// Create a new category with the given `save_path`.
    CreateCategory {
        name: String,
        save_path: PathBuf,
        reply: oneshot::Sender<Result<(), crate::category_manager::CategoryError>>,
    },
    /// Update the `save_path` on an existing category.
    EditCategory {
        name: String,
        save_path: PathBuf,
        reply: oneshot::Sender<Result<(), crate::category_manager::CategoryError>>,
    },
    /// Remove zero or more categories. Returns names actually removed.
    RemoveCategories {
        names: Vec<String>,
        reply: oneshot::Sender<Vec<String>>,
    },
    /// Snapshot the current category list.
    ListCategories {
        reply: oneshot::Sender<Vec<crate::category_manager::CategoryMetadata>>,
    },
    /// Create a batch of tags (M171). One reply slot per requested name
    /// so the caller can tell which were newly created vs already-present.
    CreateTags {
        names: Vec<String>,
        reply: oneshot::Sender<Vec<Result<(), crate::tag_manager::TagError>>>,
    },
    /// Remove zero or more tags (M171). Returns names actually removed;
    /// unknown names are tolerated (matches qBt idempotent `deleteTags`).
    DeleteTags {
        names: Vec<String>,
        reply: oneshot::Sender<Vec<String>>,
    },
    /// Snapshot the current tag list (M171). Sorted.
    ListTags {
        reply: oneshot::Sender<Vec<String>>,
    },
    /// Add the given tags to each torrent in `info_hashes` (M171).
    /// Unknown info hashes are silently skipped. The engine-layer
    /// command is a wholesale replacement, so each torrent's tag set
    /// is read, unioned with the requested additions, and replayed via
    /// `TorrentHandle::set_tags`.
    AddTagsToTorrents {
        info_hashes: Vec<Id20>,
        tags: Vec<String>,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Remove the given tags from each torrent in `info_hashes` (M171).
    /// Unknown info hashes are silently skipped.
    RemoveTagsFromTorrents {
        info_hashes: Vec<Id20>,
        tags: Vec<String>,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Remove a torrent and delete its on-disk files (qBt
    /// `deleteFiles=true`).
    RemoveTorrentWithFiles {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// M171 Lane B: snapshot the web seed URLs (BEP 19 + BEP 17 merged)
    /// for a specific torrent.
    GetWebSeeds {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<String>>>,
    },
    /// M171 Lane B: snapshot the per-piece state array as qBt codes
    /// (`0`/`1`/`2`) for a specific torrent.
    GetPieceStates {
        info_hash: Id20,
        reply: oneshot::Sender<crate::Result<Vec<u8>>>,
    },
    /// M171 Lane B: paginated piece hash list for a specific torrent.
    GetPieceHashes {
        info_hash: Id20,
        offset: u32,
        limit: u32,
        reply: oneshot::Sender<crate::Result<Vec<String>>>,
    },
    /// M171 D4: sum of routing-table sizes across the IPv4 and IPv6 DHT
    /// instances. Returns 0 when neither DHT is enabled.
    DhtNodeCount {
        reply: oneshot::Sender<usize>,
    },
    /// **TEST-ONLY (v0.173.2).** Inject info-dict bytes into a torrent's
    /// actor synchronously, returning only after the actor has processed
    /// it. Used by integration tests in `irontide-api` (A9) that exercise
    /// post-metadata HTTP surface without spinning up real peers.
    /// M187: collect per-torrent and per-peer debug state for diagnostics.
    DebugState {
        reply: oneshot::Sender<crate::types::DebugState>,
    },
    #[cfg(feature = "test-util")]
    TestInjectMetadata {
        info_hash: Id20,
        info_bytes: Vec<u8>,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    Shutdown,
}

impl SessionCommand {
    /// Static variant name for the `cmd` field of the M221.1a
    /// `session_cmd` tracing event. Stable across renames is *not* a
    /// goal — this is bench-instrumentation telemetry, so the variant
    /// identifier is the right label.
    fn name(&self) -> &'static str {
        match self {
            Self::AddTorrent { .. } => "AddTorrent",
            Self::CommitAddTorrent { .. } => "CommitAddTorrent",
            Self::AddMagnet { .. } => "AddMagnet",
            Self::RemoveTorrent { .. } => "RemoveTorrent",
            Self::PauseTorrent { .. } => "PauseTorrent",
            Self::ResumeTorrent { .. } => "ResumeTorrent",
            Self::ForceResumeTorrent { .. } => "ForceResumeTorrent",
            Self::SetTorrentSeedRatio { .. } => "SetTorrentSeedRatio",
            Self::TorrentStats { .. } => "TorrentStats",
            Self::TorrentInfo { .. } => "TorrentInfo",
            Self::ListTorrents { .. } => "ListTorrents",
            Self::SessionStats { .. } => "SessionStats",
            Self::SaveTorrentResumeData { .. } => "SaveTorrentResumeData",
            Self::SaveSessionState { .. } => "SaveSessionState",
            Self::LoadResumeState { .. } => "LoadResumeState",
            Self::QueuePosition { .. } => "QueuePosition",
            Self::SetQueuePosition { .. } => "SetQueuePosition",
            Self::QueuePositionUp { .. } => "QueuePositionUp",
            Self::QueuePositionDown { .. } => "QueuePositionDown",
            Self::QueuePositionTop { .. } => "QueuePositionTop",
            Self::QueuePositionBottom { .. } => "QueuePositionBottom",
            Self::BanPeer { .. } => "BanPeer",
            Self::UnbanPeer { .. } => "UnbanPeer",
            Self::BannedPeers { .. } => "BannedPeers",
            Self::SetIpFilter { .. } => "SetIpFilter",
            Self::GetIpFilter { .. } => "GetIpFilter",
            Self::GetSettings { .. } => "GetSettings",
            Self::ApplySettings { .. } => "ApplySettings",
            Self::MoveTorrentStorage { .. } => "MoveTorrentStorage",
            Self::AddPeers { .. } => "AddPeers",
            Self::OpenFile { .. } => "OpenFile",
            Self::ForceReannounce { .. } => "ForceReannounce",
            Self::TrackerList { .. } => "TrackerList",
            Self::GetPeerSourceCounts { .. } => "GetPeerSourceCounts",
            Self::QueryUnchokeDurations { .. } => "QueryUnchokeDurations",
            Self::GetWebSeedStats { .. } => "GetWebSeedStats",
            Self::Scrape { .. } => "Scrape",
            Self::SetFilePriority { .. } => "SetFilePriority",
            Self::FilePriorities { .. } => "FilePriorities",
            Self::SetDownloadLimit { .. } => "SetDownloadLimit",
            Self::SetUploadLimit { .. } => "SetUploadLimit",
            Self::DownloadLimit { .. } => "DownloadLimit",
            Self::UploadLimit { .. } => "UploadLimit",
            Self::SetSequentialDownload { .. } => "SetSequentialDownload",
            Self::IsSequentialDownload { .. } => "IsSequentialDownload",
            Self::SetSuperSeeding { .. } => "SetSuperSeeding",
            Self::IsSuperSeeding { .. } => "IsSuperSeeding",
            Self::SetSeedMode { .. } => "SetSeedMode",
            Self::AddTracker { .. } => "AddTracker",
            Self::ReplaceTrackers { .. } => "ReplaceTrackers",
            Self::ForceRecheck { .. } => "ForceRecheck",
            Self::RenameFile { .. } => "RenameFile",
            Self::SetMaxConnections { .. } => "SetMaxConnections",
            Self::MaxConnections { .. } => "MaxConnections",
            Self::SetMaxUploads { .. } => "SetMaxUploads",
            Self::MaxUploads { .. } => "MaxUploads",
            Self::GetPeerInfo { .. } => "GetPeerInfo",
            Self::GetDownloadQueue { .. } => "GetDownloadQueue",
            Self::HavePiece { .. } => "HavePiece",
            Self::PieceAvailability { .. } => "PieceAvailability",
            Self::FileProgress { .. } => "FileProgress",
            Self::InfoHashesQuery { .. } => "InfoHashesQuery",
            Self::TorrentFile { .. } => "TorrentFile",
            Self::TorrentFileV2 { .. } => "TorrentFileV2",
            Self::ForceDhtAnnounce { .. } => "ForceDhtAnnounce",
            Self::ForceLsdAnnounce { .. } => "ForceLsdAnnounce",
            Self::ReadPiece { .. } => "ReadPiece",
            Self::FlushCache { .. } => "FlushCache",
            Self::IsValid { .. } => "IsValid",
            Self::ClearError { .. } => "ClearError",
            Self::FileStatus { .. } => "FileStatus",
            Self::Flags { .. } => "Flags",
            Self::SetFlags { .. } => "SetFlags",
            Self::UnsetFlags { .. } => "UnsetFlags",
            Self::ConnectPeer { .. } => "ConnectPeer",
            Self::DhtPutImmutable { .. } => "DhtPutImmutable",
            Self::DhtGetImmutable { .. } => "DhtGetImmutable",
            Self::DhtPutMutable { .. } => "DhtPutMutable",
            Self::DhtGetMutable { .. } => "DhtGetMutable",
            Self::SaveResumeState { .. } => "SaveResumeState",
            Self::PostSessionStats => "PostSessionStats",
            Self::AddTorrentM170 { .. } => "AddTorrentM170",
            Self::CreateCategory { .. } => "CreateCategory",
            Self::EditCategory { .. } => "EditCategory",
            Self::RemoveCategories { .. } => "RemoveCategories",
            Self::ListCategories { .. } => "ListCategories",
            Self::CreateTags { .. } => "CreateTags",
            Self::DeleteTags { .. } => "DeleteTags",
            Self::ListTags { .. } => "ListTags",
            Self::AddTagsToTorrents { .. } => "AddTagsToTorrents",
            Self::RemoveTagsFromTorrents { .. } => "RemoveTagsFromTorrents",
            Self::RemoveTorrentWithFiles { .. } => "RemoveTorrentWithFiles",
            Self::GetWebSeeds { .. } => "GetWebSeeds",
            Self::GetPieceStates { .. } => "GetPieceStates",
            Self::GetPieceHashes { .. } => "GetPieceHashes",
            Self::DhtNodeCount { .. } => "DhtNodeCount",
            Self::DebugState { .. } => "DebugState",
            #[cfg(feature = "test-util")]
            Self::TestInjectMetadata { .. } => "TestInjectMetadata",
            Self::Shutdown => "Shutdown",
        }
    }
}

/// Channel sender that timestamps each outgoing `SessionCommand` with
/// the instant it was enqueued, so the actor's receive arm can split
/// `queue_wait_ms` (sender → receiver) from `handler_ms` (dispatch).
/// M221.1a — feeds the parallel-7 bench harness.
#[derive(Clone)]
struct SessionCmdSender(mpsc::Sender<(tokio::time::Instant, SessionCommand)>);

impl SessionCmdSender {
    async fn send(
        &self,
        cmd: SessionCommand,
    ) -> Result<(), mpsc::error::SendError<SessionCommand>> {
        let sent_at = tokio::time::Instant::now();
        self.0
            .send((sent_at, cmd))
            .await
            .map_err(|e| mpsc::error::SendError(e.0.1))
    }
}

/// Classification of settings-patch fields into "took effect immediately"
/// versus "requires session restart to apply".
///
/// Returned by [`SessionHandle::apply_settings_classified`]. The
/// `restart_required` list is surfaced as the `X-IronTide-Restart-Pending`
/// response header by the qBt v2 `setPreferences` handler so clients can
/// render a "restart to apply" UX affordance (M171 D3.5).
#[derive(Debug, Clone, Default)]
pub struct AppliedSettings {
    /// Settings fields that changed and took effect immediately.
    pub immediate: Vec<&'static str>,
    /// Settings fields that changed but require a session restart to
    /// activate (sub-actor reconfig, listen-socket rebind, DHT/LSD/PEX
    /// startup, encryption-handshake policy, anonymous-mode peer ID, etc.).
    pub restart_required: Vec<&'static str>,
}

/// Classify fields whose runtime application is immediate — rate limiters
/// (M166), alert mask, peer cap, and enum/flag state that peer/torrent
/// actors re-read on every tick.
///
/// **M173 Lane B (B10) — graduation:** `listen_port`, `dht`, and `lsd`
/// move from `restart_required` to `immediate`. The transactional
/// apply pipeline (B1) now performs the live reconfig:
/// - `listen_port`: TCP listener rebind + uTP `shutdown_and_wait` + new
///   bind + NAT `refresh_for_port` (B2/B4/B8 primitives).
/// - dht: `shutdown_and_wait` (B7 persists routing table) + new
///   `DhtHandle` + `DhtBroadcast::replace` fans out to torrents (B5+B6).
/// - lsd: `shutdown_and_wait` (B9 multicast fd guard) + new actor.
///
/// `[REGRESSION CRITICAL]`: the wire-format pinned test in
/// `crates/irontide-api/tests/qbt_v2_set_preferences.rs` asserts the
/// EXACT field-name set here. Downstream *arr clients parse the
/// `X-IronTide-Restart-Pending` header — a silent rename = downstream
/// regression. Add new fields with care; never reuse a field name.
fn classify_immediate(old: &Settings, new: &Settings) -> Vec<&'static str> {
    let mut v = Vec::new();
    if old.download_rate_limit != new.download_rate_limit {
        v.push("dl_limit");
    }
    if old.upload_rate_limit != new.upload_rate_limit {
        v.push("up_limit");
    }
    if old.max_peers_per_torrent != new.max_peers_per_torrent {
        v.push("max_connec");
    }
    if old.max_ratio_action != new.max_ratio_action {
        v.push("max_ratio_act");
    }
    if old.create_subfolder != new.create_subfolder {
        v.push("create_subfolder_enabled");
    }
    if old.auto_manage_torrents != new.auto_manage_torrents {
        v.push("auto_tmm_enabled");
    }
    if old.queueing_enabled != new.queueing_enabled {
        v.push("queueing_enabled");
    }
    if old.seed_ratio_limit != new.seed_ratio_limit {
        v.push("max_ratio");
    }
    // M173 Lane B (B10): graduate listen_port, dht, lsd from
    // restart_required → immediate. The transactional apply pipeline
    // (B1) actually performs the live reconfig.
    if old.listen_port != new.listen_port {
        v.push("listen_port");
    }
    if old.enable_dht != new.enable_dht {
        v.push("dht");
    }
    if old.enable_lsd != new.enable_lsd {
        v.push("lsd");
    }
    // M172a Lane B: CSRF + reverse-proxy settings take effect immediately
    // because the middleware re-reads Settings per-request (no actor state).
    // Each qBt wire field name mirrors qBt's own preferences keys so the
    // X-IronTide-Restart-Pending header is human-readable on the client.
    if old.qbt_compat.csrf_protection_enabled != new.qbt_compat.csrf_protection_enabled {
        v.push("web_ui_csrf_protection_enabled");
    }
    if old.qbt_compat.host_header_validation_enabled
        != new.qbt_compat.host_header_validation_enabled
    {
        v.push("web_ui_host_header_validation_enabled");
    }
    if old.qbt_compat.web_ui_reverse_proxy_enabled != new.qbt_compat.web_ui_reverse_proxy_enabled {
        v.push("web_ui_reverse_proxy_enabled");
    }
    if old.qbt_compat.web_ui_reverse_proxies_list != new.qbt_compat.web_ui_reverse_proxies_list {
        v.push("web_ui_reverse_proxies_list");
    }
    // M172a Lane C: brute-force ban settings all land as immediate —
    // the auth handler reads them from the live `Settings` snapshot per
    // request, so the next login reflects the new thresholds without
    // a session restart. M225 closes the M173+ shrink path:
    // `brute_force_registry_capacity` decreases trigger
    // `BruteForceRegistry::shrink_preserving_recent_bans` from the
    // qBt v2 `setPreferences` handler (two-tier preservation — every
    // active ban survives regardless of new cap; partials fill the
    // remainder by `last_touch` descending).
    if old.qbt_compat.max_failed_auth_count != new.qbt_compat.max_failed_auth_count {
        v.push("web_ui_max_auth_fail_count");
    }
    if old.qbt_compat.ban_duration_secs != new.qbt_compat.ban_duration_secs {
        v.push("web_ui_ban_duration");
    }
    if old.qbt_compat.bypass_local_auth != new.qbt_compat.bypass_local_auth {
        v.push("bypass_local_auth");
    }
    if old.qbt_compat.bypass_auth_subnet_whitelist != new.qbt_compat.bypass_auth_subnet_whitelist {
        v.push("bypass_auth_subnet_whitelist");
    }
    if old.qbt_compat.brute_force_registry_capacity != new.qbt_compat.brute_force_registry_capacity
    {
        v.push("brute_force_registry_capacity");
    }
    // M214: global connection cap. Accept-loop reads from the live `Settings`
    // snapshot on each tick — no caller cache to invalidate. The
    // `max_peers_per_torrent` field is already classified above as "max_connec"
    // (qBt's legacy alias). We introduce "max_connec_global" to disambiguate
    // the workspace-wide cap from the per-torrent one.
    if old.max_connections_global != new.max_connections_global {
        v.push("max_connec_global");
    }
    // M224: per-torrent upload slot cap. Propagated to in-flight torrents via
    // `SettingsDelta::max_uploads_per_torrent` and `apply_delta`; the choker's
    // unchoke selection at next tick respects the new cap. Wire alias is
    // qBt's `max_uploads_per_torrent` for the X-IronTide-Restart-Pending
    // header.
    if old.max_uploads_per_torrent != new.max_uploads_per_torrent {
        v.push("max_uploads_per_torrent");
    }
    // M215: seed-time limits. Wire format is minutes; storage is seconds.
    // Propagated to in-flight torrents via `SettingsDelta::seed_time_limit_secs`
    // and `apply_delta` at `torrent_state.rs:1633-1638` — live, no restart.
    // Field name mirrors qBt's wire convention (`max_seeding_time` /
    // `max_inactive_seeding_time`) for client-readable
    // `X-IronTide-Restart-Pending`.
    if old.seed_time_limit_secs != new.seed_time_limit_secs {
        v.push("max_seeding_time");
    }
    if old.inactive_seed_time_limit_secs != new.inactive_seed_time_limit_secs {
        v.push("max_inactive_seeding_time");
    }
    if old.save_resume_interval_secs != new.save_resume_interval_secs {
        v.push("save_resume_interval");
    }
    if old.hashing_threads != new.hashing_threads {
        v.push("hashing_threads");
    }
    if old.ip_filter_enabled != new.ip_filter_enabled {
        v.push("ip_filter_enabled");
    }
    // M226: Notifications / paths / watched folder / network — all immediate.
    // Most fields are stored-only (subsystem wiring deferred per plan
    // §NOT-in-scope), but they MUST land as immediate so the GUI's
    // not-yet-active toggles in M227 don't surface a restart-required
    // header on the wire.
    if old.notify_on_complete != new.notify_on_complete {
        v.push("notify_on_complete");
    }
    if old.notify_on_error != new.notify_on_error {
        v.push("notify_on_error");
    }
    if old.on_complete_program != new.on_complete_program {
        v.push("on_complete_program");
    }
    if old.use_incomplete_dir != new.use_incomplete_dir {
        v.push("use_incomplete_dir");
    }
    if old.incomplete_dir != new.incomplete_dir {
        v.push("incomplete_dir");
    }
    if old.default_skip_hash_check != new.default_skip_hash_check {
        v.push("default_skip_hash_check");
    }
    if old.incomplete_extension_enabled != new.incomplete_extension_enabled {
        v.push("incomplete_extension_enabled");
    }
    if old.watched_folder != new.watched_folder {
        v.push("watched_folder");
    }
    if old.delete_torrent_after_add != new.delete_torrent_after_add {
        v.push("delete_torrent_after_add");
    }
    if old.move_completed_enabled != new.move_completed_enabled {
        v.push("move_completed_enabled");
    }
    if old.move_completed_to != new.move_completed_to {
        v.push("move_completed_to");
    }
    if old.ip_filter_auto_refresh != new.ip_filter_auto_refresh {
        v.push("ip_filter_auto_refresh");
    }
    if old.web_ui_https_enabled != new.web_ui_https_enabled {
        v.push("web_ui_https_enabled");
    }
    if old.network_interface != new.network_interface {
        v.push("network_interface");
    }
    if old.default_add_paused != new.default_add_paused {
        v.push("default_add_paused");
    }
    v
}

/// Classify fields whose runtime application STILL requires a session
/// restart, post-M173 Lane B graduation:
/// - PEX (peer announcement on next handshake — propagation cost)
/// - encryption handshake policy (MSE bytes-on-wire)
/// - anonymous-mode peer ID
/// - download-dir root (in-flight torrents retain their original
///   `save_path`; only `next-add` changes — this is intentional, not
///   a bug, see HA spec non-goals)
///
/// **M173 Lane B (B10) — graduation:** `listen_port`, `dht`, `lsd` were
/// removed from this list; they now appear in [`classify_immediate`].
/// The transactional apply pipeline (B1) performs their live reconfig.
fn classify_restart_required(old: &Settings, new: &Settings) -> Vec<&'static str> {
    let mut v = Vec::new();
    if old.enable_pex != new.enable_pex {
        v.push("pex");
    }
    if old.encryption_mode != new.encryption_mode {
        v.push("encryption");
    }
    if old.anonymous_mode != new.anonymous_mode {
        v.push("anonymous_mode");
    }
    if old.download_dir != new.download_dir {
        v.push("save_path");
    }
    // v0.187.3 / 2A: Web UI listen socket — restart-required because the
    // axum listener binds at process startup, not on reconfig (the M173
    // transactional apply scaffold only covers the BitTorrent listen port).
    if old.qbt_compat.port != new.qbt_compat.port {
        v.push("webui_port");
    }
    if old.qbt_compat.bind_address != new.qbt_compat.bind_address {
        v.push("webui_bind");
    }
    // M214: NAT traversal toggles. `irontide_nat::NatHandle::start` consumes a
    // `NatConfig` once; the actor has no `update_config` primitive. Hot-toggle
    // would require shutdown+restart of the NAT actor (M173 Lane B precedent
    // for listen_port). M214 ships the honest round-trip; live reconfig defers.
    if old.enable_upnp != new.enable_upnp {
        v.push("upnp");
    }
    if old.enable_natpmp != new.enable_natpmp {
        v.push("natpmp");
    }
    // M214: proxy settings. Outbound peer/tracker connections cache proxy
    // configuration at handshake time. Hot-changing mid-session would mix
    // pre-/post-change traffic on torn-down sockets vs new sockets. qBt's
    // reference behaviour is restart-required for the same reason.
    if old.proxy.proxy_type != new.proxy.proxy_type {
        v.push("proxy_type");
    }
    if old.proxy.hostname != new.proxy.hostname {
        v.push("proxy_ip");
    }
    if old.proxy.port != new.proxy.port {
        v.push("proxy_port");
    }
    if old.proxy.username != new.proxy.username {
        v.push("proxy_username");
    }
    if old.proxy.password != new.proxy.password {
        v.push("proxy_password");
    }
    if old.proxy.proxy_peer_connections != new.proxy.proxy_peer_connections {
        v.push("proxy_peer_connections");
    }
    if old.proxy.proxy_hostnames != new.proxy.proxy_hostnames {
        v.push("proxy_hostnames");
    }
    if old.force_proxy != new.force_proxy {
        v.push("force_proxy");
    }
    v
}

/// Cloneable handle for interacting with a running session.
#[derive(Clone)]
pub struct SessionHandle {
    cmd_tx: SessionCmdSender,
    alert_tx: broadcast::Sender<Alert>,
    alert_mask: Arc<AtomicU32>,
    counters: Arc<crate::stats::SessionCounters>,
    /// Network transport factory (M51). Used by future simulation tasks.
    #[allow(dead_code)]
    factory: Arc<crate::transport::NetworkFactory>,
    /// M173 Lane B (B11): in-flight guard for concurrent
    /// `apply_settings` / `apply_settings_classified` calls. The
    /// guard is acquired BEFORE the command is queued; if a
    /// previous reconfig is still in flight, the second caller hits
    /// `Error::ConcurrentReconfig` (HTTP 409 Conflict on the qBt
    /// v2 `setPreferences` endpoint) instead of racing the first
    /// caller's read-modify-write.
    reconfig_in_flight: crate::apply::ReconfigInFlight,
}

impl SessionHandle {
    /// Start a new session with the given settings and no plugins.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn start(settings: Settings) -> crate::Result<Self> {
        Self::start_with_plugins(settings, Arc::new(Vec::new())).await
    }

    /// Start a new session with a custom disk I/O backend and no plugins.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn start_with_backend(
        settings: Settings,
        backend: Arc<dyn crate::disk_backend::DiskIoBackend>,
    ) -> crate::Result<Self> {
        Self::start_with_plugins_and_backend(settings, Arc::new(Vec::new()), backend).await
    }

    /// Start a new session with the given settings and extension plugins.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn start_with_plugins(
        settings: Settings,
        plugins: Arc<Vec<Box<dyn crate::extension::ExtensionPlugin>>>,
    ) -> crate::Result<Self> {
        let disk_config = crate::disk::DiskConfig::from(&settings);
        let backend = crate::disk_backend::create_backend_from_config(&disk_config);
        Self::start_with_plugins_and_backend(settings, plugins, backend).await
    }

    /// Start a new session with the given settings, extension plugins, and
    /// a custom disk I/O backend.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn start_with_plugins_and_backend(
        settings: Settings,
        plugins: Arc<Vec<Box<dyn crate::extension::ExtensionPlugin>>>,
        backend: Arc<dyn crate::disk_backend::DiskIoBackend>,
    ) -> crate::Result<Self> {
        Self::start_full(
            settings,
            plugins,
            backend,
            Arc::new(crate::transport::NetworkFactory::tokio()),
        )
        .await
    }

    /// Start a new session with the given settings and a custom transport factory.
    ///
    /// Uses default plugins (none) and default disk backend.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn start_with_transport(
        settings: Settings,
        factory: Arc<crate::transport::NetworkFactory>,
    ) -> crate::Result<Self> {
        let disk_config = crate::disk::DiskConfig::from(&settings);
        let backend = crate::disk_backend::create_backend_from_config(&disk_config);
        Self::start_full(settings, Arc::new(Vec::new()), backend, factory).await
    }

    /// Start a new session with all customizable parameters.
    ///
    /// This is the most general constructor — all other `start_*` variants
    /// delegate to this method. The `factory` parameter controls how TCP
    /// listeners and connections are created: use [`crate::transport::NetworkFactory::tokio()`]
    /// for real networking or a custom factory for simulation.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn start_full(
        settings: Settings,
        plugins: Arc<Vec<Box<dyn crate::extension::ExtensionPlugin>>>,
        backend: Arc<dyn crate::disk_backend::DiskIoBackend>,
        factory: Arc<crate::transport::NetworkFactory>,
    ) -> crate::Result<Self> {
        let mut settings = settings;

        // Force proxy mode: all connections must go through proxy.
        if settings.force_proxy {
            if settings.proxy.proxy_type == crate::proxy::ProxyType::None {
                return Err(crate::Error::Config(
                    "force_proxy requires a proxy to be configured".into(),
                ));
            }
            settings.enable_upnp = false;
            settings.enable_natpmp = false;
            settings.enable_dht = false;
            settings.enable_lsd = false;
        }

        // Anonymous mode: suppress identity and disable discovery.
        if settings.anonymous_mode {
            settings.enable_dht = false;
            settings.enable_lsd = false;
            settings.enable_upnp = false;
            settings.enable_natpmp = false;
        }

        // M172a A3/C2: legacy-plaintext → argon2id migration on the in-memory
        // Settings. The config file rewrite is a separate concern handled by
        // the CLI layer (see irontide_config::migrate_qbt_credentials_in_file)
        // — we only mutate the runtime copy here so login always uses PHC
        // hashes regardless of on-disk state.
        //
        // Failure semantics (C2): on hash error we keep the plaintext in
        // memory so verify still works, and emit a WARN. The daemon continues
        // — a startup crash would brick an operator on a transient OS error.
        match crate::settings::migrate_qbt_credentials(&mut settings.qbt_compat) {
            Ok(crate::settings::QbtCredentialMigration::Upgraded) => {
                warn!(
                    "qbt_compat: legacy plaintext password migrated to argon2id in memory — \
                     persist via `irontide_config::migrate_qbt_credentials_in_file` or the \
                     next config-touching CLI command to remove the plaintext from disk"
                );
            }
            Ok(crate::settings::QbtCredentialMigration::NoOp) => {}
            Err(e) => {
                warn!(
                    error = %e,
                    "qbt_compat: in-memory password migration failed — continuing with \
                     legacy plaintext; retry on next daemon start"
                );
            }
        }

        let (raw_cmd_tx, cmd_rx) = mpsc::channel::<(tokio::time::Instant, SessionCommand)>(256);
        let cmd_tx = SessionCmdSender(raw_cmd_tx);

        // Alert broadcast channel
        let (alert_tx, _) = broadcast::channel(settings.alert_channel_size);
        let alert_mask = Arc::new(AtomicU32::new(settings.alert_mask.bits()));

        // M226 Step 5: spawn the engine-side OS notification dispatcher.
        // The dispatcher subscribes to the alert broadcast BEFORE any
        // TorrentAdded can fire (H5 — eliminates the missed-cache race
        // on first add), reads `notify_on_complete` / `notify_on_error`
        // live from a watch channel mirrored by `handle_apply_settings`,
        // and exits when either the `notification_shutdown_tx` field on
        // `SessionActor` drops OR the alert broadcast closes. Production
        // uses `LibNotifySink` (wraps `notify-rust` via spawn_blocking);
        // first D-Bus failure logs a single WARN then degrades silently.
        let (notification_settings_tx, notification_settings_rx) =
            tokio::sync::watch::channel(settings.clone());
        let (notification_shutdown_tx, notification_shutdown_rx) = oneshot::channel::<()>();
        let _notification_dispatcher_handle = crate::notification::spawn_notification_dispatcher(
            crate::notification::DispatcherOptions {
                sink: Box::new(crate::notification::LibNotifySink::new()),
                settings_rx: notification_settings_rx,
                alerts_rx: alert_tx.subscribe(),
                shutdown_rx: notification_shutdown_rx,
            },
        );

        // M226 Step 6: prepare the watched-folder dispatcher's channels.
        // The dispatcher itself is spawned at the very end of `start_full`
        // (it needs a fully-built `SessionHandle` to clone), but the
        // shutdown signal + change-notify must exist before SessionActor
        // construction so they can be stored on the actor.
        let watched_folder_changed = Arc::new(tokio::sync::Notify::new());
        let (watched_folder_shutdown_tx, watched_folder_shutdown_rx) =
            oneshot::channel::<()>();
        // Fresh settings subscription dedicated to the watcher (a watch
        // Receiver is single-consumer; the notification dispatcher
        // already consumed the original).
        let watched_folder_settings_rx = notification_settings_tx.subscribe();

        let (lsd, lsd_peers_rx) = if settings.enable_lsd {
            match crate::lsd::LsdHandle::start(settings.listen_port, settings.enable_ipv6).await {
                Ok((handle, rx)) => (Some(handle), Some(rx)),
                Err(e) => {
                    warn!("LSD unavailable (port 6771): {e}");
                    (None, None)
                }
            }
        } else {
            (None, None)
        };

        let global_upload_bucket = Arc::new(parking_lot::Mutex::new(
            crate::rate_limiter::TokenBucket::new(settings.upload_rate_limit),
        ));
        let global_download_bucket = Arc::new(parking_lot::Mutex::new(
            crate::rate_limiter::TokenBucket::new(settings.download_rate_limit),
        ));

        // M225 G4: build the shared admit-gate state BEFORE binding the uTP
        // socket so the SocketActor's inbound-SYN path can read from the
        // same `Arc<AtomicI32>` / `Arc<AtomicUsize>` / `SharedIpFilter` the
        // TCP listener and `handle_apply_settings` use. These three
        // allocations are otherwise constructed further down (lines below);
        // hoisting them avoids a separate setter on `UtpSocket` and the
        // race window it would open.
        let ip_filter: SharedIpFilter =
            Arc::new(parking_lot::RwLock::new(crate::ip_filter::IpFilter::new()));
        let max_connections_global = Arc::new(std::sync::atomic::AtomicI32::new(
            settings.max_connections_global,
        ));
        let live_connections = Arc::new(std::sync::atomic::AtomicUsize::new(0));

        let utp_admit = {
            let ip_filter_for_utp = Arc::clone(&ip_filter);
            irontide_utp::AdmitGate::new(
                Arc::clone(&max_connections_global),
                Arc::clone(&live_connections),
                Arc::new(move |addr| ip_filter_for_utp.read().is_blocked(addr)),
            )
        };

        // uTP socket (shared across all torrents).
        //
        // Stage U: when the factory exposes a `bind_udp` closure (sim
        // path), bind the production `UtpSocket` on top of the factory's
        // `UdpTransport` so BEP 29 runs unmodified through the in-memory
        // packet bus. The tokio factory leaves `bind_udp` unset and the
        // direct `UtpSocket::bind` path runs (it owns the FD-level DSCP /
        // TCLASS setsockopt, which the sim has no equivalent for).
        let (utp_socket, utp_listener) = if settings.enable_utp {
            let utp_config = settings.to_utp_config(settings.listen_port);
            let bind_addr = utp_config.bind_addr;
            let result = if factory.has_bind_udp() {
                match factory.bind_udp(bind_addr).await {
                    Ok(transport) => {
                        irontide_utp::UtpSocket::bind_with_transport_and_admit_gate(
                            transport,
                            utp_config,
                            utp_admit.clone(),
                        )
                    }
                    Err(e) => Err(irontide_utp::Error::Io(e)),
                }
            } else {
                irontide_utp::UtpSocket::bind_with_admit_gate(utp_config, utp_admit.clone()).await
            };
            match result {
                Ok((socket, listener)) => (Some(socket), Some(listener)),
                Err(e) => {
                    warn!("uTP bind failed: {e}");
                    (None, None)
                }
            }
        } else {
            (None, None)
        };

        // IPv6 uTP socket (dual-stack). Sim path skips IPv6 — the sim
        // network only models v4 today.
        let (utp_socket_v6, utp_listener_v6) =
            if settings.enable_utp && settings.enable_ipv6 && !factory.has_bind_udp() {
                match irontide_utp::UtpSocket::bind_with_admit_gate(
                    settings.to_utp_config_v6(settings.listen_port),
                    utp_admit.clone(),
                )
                .await
                {
                    Ok((socket, listener)) => (Some(socket), Some(listener)),
                    Err(e) => {
                        debug!("uTP IPv6 bind failed (non-fatal): {e}");
                        (None, None)
                    }
                }
            } else {
                (None, None)
            };

        // NAT port mapping (PCP / NAT-PMP / UPnP)
        let (nat, nat_events_rx) = if settings.enable_upnp || settings.enable_natpmp {
            let nat_config = settings.to_nat_config();
            let (handle, events_rx) = irontide_nat::NatHandle::start(nat_config);
            let udp_port = if settings.enable_utp {
                Some(settings.listen_port)
            } else {
                None
            };
            handle.map_ports(settings.listen_port, udp_port).await;
            (Some(handle), Some(events_rx))
        } else {
            (None, None)
        };

        // I2P SAM session
        let sam_session = if settings.enable_i2p {
            let tunnel_config = settings.to_sam_tunnel_config();
            match crate::i2p::SamSession::create(
                &settings.i2p_hostname,
                settings.i2p_port,
                "torrent",
                tunnel_config,
            )
            .await
            {
                Ok(session) => {
                    let b32 = session.destination().to_b32_address();
                    info!("I2P SAM session created: {}", b32);
                    post_alert(
                        &alert_tx,
                        &alert_mask,
                        AlertKind::I2pSessionCreated { b32_address: b32 },
                    );
                    Some(Arc::new(session))
                }
                Err(e) => {
                    warn!("I2P SAM session failed: {e}");
                    post_alert(
                        &alert_tx,
                        &alert_mask,
                        AlertKind::I2pError {
                            message: format!("SAM session creation failed: {e}"),
                        },
                    );
                    None
                }
            }
        } else {
            None
        };

        // SSL manager (M42): create if ssl_listen_port != 0 or cert paths are provided
        let ssl_manager = if settings.ssl_listen_port != 0 || settings.ssl_cert_path.is_some() {
            match crate::ssl_manager::SslManager::new(&settings) {
                Ok(mgr) => {
                    info!("SSL manager initialized");
                    Some(Arc::new(mgr))
                }
                Err(e) => {
                    warn!(error = %e, "SSL manager initialization failed");
                    None
                }
            }
        } else {
            None
        };

        // TCP listener: bind on the main listen port for incoming peer connections.
        let tcp_listener: Option<Box<dyn crate::transport::TransportListener>> = match factory
            .bind_tcp(SocketAddr::from(([0, 0, 0, 0], settings.listen_port)))
            .await
        {
            Ok(l) => {
                info!(port = settings.listen_port, "TCP listener started");
                Some(l)
            }
            Err(e) => {
                warn!(port = settings.listen_port, error = %e, "TCP listener bind failed");
                None
            }
        };

        // SSL listener (M42): bind if ssl_listen_port != 0
        let ssl_listener: Option<Box<dyn crate::transport::TransportListener>> = if settings
            .ssl_listen_port
            != 0
        {
            match factory
                .bind_tcp(SocketAddr::from(([0, 0, 0, 0], settings.ssl_listen_port)))
                .await
            {
                Ok(l) => {
                    info!(port = settings.ssl_listen_port, "SSL listener started");
                    Some(l)
                }
                Err(e) => {
                    warn!(port = settings.ssl_listen_port, error = %e, "SSL listener bind failed");
                    None
                }
            }
        } else {
            None
        };

        // Start DHT instances
        let (dht_v4, dht_v4_ip_rx) = if settings.enable_dht {
            match DhtHandle::start(settings.to_dht_config()).await {
                Ok((handle, ip_rx)) => {
                    info!("DHT v4 started");
                    (Some(handle), Some(ip_rx))
                }
                Err(e) => {
                    warn!("DHT v4 start failed: {e}");
                    (None, None)
                }
            }
        } else {
            (None, None)
        };

        let (dht_v6, dht_v6_ip_rx) = if settings.enable_dht && settings.enable_ipv6 {
            match DhtHandle::start(settings.to_dht_config_v6()).await {
                Ok((handle, ip_rx)) => {
                    info!("DHT v6 started");
                    (Some(handle), Some(ip_rx))
                }
                Err(e) => {
                    debug!("DHT v6 start failed (non-fatal): {e}");
                    (None, None)
                }
            }
        } else {
            (None, None)
        };

        // M173 Lane B (B6): seed the broadcast surfaces with the
        // initial DHT handles so consumers see exactly the same
        // value via the broadcast as the legacy `dht_v4`/`dht_v6`
        // fields. B11's apply_settings DHT-restart phase later
        // updates the broadcasts via `replace`.
        let dht_v4_broadcast = irontide_dht::DhtBroadcast::new(dht_v4.clone());
        let dht_v6_broadcast = irontide_dht::DhtBroadcast::new(dht_v6.clone());

        let ban_config = crate::ban::BanConfig::from(&settings);
        let ban_manager: SharedBanManager = Arc::new(parking_lot::RwLock::new(
            crate::ban::BanManager::new(ban_config),
        ));

        // M225 G4: `ip_filter` was hoisted above the uTP bind so the
        // SocketActor's admit-gate closure captures the same Arc.

        let disk_config = crate::disk::DiskConfig::from(&settings);
        let spawner = crate::blocking_spawner::BlockingSpawner::new(settings.max_blocking_threads);
        let (disk_manager, disk_actor_handle) =
            crate::disk::DiskManagerHandle::new_with_backend(disk_config, backend, spawner);

        let counters = Arc::new(crate::stats::SessionCounters::new_with_diagnostics(
            settings.enable_diagnostic_counters,
        ));

        // M96: Create shared hash pool for parallel piece verification
        let hash_pool = std::sync::Arc::new(crate::hash_pool::HashPool::new(
            settings.hashing_threads,
            64,
        ));

        // M114: Spawn isolated listener task for TCP/uTP accepts.
        let info_hash_registry = Arc::new(DashMap::new());
        let (validated_tx, validated_conn_rx) = mpsc::channel(64);
        // M224 D3 / M225 G4: `max_connections_global` and `live_connections`
        // were hoisted above the uTP bind so the SocketActor's admit gate
        // shares them with this listener. handle_apply_settings updates the
        // i32 atomic in-place; both transports read it on the next admit.
        let listener_task = crate::listener::ListenerTask::new(
            tcp_listener,
            utp_listener,
            utp_listener_v6,
            Arc::clone(&info_hash_registry),
            validated_tx,
            Arc::clone(&max_connections_global),
            Arc::clone(&live_connections),
        );
        // M173 Lane B (B2): spawn via ListenerHandle::spawn so the
        // shutdown channel is plumbed in. We hold the full
        // `ListenerHandle` (not just the JoinHandle) so the future
        // listen-port rebind path (B4) can call
        // `shutdown_with_timeout` for a clean port swap. Session
        // teardown still works via Drop on the `ListenerHandle` →
        // shutdown sender Drop → receiver fires `RecvError` → loop
        // exits.
        let listener_handle = crate::listener::ListenerHandle::spawn(listener_task);

        let external_ip = settings.external_ip;

        // M170: load the category registry once on startup. Errors are
        // soft-recovered inside `CategoryRegistry::load`, so this call
        // cannot fail in practice.
        let category_registry_path = crate::category_manager::resolve_category_registry_path(
            settings.category_registry_path.as_deref(),
        );
        let category_registry = Arc::new(parking_lot::RwLock::new(
            crate::category_manager::CategoryRegistry::load(category_registry_path),
        ));
        // M171: same pattern as the category registry — soft-recover inside
        // `TagRegistry::load`, so this never fails in practice.
        let tag_registry_path =
            crate::tag_manager::resolve_tag_registry_path(settings.tag_registry_path.as_deref());
        let tag_registry = Arc::new(parking_lot::RwLock::new(
            crate::tag_manager::TagRegistry::load(tag_registry_path),
        ));
        let deletion_grace = Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new()));
        let reconfig_in_flight = crate::apply::ReconfigInFlight::new();

        let actor = SessionActor {
            settings,
            // M223 — clone so the actor can self-emit CommitAddTorrent
            // from off-actor prep tasks. The handle still owns the
            // original sender; both feed the same recv queue.
            commit_tx: cmd_tx.clone(),
            torrents: HashMap::new(),
            dht_v4,
            dht_v6,
            dht_v4_broadcast,
            dht_v6_broadcast,
            lsd,
            lsd_peers_rx,
            cmd_rx,
            alert_tx: alert_tx.clone(),
            alert_mask: Arc::clone(&alert_mask),
            global_upload_bucket,
            global_download_bucket,
            utp_socket,
            utp_socket_v6,
            nat,
            nat_events_rx,
            ban_manager,
            ip_filter,
            disk_manager,
            disk_actor_handle,
            external_ip,
            dht_v4_ip_rx,
            dht_v6_ip_rx,
            plugins,
            sam_session,
            ssl_manager,
            ssl_listener,
            validated_conn_rx,
            info_hash_registry,
            _listener_task: listener_handle,
            max_connections_global,
            live_connections,
            counters: Arc::clone(&counters),
            factory: Arc::clone(&factory),
            hash_pool,
            category_registry,
            tag_registry,
            deletion_grace,
            // Clone so the SessionHandle can hold the same guard.
            reconfig_in_flight: reconfig_in_flight.clone(),
            self_alert_rx: alert_tx.subscribe(),
            resume_save_notify: Arc::new(tokio::sync::Notify::new()),
            notification_settings_tx,
            notification_shutdown_tx,
            watched_folder_changed: Arc::clone(&watched_folder_changed),
            watched_folder_shutdown_tx,
        };

        let join_handle = tokio::spawn(actor.run());
        tokio::spawn(async move {
            match join_handle.await {
                Ok(()) => {
                    tracing::warn!("session actor exited cleanly");
                }
                Err(e) if e.is_panic() => {
                    let panic_payload = e.into_panic();
                    let msg = if let Some(s) = panic_payload.downcast_ref::<&str>() {
                        (*s).to_string()
                    } else if let Some(s) = panic_payload.downcast_ref::<String>() {
                        s.clone()
                    } else {
                        "unknown panic payload".to_string()
                    };
                    tracing::error!("session actor PANICKED: {msg}");
                }
                Err(e) => {
                    tracing::error!("session actor task error: {e}");
                }
            }
        });
        let handle = Self {
            cmd_tx,
            alert_tx,
            alert_mask,
            counters,
            factory,
            // M173 Lane B (B11): share the in-flight guard with the
            // SessionActor — the actor's apply pipeline can also
            // check it for symmetric guarantees, but the HANDLE-side
            // try_lock is what catches caller-side races (two
            // concurrent setPreferences requests).
            reconfig_in_flight,
        };

        // M226 Step 6: spawn the watched-folder dispatcher AFTER the
        // SessionHandle is built so we can hand it a `.clone()`. The
        // dispatcher calls `handle.add_torrent(params)` for every
        // .torrent file dropped in `settings.watched_folder`. Drop of
        // the matching `watched_folder_shutdown_tx` on the actor (or
        // explicit send) signals the dispatcher to exit.
        let _watched_folder_join = crate::watched_folder::spawn_watched_folder_dispatcher(
            handle.clone(),
            watched_folder_settings_rx,
            watched_folder_changed,
            watched_folder_shutdown_rx,
        );

        Ok(handle)
    }

    /// Add a torrent from parsed .torrent metadata (v1, v2, or hybrid).
    ///
    /// Low-level entry point; used by the `irontide` facade and internal
    /// sim/test code. For user-facing adds, prefer
    /// [`add_torrent`](Self::add_torrent) with [`AddTorrentParams`],
    /// which resolves categories and `download_dir` via M170 semantics.
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent cannot be added or the session is shut down.
    pub async fn add_torrent_with_meta(
        &self,
        meta: irontide_core::TorrentMeta,
        storage: Option<Arc<dyn TorrentStorage>>,
    ) -> crate::Result<Id20> {
        self.add_torrent_with_dir(meta, storage, None).await
    }

    /// Unified add entry (M170).
    ///
    /// Resolves the download directory using the precedence documented
    /// on [`AddTorrentParams`] and the category registry, then delegates
    /// to the magnet or bytes-add path as appropriate. Returns the v1
    /// info hash of the new torrent.
    ///
    /// # Errors
    ///
    /// - [`Error::CategoryNotFound`](crate::Error::CategoryNotFound) when
    ///   `params.category` names a category that is not in the registry.
    /// - [`Error::TorrentBeingRemoved`](crate::Error::TorrentBeingRemoved)
    ///   when another task is currently deleting files for the same info
    ///   hash (mapped to 409 Conflict by the qBt API).
    /// - Propagates parsing errors for bad magnet URIs / .torrent bytes.
    /// - Propagates the existing `DuplicateTorrent` / `SessionAtCapacity`
    ///   error shapes unchanged.
    pub async fn add_torrent(&self, params: AddTorrentParams) -> crate::Result<Id20> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::AddTorrentM170 {
                params: Box::new(params),
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Create a new qBt-compat category (M170).
    ///
    /// # Errors
    ///
    /// Returns [`CategoryError`](crate::CategoryError) on name validation
    /// failure, duplicate name, or persistence I/O error.
    pub async fn create_category(
        &self,
        name: String,
        save_path: PathBuf,
    ) -> Result<(), crate::category_manager::CategoryError> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::CreateCategory {
                name,
                save_path,
                reply: tx,
            })
            .await
            .is_err()
        {
            return Err(crate::category_manager::CategoryError::Persistence(
                std::io::Error::other("session shutting down"),
            ));
        }
        rx.await.unwrap_or_else(|_| {
            Err(crate::category_manager::CategoryError::Persistence(
                std::io::Error::other("session shutting down"),
            ))
        })
    }

    /// Update the `save_path` on an existing category (M170).
    ///
    /// # Errors
    ///
    /// Returns [`CategoryError::NotFound`](crate::CategoryError::NotFound)
    /// when the category does not exist, plus the same persistence /
    /// validation error shapes as [`create_category`](Self::create_category).
    pub async fn edit_category(
        &self,
        name: String,
        save_path: PathBuf,
    ) -> Result<(), crate::category_manager::CategoryError> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::EditCategory {
                name,
                save_path,
                reply: tx,
            })
            .await
            .is_err()
        {
            return Err(crate::category_manager::CategoryError::Persistence(
                std::io::Error::other("session shutting down"),
            ));
        }
        rx.await.unwrap_or_else(|_| {
            Err(crate::category_manager::CategoryError::Persistence(
                std::io::Error::other("session shutting down"),
            ))
        })
    }

    /// Remove zero or more categories (M170). Unknown names are tolerated
    /// (qBt behaviour). Returns the names that were actually removed.
    /// After removal, any torrent assigned to a removed category has its
    /// `category` label cleared and its resume data marked dirty.
    pub async fn remove_categories(&self, names: Vec<String>) -> Vec<String> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::RemoveCategories { names, reply: tx })
            .await
            .is_err()
        {
            return Vec::new();
        }
        rx.await.unwrap_or_default()
    }

    /// Snapshot the current category list (M170).
    pub async fn list_categories(&self) -> Vec<crate::category_manager::CategoryMetadata> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::ListCategories { reply: tx })
            .await
            .is_err()
        {
            return Vec::new();
        }
        rx.await.unwrap_or_default()
    }

    /// List every tag name currently in the registry (M171). Sorted.
    pub async fn list_tags(&self) -> Vec<String> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::ListTags { reply: tx })
            .await
            .is_err()
        {
            return Vec::new();
        }
        rx.await.unwrap_or_default()
    }

    /// Create a batch of tags (M171). Returns one
    /// `Result<(), TagError>` per requested name so the caller can
    /// distinguish which names already existed and which were newly
    /// created. Persistence is best-effort on success; any partial
    /// persistence failure warns but does not change the per-call reply.
    pub async fn create_tags(
        &self,
        names: Vec<String>,
    ) -> Vec<Result<(), crate::tag_manager::TagError>> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::CreateTags { names, reply: tx })
            .await
            .is_err()
        {
            return Vec::new();
        }
        rx.await.unwrap_or_default()
    }

    /// Delete a batch of tags (M171). Returns the subset of names that
    /// were actually present at call time (unknown names are silently
    /// skipped, matching qBt's idempotent `deleteTags`).
    pub async fn delete_tags(&self, names: Vec<String>) -> Vec<String> {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::DeleteTags { names, reply: tx })
            .await
            .is_err()
        {
            return Vec::new();
        }
        rx.await.unwrap_or_default()
    }

    /// Add the given tags to each torrent in `hashes` (M171).
    /// Idempotent — tags that a torrent already has are left alone.
    /// Unknown info hashes are silently skipped.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Shutdown`](crate::Error::Shutdown) if the
    /// session's command channel has closed.
    pub async fn add_tags_to_torrents(
        &self,
        hashes: Vec<Id20>,
        tags: Vec<String>,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::AddTagsToTorrents {
                info_hashes: hashes,
                tags,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Remove the given tags from each torrent in `hashes` (M171).
    /// Unknown info hashes are silently skipped.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Shutdown`](crate::Error::Shutdown) if the
    /// session's command channel has closed.
    pub async fn remove_tags_from_torrents(
        &self,
        hashes: Vec<Id20>,
        tags: Vec<String>,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::RemoveTagsFromTorrents {
                info_hashes: hashes,
                tags,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Remove a torrent and delete its on-disk files (M170,
    /// `deleteFiles=true`).
    ///
    /// Pauses the torrent, closes storage handles, then dispatches a
    /// `spawn_blocking` file-removal walk via
    /// [`delete_torrent_files_sync`](irontide_storage::delete_torrent_files_sync).
    /// The info hash is placed in a deletion grace set for the duration of
    /// the walk; concurrent calls to [`add_torrent`](Self::add_torrent)
    /// with the same hash return [`Error::TorrentBeingRemoved`](crate::Error::TorrentBeingRemoved).
    ///
    /// # Errors
    ///
    /// Returns [`Error::TorrentNotFound`](crate::Error::TorrentNotFound)
    /// if the info hash is not in the session. I/O failures during file
    /// removal are logged and swallowed — always returns `Ok(())` when
    /// the torrent is found.
    pub async fn remove_torrent_with_files(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::RemoveTorrentWithFiles {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Add a torrent with an optional per-torrent download directory override.
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent cannot be added or the session is shut down.
    pub async fn add_torrent_with_dir(
        &self,
        meta: irontide_core::TorrentMeta,
        storage: Option<Arc<dyn TorrentStorage>>,
        download_dir: Option<PathBuf>,
    ) -> crate::Result<Id20> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::AddTorrent {
                meta: Box::new(meta),
                storage,
                download_dir,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Add a torrent from a magnet link (metadata fetched via BEP 9).
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent cannot be added or the session is shut down.
    pub async fn add_magnet(&self, magnet: Magnet) -> crate::Result<Id20> {
        self.add_magnet_with_dir(magnet, None).await
    }

    /// Add a magnet link with an optional per-torrent download directory override.
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent cannot be added or the session is shut down.
    pub async fn add_magnet_with_dir(
        &self,
        magnet: Magnet,
        download_dir: Option<PathBuf>,
    ) -> crate::Result<Id20> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::AddMagnet {
                magnet,
                download_dir,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Remove a torrent from the session.
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent is not found or the session is shut down.
    pub async fn remove_torrent(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::RemoveTorrent {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Pause a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn pause_torrent(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::PauseTorrent {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Resume a paused torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn resume_torrent(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ResumeTorrent {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Force-resume a torrent, bypassing queue limits.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn force_resume_torrent(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ForceResumeTorrent {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set a per-torrent seed ratio limit override (`None` = use session default).
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn set_torrent_seed_ratio(
        &self,
        info_hash: Id20,
        limit: Option<f64>,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetTorrentSeedRatio {
                info_hash,
                limit,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get statistics for a specific torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn torrent_stats(&self, info_hash: Id20) -> crate::Result<TorrentStats> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::TorrentStats {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Snapshot per-peer cumulative unchoke duration for the given torrent.
    ///
    /// Returns `Ok(Some(map))` when the torrent exists. Each entry is the
    /// total time we (this session) had that peer unchoked over the
    /// torrent's lifetime, including reconnects (durations are flushed
    /// into a per-(SocketAddr × torrent) map on disconnect and re-merged
    /// here at query time).
    ///
    /// Returns `Ok(None)` when the torrent is unknown to this session —
    /// the explicit contract distinguishes "torrent missing" from "exists
    /// but no peers were ever unchoked".
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn peer_unchoke_durations(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Option<std::collections::HashMap<SocketAddr, std::time::Duration>>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::QueryUnchokeDurations {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Get metadata info for a specific torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn torrent_info(&self, info_hash: Id20) -> crate::Result<TorrentInfo> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::TorrentInfo {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// List all active torrent info hashes.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn list_torrents(&self) -> crate::Result<Vec<Id20>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ListTorrents { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Get aggregate session statistics.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn session_stats(&self) -> crate::Result<SessionStats> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SessionStats { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Collect per-torrent and per-peer debug state for diagnosing dispatch
    /// throughput regressions (M187).
    ///
    /// Individual torrents that do not respond within 500 ms are skipped so
    /// the endpoint always returns partial results rather than failing.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn debug_state(&self) -> crate::Result<crate::types::DebugState> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DebugState { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        // Use a generous 5 s overall timeout — the per-torrent timeouts are
        // 500 ms inside the actor, but with many torrents the total can add up.
        tokio::time::timeout(std::time::Duration::from_secs(5), rx)
            .await
            .map_err(|_| crate::Error::Shutdown)?
            .map_err(|_| crate::Error::Shutdown)
    }

    /// Subscribe to all alerts passing the session-level mask.
    #[must_use]
    pub fn subscribe(&self) -> broadcast::Receiver<Alert> {
        self.alert_tx.subscribe()
    }

    /// Subscribe with per-subscriber category filtering.
    #[must_use]
    pub fn subscribe_filtered(&self, filter: AlertCategory) -> AlertStream {
        AlertStream::new(self.alert_tx.subscribe(), filter)
    }

    /// Trigger an immediate session stats snapshot and alert.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn post_session_stats(&self) -> crate::Result<()> {
        self.cmd_tx
            .send(SessionCommand::PostSessionStats)
            .await
            .map_err(|_| crate::Error::Shutdown)
    }

    /// Access the shared atomic counters (read-only handle).
    #[must_use]
    pub fn counters(&self) -> &Arc<crate::stats::SessionCounters> {
        &self.counters
    }

    /// Atomically update the session-level alert mask.
    pub fn set_alert_mask(&self, mask: AlertCategory) {
        self.alert_mask.store(mask.bits(), Ordering::Relaxed);
    }

    /// Read the current session-level alert mask.
    #[must_use]
    pub fn alert_mask(&self) -> AlertCategory {
        AlertCategory::from_bits_truncate(self.alert_mask.load(Ordering::Relaxed))
    }

    /// Add peers to a specific torrent by info hash.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn add_peers(
        &self,
        info_hash: Id20,
        peers: Vec<SocketAddr>,
        source: crate::peer_state::PeerSource,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::AddPeers {
                info_hash,
                peers,
                source,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Gracefully shut down the session and all torrents.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn shutdown(&self) -> crate::Result<()> {
        // Timeout prevents hang if SessionActor is processing a heavy batch
        let _ = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            self.cmd_tx.send(SessionCommand::Shutdown),
        )
        .await;
        Ok(())
    }

    /// Save resume data for a specific torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the I/O operation fails.
    pub async fn save_torrent_resume_data(
        &self,
        info_hash: Id20,
    ) -> crate::Result<irontide_core::FastResumeData> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SaveTorrentResumeData {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Save full session state (all torrent resume data + DHT node cache).
    ///
    /// # Errors
    ///
    /// Returns an error if the I/O operation fails.
    pub async fn save_session_state(&self) -> crate::Result<crate::persistence::SessionState> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SaveSessionState { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Load and restore torrents from per-torrent resume files on disk.
    ///
    /// Scans the resume directory for `.resume` files, deserializes each one,
    /// reconstructs the torrent metadata, and re-adds it to the session. For
    /// resolved torrents (with stored info dict), the piece bitmap is restored.
    /// Unresolved magnets are re-added as magnet links.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Shutdown`] if the session has been shut down.
    pub async fn load_resume_state(&self) -> crate::Result<ResumeLoadResult> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::LoadResumeState { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Save per-torrent resume files for all dirty torrents.
    ///
    /// Iterates every torrent in the session, checks the `need_save_resume`
    /// dirty flag, serializes resume data to disk, and clears the flag.
    /// Returns the number of files written.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Shutdown`] if the session actor has stopped.
    pub async fn save_resume_state(&self) -> crate::Result<usize> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SaveResumeState { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the queue position of a torrent. Returns -1 if not auto-managed.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn queue_position(&self, info_hash: Id20) -> crate::Result<i32> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::QueuePosition {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set the absolute queue position of a torrent. Shifts other torrents.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn set_queue_position(&self, info_hash: Id20, pos: i32) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetQueuePosition {
                info_hash,
                pos,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Move a torrent one position up (lower number = higher priority).
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn queue_position_up(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::QueuePositionUp {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Move a torrent one position down.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn queue_position_down(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::QueuePositionDown {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Move a torrent to position 0 (highest priority).
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn queue_position_top(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::QueuePositionTop {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Move a torrent to the last position (lowest priority).
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn queue_position_bottom(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::QueuePositionBottom {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Ban a peer IP session-wide. All torrents will disconnect and refuse this IP.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn ban_peer(&self, ip: IpAddr) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::BanPeer { ip, reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Remove a ban and clear strikes for an IP. Returns `true` if the IP was banned.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn unban_peer(&self, ip: IpAddr) -> crate::Result<bool> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::UnbanPeer { ip, reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Replace the session-wide IP filter. Connected peers that are now blocked will
    /// be refused on subsequent connection attempts.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn set_ip_filter(&self, filter: crate::ip_filter::IpFilter) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetIpFilter { filter, reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Get a clone of the current IP filter.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn ip_filter(&self) -> crate::Result<crate::ip_filter::IpFilter> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetIpFilter { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Get a clone of the current session settings.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn settings(&self) -> crate::Result<Settings> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetSettings { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Apply new settings at runtime.
    ///
    /// Validates the settings, updates rate limiters immediately, and stores
    /// the new settings. Sub-actor reconfiguration (disk, DHT, NAT) takes
    /// effect on next session restart for the fields that remain in
    /// `restart_required`; `listen_port`, `dht`, `lsd` are now applied
    /// live (M173 Lane B B10).
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ConcurrentReconfig`] if another
    /// `apply_settings` / `apply_settings_classified` call is still in
    /// flight (M173 Lane B B11). Caller should retry shortly.
    pub async fn apply_settings(&self, settings: Settings) -> crate::Result<()> {
        let _guard = self
            .reconfig_in_flight
            .try_lock()
            .ok_or(crate::Error::ConcurrentReconfig)?;
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ApplySettings {
                settings: Box::new(settings),
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Apply new settings and return a classification of which fields took
    /// effect immediately versus which require a session restart (M171 D3.5).
    ///
    /// Identical behaviour to [`apply_settings`](Self::apply_settings), but
    /// the return value lets callers surface the "restart to apply" UX —
    /// specifically the `X-IronTide-Restart-Pending` response header on the
    /// qBt v2 `setPreferences` endpoint and the GUI restart-banner.
    ///
    /// M173 Lane B (B11): the in-flight guard is acquired BEFORE the
    /// snapshot read, so concurrent callers cannot race the
    /// read-modify-write. The second caller hits
    /// [`crate::Error::ConcurrentReconfig`].
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ConcurrentReconfig`] if another reconfig
    /// is still in flight. Returns [`crate::Error::InvalidSettings`] if
    /// the patch fails validation. Returns [`crate::Error::Shutdown`]
    /// if the session has shut down.
    pub async fn apply_settings_classified(
        &self,
        settings: Settings,
    ) -> crate::Result<AppliedSettings> {
        let _guard = self
            .reconfig_in_flight
            .try_lock()
            .ok_or(crate::Error::ConcurrentReconfig)?;
        // Snapshot AFTER acquiring the guard so the classification is
        // computed against a stable pre-call state.
        let snapshot = self.settings().await?;
        let immediate = classify_immediate(&snapshot, &settings);
        let restart_required = classify_restart_required(&snapshot, &settings);
        // Inner apply_settings tries to re-acquire the guard. To avoid
        // a self-deadlock, we send the command directly here rather
        // than calling self.apply_settings(), which would error out
        // with ConcurrentReconfig because we already hold the lock.
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ApplySettings {
                settings: Box::new(settings),
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)??;
        Ok(AppliedSettings {
            immediate,
            restart_required,
        })
    }

    /// Get the current DHT routing-table size, summed across IPv4 and IPv6
    /// instances (M171 D4).
    ///
    /// Returns `Ok(0)` when DHT is disabled for both address families, or
    /// when neither instance has bootstrapped yet. Wired into the qBt v2
    /// `transferInfo.dht_nodes` field and the DHT pseudo-tracker's
    /// `num_peers` column on `/api/v2/torrents/trackers`.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn dht_node_count(&self) -> crate::Result<usize> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DhtNodeCount { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Get the list of currently banned peer IPs.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn banned_peers(&self) -> crate::Result<Vec<IpAddr>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::BannedPeers { reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    /// Move a torrent's data files to a new download directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn move_torrent_storage(
        &self,
        info_hash: Id20,
        new_path: std::path::PathBuf,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::MoveTorrentStorage {
                info_hash,
                new_path,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Opens a file stream for sequential reading (`AsyncRead` + `AsyncSeek`).
    ///
    /// The returned [`FileStream`](crate::streaming::FileStream) reads data from
    /// a specific file within a torrent, blocking on pieces that haven't been
    /// downloaded yet.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn open_file(
        &self,
        info_hash: Id20,
        file_index: usize,
    ) -> crate::Result<crate::streaming::FileStream> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::OpenFile {
                info_hash,
                file_index,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Force all trackers for a torrent to re-announce immediately.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn force_reannounce(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ForceReannounce {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the list of all configured trackers with their status for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn tracker_list(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Vec<crate::tracker_manager::TrackerInfo>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::TrackerList {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// M178 Lane B3 / TODO-2: cumulative count of UNIQUE peers received via
    /// PEX (BEP 11) for this torrent since the actor started.
    ///
    /// # Errors
    /// - [`Error::TorrentNotFound`](crate::Error::TorrentNotFound) when
    ///   the hash is unknown.
    /// - [`Error::Shutdown`](crate::Error::Shutdown) on actor shutdown.
    pub async fn pex_peer_count(&self, info_hash: Id20) -> crate::Result<usize> {
        let counts = self.peer_source_counts(info_hash).await?;
        Ok(counts.0)
    }

    /// M178 Lane B3 / TODO-2: cumulative count of UNIQUE peers received via
    /// LSD (BEP 14) multicast for this torrent since the actor started.
    ///
    /// # Errors
    /// - [`Error::TorrentNotFound`](crate::Error::TorrentNotFound) when
    ///   the hash is unknown.
    /// - [`Error::Shutdown`](crate::Error::Shutdown) on actor shutdown.
    pub async fn lsd_peer_count(&self, info_hash: Id20) -> crate::Result<usize> {
        let counts = self.peer_source_counts(info_hash).await?;
        Ok(counts.1)
    }

    async fn peer_source_counts(&self, info_hash: Id20) -> crate::Result<(usize, usize)> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetPeerSourceCounts {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// M178 Lane C: per-URL web-seed stats snapshot for the qBt v2
    /// webseeds endpoint and the GUI HTTP Sources tab.
    ///
    /// # Errors
    /// - [`Error::TorrentNotFound`](crate::Error::TorrentNotFound) when
    ///   the hash is unknown.
    /// - [`Error::Shutdown`](crate::Error::Shutdown) on actor shutdown.
    pub async fn web_seed_stats(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Vec<irontide_core::WebSeedStats>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetWebSeedStats {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// M171 Lane B: list the web seed URLs (BEP 19 + BEP 17 merged) for a torrent.
    ///
    /// BEP 19 `url-list` URLs come first, followed by BEP 17 `httpseeds`
    /// URLs — the wire order. Returns an empty vec when the torrent's
    /// metadata has not yet been fetched (magnet still resolving the
    /// info dictionary).
    ///
    /// # Errors
    /// - [`Error::TorrentNotFound`](crate::Error::TorrentNotFound) if the
    ///   info-hash is unknown.
    /// - [`Error::Shutdown`](crate::Error::Shutdown) if the session's
    ///   command channel has closed.
    pub async fn get_web_seeds(&self, info_hash: Id20) -> crate::Result<Vec<String>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetWebSeeds {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// M171 Lane B: snapshot the per-piece qBt state codes for a torrent.
    ///
    /// Returns a `Vec<u8>` one byte per piece — `0` = not downloaded,
    /// `1` = downloading, `2` = downloaded + checked. An empty vec is
    /// returned when metadata hasn't resolved yet (magnet still fetching
    /// the info dictionary) — callers should map that to a 404.
    ///
    /// # Errors
    /// - [`Error::TorrentNotFound`](crate::Error::TorrentNotFound) if the
    ///   info-hash is unknown.
    /// - [`Error::Shutdown`](crate::Error::Shutdown) if the session's
    ///   command channel has closed.
    pub async fn get_piece_states(&self, info_hash: Id20) -> crate::Result<Vec<u8>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetPieceStates {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// M171 Lane B: paginated piece hash list for a torrent.
    ///
    /// v1 / hybrid torrents return SHA-1 hashes (40-char hex strings);
    /// v2-only torrents return SHA-256 hashes (64-char hex strings).
    /// `offset` and `limit` are clamped to the real hash count inside
    /// the actor — callers can pass arbitrary values without overflow
    /// concerns. An empty vec is returned when metadata hasn't resolved
    /// yet — callers should map that to a 404.
    ///
    /// # Errors
    /// - [`Error::TorrentNotFound`](crate::Error::TorrentNotFound) if the
    ///   info-hash is unknown.
    /// - [`Error::Shutdown`](crate::Error::Shutdown) if the session's
    ///   command channel has closed.
    pub async fn get_piece_hashes(
        &self,
        info_hash: Id20,
        offset: u32,
        limit: u32,
    ) -> crate::Result<Vec<String>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetPieceHashes {
                info_hash,
                offset,
                limit,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Scrape trackers for seeder/leecher counts for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn scrape(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Option<(String, irontide_tracker::ScrapeInfo)>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::Scrape {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set the download priority of a specific file within a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn set_file_priority(
        &self,
        info_hash: Id20,
        index: usize,
        priority: irontide_core::FilePriority,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetFilePriority {
                info_hash,
                index,
                priority,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the current per-file priorities for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn file_priorities(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Vec<irontide_core::FilePriority>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::FilePriorities {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set the per-torrent download rate limit in bytes/sec (0 = unlimited).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn set_download_limit(
        &self,
        info_hash: Id20,
        bytes_per_sec: u64,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetDownloadLimit {
                info_hash,
                bytes_per_sec,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set the per-torrent upload rate limit in bytes/sec (0 = unlimited).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn set_upload_limit(&self, info_hash: Id20, bytes_per_sec: u64) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetUploadLimit {
                info_hash,
                bytes_per_sec,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the current per-torrent download rate limit in bytes/sec (0 = unlimited).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn download_limit(&self, info_hash: Id20) -> crate::Result<u64> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DownloadLimit {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the current per-torrent upload rate limit in bytes/sec (0 = unlimited).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn upload_limit(&self, info_hash: Id20) -> crate::Result<u64> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::UploadLimit {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Enable or disable sequential (in-order) piece downloading for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn set_sequential_download(
        &self,
        info_hash: Id20,
        enabled: bool,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetSequentialDownload {
                info_hash,
                enabled,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Query whether sequential downloading is enabled for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn is_sequential_download(&self, info_hash: Id20) -> crate::Result<bool> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::IsSequentialDownload {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Enable or disable BEP 16 super seeding mode for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn set_super_seeding(&self, info_hash: Id20, enabled: bool) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetSuperSeeding {
                info_hash,
                enabled,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Query whether BEP 16 super seeding mode is enabled for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn is_super_seeding(&self, info_hash: Id20) -> crate::Result<bool> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::IsSuperSeeding {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Enable or disable user-requested seed-only mode for a torrent (M159).
    ///
    /// When `enabled` is `true`, the engine stops scheduling new block requests
    /// and cancels all in-flight requests for the torrent, but continues to
    /// serve uploads to interested peers. This is distinct from "naturally
    /// seeding" (all pieces downloaded): it represents an explicit user toggle
    /// layered on top of the download state.
    ///
    /// Toggling back to `false` resumes normal piece scheduling.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::TorrentNotFound`] if `info_hash` is not registered
    /// in the session, or [`crate::Error::Shutdown`] if the session actor has
    /// terminated.
    pub async fn set_seed_mode(&self, info_hash: Id20, enabled: bool) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetSeedMode {
                info_hash,
                enabled,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Add a new tracker URL to a torrent.
    ///
    /// The URL is validated and deduplicated by the tracker manager.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn add_tracker(&self, info_hash: Id20, url: String) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::AddTracker {
                info_hash,
                url,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Replace all tracker URLs for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn replace_trackers(&self, info_hash: Id20, urls: Vec<String>) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ReplaceTrackers {
                info_hash,
                urls,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Trigger a full piece verification (force recheck) for a torrent.
    ///
    /// Clears all piece completion data, re-verifies every piece, and
    /// transitions to `Seeding` or `Downloading` depending on the result.
    /// Returns after the recheck is complete.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn force_recheck(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ForceRecheck {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Rename a file within a torrent on disk.
    ///
    /// Changes the filename of the specified file (by index) to `new_name`.
    /// The file stays in the same directory; only the filename component changes.
    /// Fires a `FileRenamed` alert on success.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn rename_file(
        &self,
        info_hash: Id20,
        file_index: usize,
        new_name: String,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::RenameFile {
                info_hash,
                file_index,
                new_name,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set the per-torrent maximum number of connections (0 = use global default).
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn set_max_connections(&self, info_hash: Id20, limit: usize) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetMaxConnections {
                info_hash,
                limit,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the current per-torrent maximum connection limit (0 = use global default).
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn max_connections(&self, info_hash: Id20) -> crate::Result<usize> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::MaxConnections {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set the per-torrent maximum number of upload slots (unchoke slots).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn set_max_uploads(&self, info_hash: Id20, limit: usize) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetMaxUploads {
                info_hash,
                limit,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the current per-torrent maximum upload slots (unchoke slots).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn max_uploads(&self, info_hash: Id20) -> crate::Result<usize> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::MaxUploads {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get per-peer details for all connected peers of a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn get_peer_info(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Vec<crate::types::PeerInfo>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetPeerInfo {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get in-flight piece download status for a torrent (the download queue).
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn get_download_queue(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Vec<crate::types::PartialPieceInfo>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::GetDownloadQueue {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Check whether a specific piece has been downloaded for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn have_piece(&self, info_hash: Id20, index: u32) -> crate::Result<bool> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::HavePiece {
                info_hash,
                index,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get per-piece availability counts from connected peers for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn piece_availability(&self, info_hash: Id20) -> crate::Result<Vec<u32>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::PieceAvailability {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get per-file bytes-downloaded progress for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn file_progress(&self, info_hash: Id20) -> crate::Result<Vec<u64>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::FileProgress {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the torrent's identity hashes (v1 and/or v2).
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn info_hashes(&self, info_hash: Id20) -> crate::Result<irontide_core::InfoHashes> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::InfoHashesQuery {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the full v1 metainfo for a torrent.
    ///
    /// Returns `None` for magnet links before metadata has been received.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn torrent_file(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Option<irontide_core::TorrentMetaV1>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::TorrentFile {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get the full v2 metainfo for a torrent.
    ///
    /// Returns `None` if the torrent is not a v2/hybrid torrent, or for magnet
    /// links before metadata has been received.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn torrent_file_v2(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Option<irontide_core::TorrentMetaV2>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::TorrentFileV2 {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// **TEST-ONLY.** Synchronously inject an info-dict into a torrent's
    /// `MetadataDownloader` queue. Returns only after the actor has processed
    /// the message. Reuses the existing M147 internal handler at
    /// `torrent.rs:3665` via a separate test-only `TorrentCommand` variant
    /// (the production [`TorrentHandle::send_pre_resolved_metadata`] is
    /// fire-and-forget and stays unchanged).
    ///
    /// Introduced in v0.173.2 as a cross-crate test escape hatch for the
    /// `irontide-api` A9 HTTP integration test — it lets tests exercise the
    /// post-metadata HTTP surface without spinning up real peers.
    ///
    /// # Errors
    /// - [`crate::Error::TorrentNotFound`] if `info_hash` is not registered.
    /// - [`crate::Error::Shutdown`] if the session or torrent command
    ///   channel is closed.
    #[cfg(feature = "test-util")]
    pub async fn debug_inject_metadata(
        &self,
        info_hash: Id20,
        info_bytes: Vec<u8>,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::TestInjectMetadata {
                info_hash,
                info_bytes,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Force an immediate DHT announce for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn force_dht_announce(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ForceDhtAnnounce {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Force an immediate LSD (Local Service Discovery) announce for a torrent.
    ///
    /// LSD is a session-level component — this does not go through the torrent actor.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn force_lsd_announce(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ForceLsdAnnounce {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Read all data for a specific piece from disk.
    ///
    /// # Errors
    ///
    /// Returns an error if the data cannot be parsed or I/O fails.
    pub async fn read_piece(&self, info_hash: Id20, index: u32) -> crate::Result<bytes::Bytes> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ReadPiece {
                info_hash,
                index,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Flush the disk write cache for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn flush_cache(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::FlushCache {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Check if a torrent exists in the session and its handle is still valid.
    pub async fn is_valid(&self, info_hash: Id20) -> bool {
        let (tx, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(SessionCommand::IsValid {
                info_hash,
                reply: tx,
            })
            .await
            .is_err()
        {
            return false;
        }
        rx.await.unwrap_or(false)
    }

    /// Clear the error state on a torrent, resuming it if it was paused due to error.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn clear_error(&self, info_hash: Id20) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ClearError {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Get per-file open/mode status for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn file_status(
        &self,
        info_hash: Id20,
    ) -> crate::Result<Vec<crate::types::FileStatus>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::FileStatus {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Read the current torrent flags as a [`crate::types::TorrentFlags`] bitflag set.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn flags(&self, info_hash: Id20) -> crate::Result<crate::types::TorrentFlags> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::Flags {
                info_hash,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Set (enable) the specified torrent flags.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn set_flags(
        &self,
        info_hash: Id20,
        flags: crate::types::TorrentFlags,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::SetFlags {
                info_hash,
                flags,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Unset (disable) the specified torrent flags.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn unset_flags(
        &self,
        info_hash: Id20,
        flags: crate::types::TorrentFlags,
    ) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::UnsetFlags {
                info_hash,
                flags,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Immediately initiate a peer connection for a torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the connection or binding fails.
    pub async fn connect_peer(&self, info_hash: Id20, addr: SocketAddr) -> crate::Result<()> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::ConnectPeer {
                info_hash,
                addr,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Store an immutable item in the DHT (BEP 44).
    ///
    /// Returns the SHA-1 target hash of the stored value.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn dht_put_immutable(&self, value: Vec<u8>) -> crate::Result<Id20> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DhtPutImmutable { value, reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Retrieve an immutable item from the DHT (BEP 44).
    ///
    /// Returns `Some(value)` if found, `None` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn dht_get_immutable(&self, target: Id20) -> crate::Result<Option<Vec<u8>>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DhtGetImmutable { target, reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Store a mutable item in the DHT (BEP 44).
    ///
    /// `keypair_bytes` is a 32-byte Ed25519 seed. Returns the target hash.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn dht_put_mutable(
        &self,
        keypair_bytes: [u8; 32],
        value: Vec<u8>,
        seq: i64,
        salt: Vec<u8>,
    ) -> crate::Result<Id20> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DhtPutMutable {
                keypair_bytes,
                value,
                seq,
                salt,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    /// Retrieve a mutable item from the DHT (BEP 44).
    ///
    /// Returns `Some((value, seq))` if found, `None` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn dht_get_mutable(
        &self,
        public_key: [u8; 32],
        salt: Vec<u8>,
    ) -> crate::Result<Option<(Vec<u8>, i64)>> {
        let (tx, rx) = oneshot::channel();
        self.cmd_tx
            .send(SessionCommand::DhtGetMutable {
                public_key,
                salt,
                reply: tx,
            })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)?
    }

    // ── M121: Convenience API for future HTTP endpoints ──

    /// List all torrents as lightweight summaries.
    ///
    /// Fetches stats for each active torrent and converts to [`TorrentSummary`].
    /// Torrents that fail the stats query (e.g. shutting down) are silently skipped.
    ///
    /// # Errors
    ///
    /// Returns an error if the session is shut down.
    pub async fn list_torrent_summaries(&self) -> crate::Result<Vec<TorrentSummary>> {
        let ids = self.list_torrents().await?;
        let mut summaries = Vec::with_capacity(ids.len());
        for id in ids {
            if let Ok(stats) = self.torrent_stats(id).await {
                summaries.push(TorrentSummary::from(&stats));
            }
        }
        Ok(summaries)
    }

    /// Add a torrent from a magnet URI string.
    ///
    /// Parses the URI, extracts info hashes, and adds the magnet to the session.
    /// Returns the info hashes (v1 and/or v2) for the added torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent cannot be added or the session is shut down.
    pub async fn add_magnet_uri(&self, uri: &str) -> crate::Result<irontide_core::InfoHashes> {
        let magnet = irontide_core::Magnet::parse(uri)?;
        let info_hashes = magnet.info_hashes.clone();
        self.add_magnet(magnet).await?;
        Ok(info_hashes)
    }

    /// Add a torrent from raw .torrent file bytes.
    ///
    /// Auto-detects v1, v2, or hybrid format. Returns the info hashes for the
    /// added torrent.
    ///
    /// # Errors
    ///
    /// Returns an error if the torrent cannot be added or the session is shut down.
    pub async fn add_torrent_bytes(
        &self,
        bytes: &[u8],
    ) -> crate::Result<irontide_core::InfoHashes> {
        let meta = irontide_core::torrent_from_bytes_any(bytes)?;
        let info_hashes = meta.info_hashes();
        self.add_torrent_with_meta(meta, None).await?;
        Ok(info_hashes)
    }
}

// ---------------------------------------------------------------------------
// SessionActor — internal single-owner event loop
// ---------------------------------------------------------------------------

struct SessionActor {
    settings: Settings,
    /// M223 — self-loopback sender, so the spawned `handle_add_torrent`
    /// prep tasks can route their `CommitAddTorrent` result back through
    /// the same recv loop that owns the mutating session state.
    /// Cloned from the same sender the `SessionHandle` holds; carries
    /// the M221.1a timing wrapper so the commit hop is observable in
    /// the `queue_wait_ms` / `handler_ms` telemetry.
    commit_tx: SessionCmdSender,
    torrents: HashMap<Id20, TorrentEntry>,
    dht_v4: Option<DhtHandle>,
    dht_v6: Option<DhtHandle>,
    /// M173 Lane B (B6): broadcast surface for runtime `DhtHandle`
    /// replacement. `TorrentActor` consumers borrow a `DhtReceiver`
    /// instead of cloning `DhtHandle`, so a session-side DHT restart
    /// (B11) propagates to every torrent on the next `borrow()`.
    /// Initialised once at session start with the same value as the
    /// `dht_v4`/`dht_v6` clones; never written until B11.
    dht_v4_broadcast: irontide_dht::DhtBroadcast,
    dht_v6_broadcast: irontide_dht::DhtBroadcast,
    lsd: Option<crate::lsd::LsdHandle>,
    lsd_peers_rx: Option<mpsc::Receiver<(Id20, SocketAddr)>>,
    cmd_rx: mpsc::Receiver<(tokio::time::Instant, SessionCommand)>,
    alert_tx: broadcast::Sender<Alert>,
    alert_mask: Arc<AtomicU32>,
    global_upload_bucket: SharedBucket,
    global_download_bucket: SharedBucket,
    utp_socket: Option<irontide_utp::UtpSocket>,
    utp_socket_v6: Option<irontide_utp::UtpSocket>,
    nat: Option<irontide_nat::NatHandle>,
    nat_events_rx: Option<mpsc::Receiver<irontide_nat::NatEvent>>,
    ban_manager: SharedBanManager,
    ip_filter: SharedIpFilter,
    disk_manager: crate::disk::DiskManagerHandle,
    #[allow(dead_code)]
    disk_actor_handle: tokio::task::JoinHandle<()>,
    /// External IP discovered via NAT traversal or configured manually (BEP 40).
    external_ip: Option<std::net::IpAddr>,
    /// BEP 42: External IP consensus from DHT v4 KRPC responses.
    dht_v4_ip_rx: Option<mpsc::Receiver<std::net::IpAddr>>,
    /// BEP 42: External IP consensus from DHT v6 KRPC responses.
    dht_v6_ip_rx: Option<mpsc::Receiver<std::net::IpAddr>>,
    /// Registered extension plugins, shared with all `TorrentActors`.
    plugins: Arc<Vec<Box<dyn crate::extension::ExtensionPlugin>>>,
    /// I2P SAM session (if enabled).
    sam_session: Option<Arc<crate::i2p::SamSession>>,
    /// SSL manager for SSL torrent certificate handling (M42).
    ssl_manager: Option<Arc<crate::ssl_manager::SslManager>>,
    /// SSL/TLS TCP listener (separate port from the main listener) (M42).
    ssl_listener: Option<Box<dyn crate::transport::TransportListener>>,
    /// Channel receiving pre-validated inbound connections from the `ListenerTask` (M114).
    validated_conn_rx: mpsc::Receiver<crate::listener::IdentifiedConnection>,
    /// Registry of active info hashes shared with the `ListenerTask` (M114).
    /// INVARIANT: Must be updated whenever torrents are added/removed.
    /// If a new torrent-add path is added without updating this registry,
    /// inbound connections for that torrent will be silently rejected.
    info_hash_registry: Arc<DashMap<Id20, ()>>,
    /// Handle to keep the listener task alive; dropped on session shutdown
    /// (M114). M173 Lane B (B2) replaced the bare `JoinHandle` with
    /// `ListenerHandle` so the listen-port rebind path (B4) can call
    /// `shutdown_with_timeout` for a clean port swap.
    #[allow(dead_code)] // used by Drop sequence + B4 listen-port rebind
    _listener_task: crate::listener::ListenerHandle,
    /// M224 D3: global TCP-inbound connection cap, shared with the
    /// `ListenerTask`. `-1` = unlimited. Updated atomically from
    /// `handle_apply_settings` so the listener sees the new value on the
    /// next accept without restarting the task.
    max_connections_global: Arc<std::sync::atomic::AtomicI32>,
    /// M224 D3: live TCP-inbound connection count, shared with the
    /// `ListenerTask`. Incremented at TCP accept; decremented when the
    /// `LiveConnectionGuard` attached to the accepted connection drops.
    /// Kept here so future milestones (M225 outbound, observability) can
    /// read the live count without touching the listener.
    #[allow(dead_code)] // read via the M224 G1 integration test + future M225 observability.
    live_connections: Arc<std::sync::atomic::AtomicUsize>,
    /// Shared atomic session counters (M50).
    counters: Arc<crate::stats::SessionCounters>,
    /// Network transport factory for TCP operations (M51).
    factory: Arc<crate::transport::NetworkFactory>,
    /// Shared hash pool for parallel piece verification (M96).
    hash_pool: std::sync::Arc<crate::hash_pool::HashPool>,
    /// M170: qBt-compat category registry, shared with CRUD call paths.
    category_registry: Arc<parking_lot::RwLock<crate::category_manager::CategoryRegistry>>,
    /// M171: qBt-compat tag registry, shared with CRUD call paths.
    tag_registry: Arc<parking_lot::RwLock<crate::tag_manager::TagRegistry>>,
    /// M170: info hashes currently in the `remove_torrent_with_files`
    /// grace period. Guards against fast delete-then-re-add sequences
    /// that would otherwise race the file-deletion walker.
    deletion_grace: Arc<parking_lot::Mutex<std::collections::HashSet<Id20>>>,
    /// M173 Lane B: in-flight `apply_settings` guard. Concurrent
    /// `setPreferences` calls hit `ApplyError::ConcurrentReconfig`
    /// rather than interleaving rate-limiter / listener-rebind /
    /// DHT-restart phases. Wired by B11.
    #[allow(dead_code)] // wired by B11 — concurrent setPreferences guard
    reconfig_in_flight: crate::apply::ReconfigInFlight,
    self_alert_rx: broadcast::Receiver<Alert>,
    resume_save_notify: Arc<tokio::sync::Notify>,
    /// M226 Step 5: live settings broadcast to the engine-side OS
    /// notification dispatcher spawned in `start_full`. Updated from
    /// `handle_apply_settings` so `notify_on_complete` /
    /// `notify_on_error` toggles take effect on the very next alert
    /// without restarting the dispatcher task.
    notification_settings_tx: tokio::sync::watch::Sender<Settings>,
    /// M226 Step 5: held alive only for its `Drop` — when the
    /// `SessionActor` ends and this field drops, the matching
    /// `oneshot::Receiver` in the dispatcher resolves and the
    /// dispatcher loop exits cleanly. Belt-and-suspenders with the
    /// `alert_tx` broadcast closure (the dispatcher also exits on
    /// `RecvError::Closed`), since `alert_tx` is held by every
    /// outstanding `SessionHandle::subscribe()` consumer and may
    /// outlive the actor.
    #[allow(dead_code)]
    notification_shutdown_tx: oneshot::Sender<()>,
    /// M226 Step 6: triggers the watched-folder dispatcher to drop
    /// its current debouncer (releasing inotify FDs) and rebuild
    /// against the new path. Pinged by `handle_apply_settings` when
    /// the `SettingsDelta` carries a change on `watched_folder` or
    /// `delete_torrent_after_add`. Separate from the Settings watch
    /// channel because rate-limit / DHT / mask changes shouldn't
    /// cause inotify churn.
    watched_folder_changed: Arc<tokio::sync::Notify>,
    /// M226 Step 6: same Drop-as-shutdown pattern as
    /// [`Self::notification_shutdown_tx`].
    #[allow(dead_code)]
    watched_folder_shutdown_tx: oneshot::Sender<()>,
}

impl SessionActor {
    /// v0.173.1: shared helper for reader sites that used to read
    /// `TorrentEntry.meta` (a stale cache that was silently `None` forever
    /// for magnet-added torrents). Always queries the `TorrentActor` — the
    /// single source of truth for torrent metadata post-v0.173.1.
    ///
    /// Returns [`crate::Error::TorrentNotFound`] if `info_hash` isn't in the
    /// registry, [`crate::Error::MetadataNotReady`] if the actor has not yet
    /// assembled metadata (magnet pre-resolution), or propagates
    /// [`crate::Error::Shutdown`] if the actor has already exited.
    async fn get_entry_meta(&self, info_hash: Id20) -> crate::Result<irontide_core::TorrentMetaV1> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        entry
            .handle
            .get_meta()
            .await?
            .ok_or(crate::Error::MetadataNotReady(info_hash))
    }

    async fn run(mut self) {
        let mut refill_interval = tokio::time::interval(std::time::Duration::from_millis(100));
        refill_interval.tick().await; // skip first immediate tick

        let auto_manage_secs = self.settings.auto_manage_interval.max(1);
        let mut auto_manage_interval =
            tokio::time::interval(std::time::Duration::from_secs(auto_manage_secs));
        auto_manage_interval.tick().await; // skip first immediate tick

        // Periodic session stats timer (M50)
        let stats_interval_ms = self.settings.stats_report_interval;
        let mut stats_timer = if stats_interval_ms > 0 {
            Some(tokio::time::interval(std::time::Duration::from_millis(
                stats_interval_ms,
            )))
        } else {
            None
        };
        if let Some(ref mut t) = stats_timer {
            t.tick().await; // skip first immediate tick
        }

        // Periodic sample_infohashes timer (BEP 51, M111)
        let sample_interval_secs = self.settings.dht_sample_infohashes_interval;
        let mut sample_timer = if sample_interval_secs > 0 {
            Some(tokio::time::interval(std::time::Duration::from_secs(
                sample_interval_secs,
            )))
        } else {
            None
        };
        if let Some(ref mut t) = sample_timer {
            t.tick().await; // skip first immediate tick
        }

        // Periodic resume file save timer (M161)
        let mut resume_save_interval = if self.settings.save_resume_interval_secs > 0 {
            Some(tokio::time::interval(std::time::Duration::from_secs(
                self.settings.save_resume_interval_secs,
            )))
        } else {
            None
        };
        if let Some(ref mut t) = resume_save_interval {
            t.tick().await; // skip first immediate tick
        }

        // Auto-restore torrents from resume files on startup (M161 Phase 5).
        {
            let resume_dir = self.effective_resume_dir();
            let resume_files = crate::resume_file::scan_resume_dir(&resume_dir);
            if !resume_files.is_empty() {
                // Reuse the existing sequential restore logic from Phase 4.
                match self.handle_load_resume_state().await {
                    Ok(result) => {
                        info!(
                            restored = result.restored,
                            skipped = result.skipped,
                            failed = result.failed,
                            "auto-restored torrents on startup"
                        );
                    }
                    Err(e) => {
                        warn!("auto-restore on startup failed: {e}");
                    }
                }

                // Init throttle: restored torrents were queued inside
                // handle_load_resume_state when queueing_enabled. Run one
                // immediate evaluate_queue() so up to active_checking
                // torrents enter Checking right away (don't wait 30s).
                if self.settings.queueing_enabled {
                    self.evaluate_queue().await;
                }

                // Orphan cleanup: delete .resume files whose hex stem does not
                // match any info hash currently in the session.
                let active_hashes: std::collections::HashSet<String> = self
                    .torrents
                    .keys()
                    .map(|h| hex::encode(h.as_bytes()))
                    .collect();

                // Re-scan after load — some files may have been consumed.
                let current_files = crate::resume_file::scan_resume_dir(&resume_dir);
                for path in &current_files {
                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str())
                        && !active_hashes.contains(stem)
                    {
                        if let Err(e) = std::fs::remove_file(path) {
                            warn!(path = %path.display(), "failed to remove orphan resume file: {e}");
                        } else {
                            debug!(path = %path.display(), "removed orphan resume file");
                        }
                    }
                }
            }
        }

        loop {
            tokio::select! {
                cmd = self.cmd_rx.recv() => {
                    // M221.1a — per-command timing. `sent_at` is the
                    // instant the sender enqueued the command (via
                    // `SessionCmdSender::send`); `recv_at` is now.
                    // `queue_wait_ms` measures actor backlog; the
                    // post-match `handler_ms` covers the dispatch.
                    // Shutdown/None paths return early and skip the
                    // tracing emit — telemetry is intentionally absent
                    // for the terminal command.
                    let recv_at = tokio::time::Instant::now();
                    let queue_wait_ms = cmd.as_ref().map_or(0.0, |(sent_at, _)| {
                        recv_at.saturating_duration_since(*sent_at).as_secs_f64() * 1000.0
                    });
                    let cmd_name = cmd.as_ref().map_or("<closed>", |(_, c)| c.name());
                    let handler_start = tokio::time::Instant::now();
                    let cmd = cmd.map(|(_sent_at, c)| c);
                    match cmd {
                        Some(SessionCommand::AddTorrent {
                            meta,
                            storage,
                            download_dir,
                            reply,
                        }) => {
                            // M223 — spawn-per-add path. The heavy
                            // `disk_manager.register_torrent` +
                            // `TorrentHandle::from_torrent` work runs in a
                            // `tokio::spawn`'d task; results route back via
                            // `SessionCommand::CommitAddTorrent`. Legacy entry
                            // point: no tags available from the pre-M171
                            // command shape.
                            let setup: crate::Result<AddTorrentPrepBundle> = (|| {
                                let info_hash = meta.as_v1().map_or_else(
                                    || meta.info_hashes().best_v1(),
                                    |v| v.info_hash,
                                );
                                if self.torrents.contains_key(&info_hash) {
                                    return Err(crate::Error::DuplicateTorrent(info_hash));
                                }
                                if self.torrents.len() >= self.settings.max_torrents {
                                    return Err(crate::Error::SessionAtCapacity(
                                        self.settings.max_torrents,
                                    ));
                                }
                                Ok(self.build_add_torrent_prep_bundle(
                                    *meta,
                                    storage,
                                    download_dir,
                                    Vec::new(),
                                    None,
                                ))
                            })();
                            match setup {
                                Ok(bundle) => self.try_spawn_add_torrent(bundle, reply),
                                Err(e) => {
                                    let _ = reply.send(Err(e));
                                }
                            }
                        }
                        Some(SessionCommand::CommitAddTorrent { result, reply }) => {
                            // M223 — feedback variant: the spawn-per-add prep
                            // phase finished. `commit_add_torrent` does the
                            // mutating fixup on the actor (insert into
                            // `self.torrents`, queue position, alert, LSD,
                            // M170 post-hooks) using the precomputed
                            // `is_private` from the bundle.
                            let id = self.commit_add_torrent(result).await;
                            let _ = reply.send(id);
                        }
                        Some(SessionCommand::AddMagnet { magnet, download_dir, reply }) => {
                            // Legacy entry point: no tags available from the
                            // pre-M171 command shape.
                            let result = self
                                .handle_add_magnet(magnet, download_dir, Vec::new())
                                .await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::RemoveTorrent { info_hash, reply }) => {
                            let result = self.handle_remove_torrent(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::PauseTorrent { info_hash, reply }) => {
                            let result = self.handle_pause_torrent(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ResumeTorrent { info_hash, reply }) => {
                            let result = self.handle_resume_torrent(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ForceResumeTorrent { info_hash, reply }) => {
                            let result = self.handle_force_resume_torrent(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetTorrentSeedRatio { info_hash, limit, reply }) => {
                            let result = self.handle_set_torrent_seed_ratio(info_hash, limit).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::TorrentStats { info_hash, reply }) => {
                            let result = self.handle_torrent_stats(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::TorrentInfo { info_hash, reply }) => {
                            // v0.173.1: handle_torrent_info is now async because
                            // it queries the TorrentActor for metadata (Class A
                            // architectural fix — no more TorrentEntry.meta cache).
                            let result = self.handle_torrent_info(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ListTorrents { reply }) => {
                            let list: Vec<Id20> = self.torrents.keys().copied().collect();
                            let _ = reply.send(list);
                        }
                        Some(SessionCommand::SessionStats { reply }) => {
                            let stats = self.make_session_stats().await;
                            let _ = reply.send(stats);
                        }
                        Some(SessionCommand::SaveTorrentResumeData { info_hash, reply }) => {
                            let result = self.handle_save_torrent_resume(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SaveSessionState { reply }) => {
                            let result = self.handle_save_session_state().await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::LoadResumeState { reply }) => {
                            let result = self.handle_load_resume_state().await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::QueuePosition { info_hash, reply }) => {
                            let result = match self.torrents.get(&info_hash) {
                                Some(entry) => Ok(entry.queue_position),
                                None => Err(crate::Error::TorrentNotFound(info_hash)),
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetQueuePosition { info_hash, pos, reply }) => {
                            let result = self.handle_set_queue_position(info_hash, pos);
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::QueuePositionUp { info_hash, reply }) => {
                            let result = self.handle_queue_move(info_hash, crate::queue::move_up);
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::QueuePositionDown { info_hash, reply }) => {
                            let result = self.handle_queue_move(info_hash, crate::queue::move_down);
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::QueuePositionTop { info_hash, reply }) => {
                            let result = self.handle_queue_move(info_hash, crate::queue::move_top);
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::QueuePositionBottom { info_hash, reply }) => {
                            let result = self.handle_queue_move(info_hash, crate::queue::move_bottom);
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::BanPeer { ip, reply }) => {
                            self.ban_manager.write().ban(ip);
                            let _ = reply.send(());
                        }
                        Some(SessionCommand::UnbanPeer { ip, reply }) => {
                            let was_banned = self.ban_manager.write().unban(&ip);
                            let _ = reply.send(was_banned);
                        }
                        Some(SessionCommand::BannedPeers { reply }) => {
                            let list: Vec<IpAddr> = self.ban_manager.read()
                                .banned_list().iter().copied().collect();
                            let _ = reply.send(list);
                        }
                        Some(SessionCommand::SetIpFilter { filter, reply }) => {
                            *self.ip_filter.write() = filter;
                            let _ = reply.send(());
                        }
                        Some(SessionCommand::GetIpFilter { reply }) => {
                            let filter = self.ip_filter.read().clone();
                            let _ = reply.send(filter);
                        }
                        Some(SessionCommand::GetSettings { reply }) => {
                            let _ = reply.send(self.settings.clone());
                        }
                        Some(SessionCommand::ApplySettings { settings, reply }) => {
                            let result = self.handle_apply_settings(*settings);
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DhtNodeCount { reply }) => {
                            // Sum routing-table sizes across both DHT
                            // instances. Either instance erroring or being
                            // absent contributes 0 — the qBt wire field is
                            // a best-effort gauge, not a strict invariant.
                            let mut total: usize = 0;
                            if let Some(dht) = &self.dht_v4
                                && let Ok(c) = dht.node_count().await
                            {
                                total += c;
                            }
                            if let Some(dht) = &self.dht_v6
                                && let Ok(c) = dht.node_count().await
                            {
                                total += c;
                            }
                            let _ = reply.send(total);
                        }
                        Some(SessionCommand::MoveTorrentStorage { info_hash, new_path, reply }) => {
                            let result = self.handle_move_torrent_storage(info_hash, new_path).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::AddPeers { info_hash, peers, source, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.add_peers(peers, source).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::OpenFile { info_hash, file_index, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.open_file(file_index).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ForceReannounce { info_hash, reply }) => {
                            let result = match self.torrents.get(&info_hash) {
                                Some(entry) => {
                                    entry.handle.force_reannounce().await
                                }
                                None => Err(crate::Error::TorrentNotFound(info_hash)),
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::TrackerList { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.tracker_list().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetPeerSourceCounts { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.peer_source_counts().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::QueryUnchokeDurations { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.query_unchoke_durations().await.ok()
                            } else {
                                None
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetWebSeedStats { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.get_web_seed_stats().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetWebSeeds { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.get_web_seeds().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetPieceStates { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.get_piece_states().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetPieceHashes { info_hash, offset, limit, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.get_piece_hashes(offset, limit).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::Scrape { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.scrape().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetFilePriority { info_hash, index, priority, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_file_priority(index, priority).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::FilePriorities { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.file_priorities().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetDownloadLimit { info_hash, bytes_per_sec, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_download_limit(bytes_per_sec).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetUploadLimit { info_hash, bytes_per_sec, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_upload_limit(bytes_per_sec).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DownloadLimit { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.download_limit().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::UploadLimit { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.upload_limit().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetSequentialDownload { info_hash, enabled, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_sequential_download(enabled).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::IsSequentialDownload { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.is_sequential_download().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetSuperSeeding { info_hash, enabled, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_super_seeding(enabled).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::IsSuperSeeding { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.is_super_seeding().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetSeedMode { info_hash, enabled, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_seed_mode(enabled).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::AddTracker { info_hash, url, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.add_tracker(url).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ReplaceTrackers { info_hash, urls, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.replace_trackers(urls).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ForceRecheck { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.force_recheck().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::RenameFile { info_hash, file_index, new_name, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.rename_file(file_index, new_name).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetMaxConnections { info_hash, limit, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_max_connections(limit).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::MaxConnections { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.max_connections().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetMaxUploads { info_hash, limit, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_max_uploads(limit).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::MaxUploads { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.max_uploads().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetPeerInfo { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.get_peer_info().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::GetDownloadQueue { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.get_download_queue().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::HavePiece { info_hash, index, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.have_piece(index).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::PieceAvailability { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.piece_availability().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::FileProgress { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.file_progress().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::InfoHashesQuery { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.info_hashes().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::TorrentFile { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.torrent_file().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::TorrentFileV2 { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.torrent_file_v2().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        #[cfg(feature = "test-util")]
                        Some(SessionCommand::TestInjectMetadata {
                            info_hash,
                            info_bytes,
                            reply,
                        }) => {
                            let result = match self.torrents.get(&info_hash) {
                                Some(entry) => {
                                    entry.handle.test_inject_metadata(info_bytes).await
                                }
                                None => Err(crate::Error::TorrentNotFound(info_hash)),
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ForceDhtAnnounce { info_hash, reply }) => {
                            // v0.173.2: BEP 27 enforcement on the DHT path. M173.1 fixed the
                            // LSD leak vector but missed DHT — private torrents would still
                            // announce their info hash to DHT and leak peer IPs. Mirrors the
                            // LSD pattern at session.rs:3541-3563.
                            let result = match self.torrents.get(&info_hash) {
                                Some(entry) => {
                                    if entry.is_private().await {
                                        Err(crate::Error::InvalidSettings(
                                            "DHT disabled for private torrent".into(),
                                        ))
                                    } else {
                                        entry.handle.force_dht_announce().await
                                    }
                                }
                                None => Err(crate::Error::TorrentNotFound(info_hash)),
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ForceLsdAnnounce { info_hash, reply }) => {
                            // LSD is session-level: verify the torrent exists, then announce directly.
                            //
                            // v0.173.1: is_private is now async. Match guards can't be async, so
                            // evaluate the flag up front and branch on the bool.
                            let result = match self.torrents.get(&info_hash) {
                                Some(entry) => {
                                    if entry.is_private().await {
                                        // BEP 27: private torrents must not use LSD
                                        Err(crate::Error::InvalidSettings(
                                            "LSD disabled for private torrent".into(),
                                        ))
                                    } else {
                                        if let Some(ref lsd) = self.lsd {
                                            lsd.announce(vec![info_hash]).await;
                                        }
                                        Ok(())
                                    }
                                }
                                None => Err(crate::Error::TorrentNotFound(info_hash)),
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ReadPiece { info_hash, index, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.read_piece(index).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::FlushCache { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.flush_cache().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::IsValid { info_hash, reply }) => {
                            let valid = self.torrents.get(&info_hash)
                                .is_some_and(|e| e.handle.is_valid());
                            let _ = reply.send(valid);
                        }
                        Some(SessionCommand::ClearError { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.clear_error().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::FileStatus { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.file_status().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::Flags { info_hash, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.flags().await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::SetFlags { info_hash, flags, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.set_flags(flags).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::UnsetFlags { info_hash, flags, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.unset_flags(flags).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ConnectPeer { info_hash, addr, reply }) => {
                            let result = if let Some(entry) = self.torrents.get(&info_hash) {
                                entry.handle.connect_peer(addr).await
                            } else {
                                Err(crate::Error::TorrentNotFound(info_hash))
                            };
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DhtPutImmutable { value, reply }) => {
                            let result = self.handle_dht_put_immutable(value).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DhtGetImmutable { target, reply }) => {
                            let result = self.handle_dht_get_immutable(target).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DhtPutMutable { keypair_bytes, value, seq, salt, reply }) => {
                            let result = self.handle_dht_put_mutable(keypair_bytes, value, seq, salt).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DhtGetMutable { public_key, salt, reply }) => {
                            let result = self.handle_dht_get_mutable(public_key, salt).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::PostSessionStats) => {
                            self.fire_stats_alert();
                        }
                        Some(SessionCommand::SaveResumeState { reply }) => {
                            let count = self.save_dirty_resume_files().await;
                            let _ = reply.send(Ok(count));
                        }
                        Some(SessionCommand::AddTorrentM170 { params, reply }) => {
                            // M223 — bytes branch goes through the
                            // spawn-per-add path; magnet branch stays inline.
                            // The dispatcher consumes `reply` directly.
                            self.dispatch_add_torrent_m170(*params, reply).await;
                        }
                        Some(SessionCommand::CreateCategory { name, save_path, reply }) => {
                            let result = self.handle_create_category(name, save_path).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::EditCategory { name, save_path, reply }) => {
                            let result = self.handle_edit_category(name, save_path).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::RemoveCategories { names, reply }) => {
                            let result = self.handle_remove_categories(names).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::ListCategories { reply }) => {
                            let snapshot = self.category_registry.read().list();
                            let _ = reply.send(snapshot);
                        }
                        Some(SessionCommand::CreateTags { names, reply }) => {
                            let results: Vec<_> = {
                                let mut reg = self.tag_registry.write();
                                names.into_iter().map(|n| reg.create(n)).collect()
                            };
                            // Persist any successful creates. Persistence failures
                            // warn but don't change the per-call reply (matches
                            // CreateCategory).
                            if let Err(e) = self.persist_tag_registry().await {
                                tracing::warn!(
                                    error = %e,
                                    "failed to persist tag registry after CreateTags"
                                );
                            }
                            let _ = reply.send(results);
                        }
                        Some(SessionCommand::DeleteTags { names, reply }) => {
                            let removed = self.handle_delete_tags(names).await;
                            let _ = reply.send(removed);
                        }
                        Some(SessionCommand::ListTags { reply }) => {
                            let names = self.tag_registry.read().list();
                            let _ = reply.send(names);
                        }
                        Some(SessionCommand::AddTagsToTorrents { info_hashes, tags, reply }) => {
                            let res = self.handle_add_tags_to_torrents(info_hashes, tags).await;
                            let _ = reply.send(res);
                        }
                        Some(SessionCommand::RemoveTagsFromTorrents { info_hashes, tags, reply }) => {
                            let res = self
                                .handle_remove_tags_from_torrents(info_hashes, tags)
                                .await;
                            let _ = reply.send(res);
                        }
                        Some(SessionCommand::RemoveTorrentWithFiles { info_hash, reply }) => {
                            let result = self.handle_remove_torrent_with_files(info_hash).await;
                            let _ = reply.send(result);
                        }
                        Some(SessionCommand::DebugState { reply }) => {
                            let state = self.make_debug_state().await;
                            let _ = reply.send(state);
                        }
                        Some(SessionCommand::Shutdown) | None => {
                            self.shutdown_all().await;
                            return;
                        }
                    }
                    // M221.1a — emit per-command timing on the
                    // bench-harness target. Filtering happens in the
                    // tracing subscriber (parallel-7 harness sets
                    // RUST_LOG=irontide_session::cmd_timing=info); the
                    // emit is unconditional so any external consumer
                    // can opt in.
                    let handler_ms = handler_start.elapsed().as_secs_f64() * 1000.0;
                    info!(
                        target: "irontide_session::cmd_timing",
                        cmd = cmd_name,
                        queue_wait_ms = queue_wait_ms,
                        handler_ms = handler_ms,
                        "session_cmd"
                    );
                }
                result = async {
                    match &mut self.lsd_peers_rx {
                        Some(rx) => rx.recv().await,
                        None => std::future::pending().await,
                    }
                } => {
                    if let Some((info_hash, peer_addr)) = result
                        && let Some(entry) = self.torrents.get(&info_hash)
                    {
                        // v0.173.1: is_private is async — can't chain it into the let-else
                        // condition list, evaluate separately before add_peers.
                        let is_priv = entry.is_private().await;
                        if !is_priv {
                            // BEP 27: reject LSD peers for private torrents
                            let _ = entry.handle.add_peers(vec![peer_addr], crate::peer_state::PeerSource::Lsd).await;
                        }
                    }
                }
                // Pre-validated inbound connections from ListenerTask (M114)
                Some(conn) = self.validated_conn_rx.recv() => {
                    self.handle_identified_inbound(conn);
                }
                // SSL inbound connections (M42)
                result = async {
                    if let Some(ref mut listener) = self.ssl_listener {
                        listener.accept().await
                    } else {
                        std::future::pending().await
                    }
                } => {
                    if let Ok((stream, addr)) = result {
                        self.handle_ssl_incoming(stream, addr).await;
                    }
                }
                // Global rate limiter refill (100ms)
                _ = refill_interval.tick() => {
                    let elapsed = std::time::Duration::from_millis(100);
                    self.global_upload_bucket.lock().refill(elapsed);
                    self.global_download_bucket.lock().refill(elapsed);
                }
                // Auto-manage queue evaluation
                _ = auto_manage_interval.tick() => {
                    self.evaluate_queue().await;
                }
                // Checking-complete trigger: when a torrent exits Checking
                // state, re-evaluate immediately so the next candidate
                // promotes without waiting for the 30s periodic tick.
                alert = self.self_alert_rx.recv() => {
                    if let Ok(alert) = alert
                        && matches!(
                            alert.kind,
                            AlertKind::StateChanged {
                                prev_state: TorrentState::Checking,
                                new_state,
                                ..
                            } if new_state != TorrentState::Checking
                        )
                    {
                        self.evaluate_queue().await;
                    }
                }
                // NAT port mapping events
                event = recv_nat_event(&mut self.nat_events_rx) => {
                    match event {
                        irontide_nat::NatEvent::MappingSucceeded { port, protocol } => {
                            info!(port, %protocol, "port mapping succeeded");
                            post_alert(
                                &self.alert_tx,
                                &self.alert_mask,
                                AlertKind::PortMappingSucceeded { port, protocol },
                            );
                        }
                        irontide_nat::NatEvent::MappingFailed { port, message } => {
                            warn!(port, %message, "port mapping failed");
                            post_alert(
                                &self.alert_tx,
                                &self.alert_mask,
                                AlertKind::PortMappingFailed { port, message },
                            );
                        }
                        irontide_nat::NatEvent::ExternalIpDiscovered { ip } => {
                            info!(%ip, "external IP discovered via NAT traversal");
                            self.external_ip = Some(ip);
                            // Propagate to all active torrents for BEP 40 peer priority.
                            for entry in self.torrents.values() {
                                let _ = entry.handle.update_external_ip(ip).await;
                            }
                            // BEP 42: notify DHT instances of external IP
                            if let Some(dht) = &self.dht_v4 {
                                let _ = dht.update_external_ip(ip, irontide_dht::IpVoteSource::Nat).await;
                            }
                            if let Some(dht) = &self.dht_v6 {
                                let _ = dht.update_external_ip(ip, irontide_dht::IpVoteSource::Nat).await;
                            }
                        }
                    }
                }
                // BEP 42: DHT v4 external IP consensus
                Some(ip) = recv_dht_ip(&mut self.dht_v4_ip_rx) => {
                    info!(%ip, "external IP discovered via DHT v4 (BEP 42)");
                    self.external_ip = Some(ip);
                    for entry in self.torrents.values() {
                        let _ = entry.handle.update_external_ip(ip).await;
                    }
                }
                // BEP 42: DHT v6 external IP consensus
                Some(ip) = recv_dht_ip(&mut self.dht_v6_ip_rx) => {
                    info!(%ip, "external IP discovered via DHT v6 (BEP 42)");
                    self.external_ip = Some(ip);
                    for entry in self.torrents.values() {
                        let _ = entry.handle.update_external_ip(ip).await;
                    }
                }
                // Periodic session stats (M50)
                _ = async {
                    match &mut stats_timer {
                        Some(t) => t.tick().await,
                        None => std::future::pending().await,
                    }
                } => {
                    self.fire_stats_alert();
                }
                // Periodic sample_infohashes (BEP 51, M111)
                _ = async {
                    match &mut sample_timer {
                        Some(t) => t.tick().await,
                        None => std::future::pending().await,
                    }
                } => {
                    self.fire_sample_infohashes().await;
                }
                // Periodic resume file save (M161)
                _ = async {
                    match &mut resume_save_interval {
                        Some(t) => t.tick().await,
                        None => std::future::pending().await,
                    }
                } => {
                    let count = self.save_dirty_resume_files().await;
                    if count > 0 {
                        info!(count, "periodic resume save completed");
                    }
                }
                // Periodic resume save interval rebuild (M225)
                () = self.resume_save_notify.notified() => {
                    resume_save_interval = if self.settings.save_resume_interval_secs > 0 {
                        Some(tokio::time::interval(std::time::Duration::from_secs(
                            self.settings.save_resume_interval_secs,
                        )))
                    } else {
                        None
                    };
                    if let Some(ref mut t) = resume_save_interval {
                        t.tick().await; // skip first immediate tick
                    }
                }
            }
        }
    }

    /// Return clones of global buckets if they have a non-zero rate, else None.
    fn global_buckets_if_limited(&self) -> (Option<SharedBucket>, Option<SharedBucket>) {
        let up = if self.settings.upload_rate_limit > 0 {
            Some(Arc::clone(&self.global_upload_bucket))
        } else {
            None
        };
        let down = if self.settings.download_rate_limit > 0 {
            Some(Arc::clone(&self.global_download_bucket))
        } else {
            None
        };
        (up, down)
    }

    fn make_slot_tuner(&self) -> crate::slot_tuner::SlotTuner {
        if self.settings.auto_upload_slots {
            crate::slot_tuner::SlotTuner::new(
                4, // initial slots
                self.settings.auto_upload_slots_min,
                self.settings.auto_upload_slots_max,
            )
        } else {
            crate::slot_tuner::SlotTuner::disabled(4)
        }
    }

    fn make_torrent_config(&self) -> TorrentConfig {
        TorrentConfig::from(&self.settings)
    }

    /// Returns the next available queue position (one past the max).
    fn next_queue_position(&self) -> i32 {
        self.torrents
            .values()
            .filter(|e| e.auto_managed)
            .map(|e| e.queue_position)
            .max()
            .map_or(0, |m| m + 1)
    }

    /// Inline add-torrent path: builds the prep bundle on the actor,
    /// runs prepare + commit phases sequentially without spawning. Used
    /// by the resume-restore startup path (single-threaded by
    /// construction) and the `handle_add_torrent_with_params` M170
    /// helper. The `AddTorrent` and `AddTorrentM170` recv arms call
    /// `try_spawn_add_torrent` instead — same prep + commit primitives,
    /// but the prep runs in a `tokio::spawn` and the commit hop returns
    /// via `SessionCommand::CommitAddTorrent` (M223).
    async fn handle_add_torrent(
        &mut self,
        torrent_meta: irontide_core::TorrentMeta,
        storage: Option<Arc<dyn TorrentStorage>>,
        download_dir: Option<PathBuf>,
        tags: Vec<String>,
    ) -> crate::Result<Id20> {
        let info_hash = torrent_meta
            .as_v1()
            .map_or_else(|| torrent_meta.info_hashes().best_v1(), |v| v.info_hash);
        if self.torrents.contains_key(&info_hash) {
            return Err(crate::Error::DuplicateTorrent(info_hash));
        }
        if self.torrents.len() >= self.settings.max_torrents {
            return Err(crate::Error::SessionAtCapacity(self.settings.max_torrents));
        }
        let bundle =
            self.build_add_torrent_prep_bundle(torrent_meta, storage, download_dir, tags, None);
        let prep = prepare_add_torrent_off_actor(bundle).await;
        self.commit_add_torrent(prep).await
    }

    /// M223 — build the off-actor add-torrent prep bundle synchronously
    /// from session state. Cheap Arc-clones + a single
    /// `make_torrent_config` snapshot; never awaits, so it stays on the
    /// actor without contributing to the queue-wait stack.
    fn build_add_torrent_prep_bundle(
        &self,
        torrent_meta: irontide_core::TorrentMeta,
        storage: Option<Arc<dyn TorrentStorage>>,
        download_dir: Option<PathBuf>,
        tags: Vec<String>,
        m170_post: Option<M170PostAdd>,
    ) -> AddTorrentPrepBundle {
        let mut torrent_config = self.make_torrent_config();
        if let Some(dir) = download_dir {
            torrent_config.download_dir = dir;
        }
        // M171: bake tags into the config BEFORE the actor is constructed so
        // the first `stats()` snapshot already carries them — no post-add
        // spawn race. An empty vec is a no-op but still replaces any
        // session-level default (currently also empty).
        torrent_config.tags = tags;

        let (global_up, global_down) = self.global_buckets_if_limited();
        let slot_tuner = self.make_slot_tuner();

        AddTorrentPrepBundle {
            torrent_meta,
            storage_override: storage,
            torrent_config,
            disk_manager: self.disk_manager.clone(),
            dht_v4_broadcast: self.dht_v4_broadcast.clone(),
            dht_v6_broadcast: self.dht_v6_broadcast.clone(),
            global_up,
            global_down,
            slot_tuner,
            alert_tx: self.alert_tx.clone(),
            alert_mask: Arc::clone(&self.alert_mask),
            utp_socket: self.utp_socket.clone(),
            utp_socket_v6: self.utp_socket_v6.clone(),
            ban_manager: Arc::clone(&self.ban_manager),
            ip_filter: Arc::clone(&self.ip_filter),
            plugins: Arc::clone(&self.plugins),
            sam_session: self.sam_session.clone(),
            ssl_manager: self.ssl_manager.clone(),
            factory: Arc::clone(&self.factory),
            hash_pool: Arc::clone(&self.hash_pool),
            counters: Arc::clone(&self.counters),
            m170_post,
        }
    }

    /// M223 — commit phase of the spawn-per-add fix. Mutates session
    /// state (insert into `self.torrents`, info-hash registry, queue
    /// position, alert, LSD announce, M170 post-hooks) using the
    /// success-path payload from `prepare_add_torrent_off_actor`. On
    /// `Err` from prep, returns the error untouched.
    async fn commit_add_torrent(
        &mut self,
        prep: crate::Result<PreparedAddTorrent>,
    ) -> crate::Result<Id20> {
        let PreparedAddTorrent {
            handle,
            info_hash,
            is_private,
            m170_post,
        } = prep?;
        // Re-check dup + capacity: parallel adds may both pass the
        // pre-spawn check, then race the commit. The later one fails
        // here, and dropping `handle` triggers the spawned TorrentActor's
        // graceful shutdown (its cmd_tx receiver hangs up → recv returns
        // None → actor exits).
        if self.torrents.contains_key(&info_hash) {
            drop(handle);
            return Err(crate::Error::DuplicateTorrent(info_hash));
        }
        if self.torrents.len() >= self.settings.max_torrents {
            drop(handle);
            return Err(crate::Error::SessionAtCapacity(self.settings.max_torrents));
        }
        self.torrents.insert(
            info_hash,
            TorrentEntry {
                handle,
                queue_position: -1,
                auto_managed: true,
                started_at: Some(tokio::time::Instant::now()),
                smoothed_download_rate: f64::MAX,
                smoothed_upload_rate: f64::MAX,
            },
        );
        self.info_hash_registry.insert(info_hash, ());

        // Assign queue position for auto-managed torrents
        let pos = self.next_queue_position();
        if let Some(entry) = self.torrents.get_mut(&info_hash)
            && entry.auto_managed
        {
            entry.queue_position = pos;
        }

        info!(%info_hash, "torrent added to session");
        // M223 — `TorrentAdded` is posted in `prepare_add_torrent_off_actor`
        // (BEFORE the `commit_tx.send.await` yield) to preserve the alert
        // ordering invariant under spawn-per-add. See the comment there.
        // BEP 27: private torrents must not use LSD. `is_private` is
        // precomputed from `meta.info.private == Some(1)` in the prep
        // bundle, so the commit arm needs no async query.
        if let Some(ref lsd) = self.lsd
            && !is_private
        {
            lsd.announce(vec![info_hash]).await;
        }
        // M170 post-add hooks (category + paused-on-add) for the
        // `AddTorrentM170` path. Always `None` for the legacy
        // `AddTorrent` path.
        if let Some(M170PostAdd { category, paused }) = m170_post {
            self.apply_post_add_m170(info_hash, category, paused);
        }
        Ok(info_hash)
    }

    /// M223 — recv-arm helper: spawn the prep phase off the actor,
    /// route the result back via `CommitAddTorrent`. Consumes `reply`,
    /// so callers must not also send to it.
    fn try_spawn_add_torrent(
        &self,
        bundle: AddTorrentPrepBundle,
        reply: oneshot::Sender<crate::Result<Id20>>,
    ) {
        let commit_tx = self.commit_tx.clone();
        tokio::spawn(async move {
            let result = prepare_add_torrent_off_actor(bundle).await;
            if commit_tx
                .send(SessionCommand::CommitAddTorrent { result, reply })
                .await
                .is_err()
            {
                // Session is shutting down; the receiver is gone too.
                // The `reply` oneshot was moved into the variant which
                // got dropped, so the original caller observes a closed
                // channel — the right shutdown signal.
                warn!("M223 prep task: commit_tx send failed (session shutting down)");
            }
        });
    }

    async fn handle_add_magnet(
        &mut self,
        magnet: Magnet,
        download_dir: Option<PathBuf>,
        tags: Vec<String>,
    ) -> crate::Result<Id20> {
        let info_hash = magnet.info_hash();
        let display_name = magnet.display_name.clone().unwrap_or_default();
        if self.torrents.contains_key(&info_hash) {
            return Err(crate::Error::DuplicateTorrent(info_hash));
        }
        if self.torrents.len() >= self.settings.max_torrents {
            return Err(crate::Error::SessionAtCapacity(self.settings.max_torrents));
        }
        let mut config = self.make_torrent_config();
        if let Some(dir) = download_dir {
            config.download_dir = dir;
        }
        // M171: bake tags into the config BEFORE the actor is constructed so
        // the first `stats()` snapshot already carries them — no post-add
        // spawn race. An empty vec is a no-op but still replaces any
        // session-level default (currently also empty).
        config.tags = tags;
        let (global_up, global_down) = self.global_buckets_if_limited();
        let slot_tuner = self.make_slot_tuner();
        let handle = TorrentHandle::from_magnet(
            magnet,
            self.disk_manager.clone(),
            config,
            self.dht_v4_broadcast.subscribe(),
            self.dht_v6_broadcast.subscribe(),
            global_up,
            global_down,
            slot_tuner,
            self.alert_tx.clone(),
            Arc::clone(&self.alert_mask),
            self.utp_socket.clone(),
            self.utp_socket_v6.clone(),
            Arc::clone(&self.ban_manager),
            Arc::clone(&self.ip_filter),
            Arc::clone(&self.plugins),
            self.sam_session.clone(),
            self.ssl_manager.clone(),
            Arc::clone(&self.factory),
            Some(Arc::clone(&self.hash_pool)),
            Arc::clone(&self.counters),
        )
        .await?;
        // M147: Spawn background metadata resolver before registering.
        // This races against the TorrentActor's own FetchingMetadata phase —
        // first to resolve wins.
        self.spawn_metadata_resolver(info_hash, &handle);

        self.torrents.insert(
            info_hash,
            TorrentEntry {
                handle,
                queue_position: -1,
                auto_managed: true,
                started_at: Some(tokio::time::Instant::now()),
                smoothed_download_rate: f64::MAX,
                smoothed_upload_rate: f64::MAX,
            },
        );
        self.info_hash_registry.insert(info_hash, ());

        // Assign queue position for auto-managed torrents
        let pos = self.next_queue_position();
        if let Some(entry) = self.torrents.get_mut(&info_hash)
            && entry.auto_managed
        {
            entry.queue_position = pos;
        }

        info!(%info_hash, "magnet torrent added to session");
        post_alert(
            &self.alert_tx,
            &self.alert_mask,
            AlertKind::TorrentAdded {
                info_hash,
                name: display_name,
            },
        );
        // BEP 27: magnet metadata not available yet — we allow this one-time LAN
        // announce. Once metadata resolves, all subsequent LSD ops are gated by
        // is_private() checks in ForceLsdAnnounce and lsd_peers_rx handlers.
        if let Some(ref lsd) = self.lsd {
            lsd.announce(vec![info_hash]).await;
        }
        Ok(info_hash)
    }

    /// M147: Spawn a background task that pre-resolves magnet metadata via DHT.
    ///
    /// The resolver connects to peers discovered via DHT `get_peers`, performs
    /// BT + BEP 10 extension + BEP 9 `ut_metadata` exchanges, and sends the
    /// assembled metadata back to the `TorrentActor` via `PreResolvedMetadata`.
    /// This races against the `TorrentActor`'s own `FetchingMetadata` phase.
    fn spawn_metadata_resolver(&self, info_hash: Id20, torrent_handle: &TorrentHandle) {
        let dht = match self.dht_v4 {
            Some(ref dht) => dht.clone(),
            None => return, // No DHT = skip background resolution
        };
        let factory = Arc::clone(&self.factory);
        let connect_timeout = std::time::Duration::from_secs(self.settings.peer_connect_timeout);
        let handle = torrent_handle.clone();

        tokio::spawn(async move {
            let peer_rx = match dht.get_peers(info_hash).await {
                Ok(rx) => rx,
                Err(e) => {
                    debug!(
                        %info_hash,
                        "metadata resolver: failed to start DHT get_peers: {e}"
                    );
                    return;
                }
            };

            let peer_id = irontide_core::PeerId::generate().0;
            match crate::metadata_resolver::resolve_metadata(
                info_hash,
                peer_id,
                peer_rx,
                factory,
                connect_timeout,
                crate::metadata_resolver::DEFAULT_MAX_CONCURRENT,
            )
            .await
            {
                Ok((meta, peers)) => {
                    let info_bytes = if let Some(b) = meta.info_bytes {
                        b.to_vec()
                    } else {
                        match irontide_bencode::to_bytes(&meta.info) {
                            Ok(bytes) => bytes,
                            Err(e) => {
                                debug!(
                                    %info_hash,
                                    "metadata resolver: failed to re-encode info dict: {e}"
                                );
                                return;
                            }
                        }
                    };
                    debug!(
                        %info_hash,
                        num_peers = peers.len(),
                        "metadata resolver: pre-resolved metadata, sending to torrent actor"
                    );
                    handle.send_pre_resolved_metadata(info_bytes, peers);
                }
                Err(e) => {
                    debug!(
                        %info_hash,
                        "metadata resolver: failed to resolve metadata: {e}"
                    );
                }
            }
        });
    }

    async fn handle_remove_torrent(&mut self, info_hash: Id20) -> crate::Result<()> {
        let entry = self
            .torrents
            .remove(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        self.info_hash_registry.remove(&info_hash);
        let was_auto_managed = entry.auto_managed;
        let removed_position = entry.queue_position;
        entry.handle.shutdown().await?;
        self.disk_manager.unregister_torrent(info_hash).await;

        // Shift queue positions for remaining auto-managed torrents
        if was_auto_managed && removed_position >= 0 {
            let mut entries = self.queue_entries();
            let changed = crate::queue::remove_position(&mut entries, removed_position);
            self.apply_queue_changes(&changed);
        }

        // Delete the resume file for this torrent so it is not restored
        // on the next startup. Errors are logged but not propagated — the
        // torrent is already removed from the in-memory state.
        let resume_dir = self.effective_resume_dir();
        if let Err(e) = crate::resume_file::delete_resume_file(&resume_dir, &info_hash) {
            // NotFound is expected when no resume file was ever written.
            if e.kind() != std::io::ErrorKind::NotFound {
                warn!(%info_hash, "failed to delete resume file on removal: {e}");
            }
        }

        info!(%info_hash, "torrent removed from session");
        post_alert(
            &self.alert_tx,
            &self.alert_mask,
            AlertKind::TorrentRemoved { info_hash },
        );
        Ok(())
    }

    // ── M170 handlers ──────────────────────────────────────────────────

    /// M170: unified add entry. Parses magnet or bytes, resolves the
    /// download directory via category precedence, and dispatches to the
    /// existing add paths.
    /// M223 — dispatcher for the `AddTorrentM170` recv arm. The bytes
    /// branch goes through the spawn-per-add path
    /// (`try_spawn_add_torrent`); the magnet branch stays inline because
    /// it is dominated by metadata fetch latency, not by
    /// `TorrentHandle::from_torrent` cost, and is out of M223 scope.
    /// Consumes `reply` directly — either sends an error synchronously
    /// or hands `reply` to the spawned prep task (which routes it back
    /// via `CommitAddTorrent`).
    async fn dispatch_add_torrent_m170(
        &mut self,
        params: AddTorrentParams,
        reply: oneshot::Sender<crate::Result<Id20>>,
    ) {
        // Resolve download_dir + prepare category label early so that
        // an unknown category fails fast (before any parsing work).
        let (resolved_dir, resolved_category) =
            match self.resolve_download_dir_and_category(&params) {
                Ok(x) => x,
                Err(e) => {
                    let _ = reply.send(Err(e));
                    return;
                }
            };

        let AddTorrentParams {
            source,
            tags,
            paused,
            skip_checking: _, // reserved for M171+
            ..
        } = params;

        // M226: resolve None → engine `default_add_paused`. `Some(v)` is an
        // explicit per-call override and wins over the engine setting.
        let paused = paused.unwrap_or(self.settings.default_add_paused);

        match source {
            AddSource::Magnet(uri) => {
                // Magnet path: stays inline (out of M223 scope).
                let result: crate::Result<Id20> = async {
                    let magnet = irontide_core::Magnet::parse(&uri)?;
                    let info_hash = magnet.info_hash();
                    self.reject_if_in_deletion_grace(info_hash)?;
                    let id = self.handle_add_magnet(magnet, resolved_dir, tags).await?;
                    self.apply_post_add_m170(id, resolved_category, paused);
                    Ok(id)
                }
                .await;
                let _ = reply.send(result);
            }
            AddSource::Bytes(bytes) => {
                // Bytes path: spawn-per-add.
                let setup: crate::Result<AddTorrentPrepBundle> = (|| {
                    let meta = irontide_core::torrent_from_bytes_any(&bytes)?;
                    let info_hash = meta
                        .as_v1()
                        .map_or_else(|| meta.info_hashes().best_v1(), |v| v.info_hash);
                    self.reject_if_in_deletion_grace(info_hash)?;
                    if self.torrents.contains_key(&info_hash) {
                        return Err(crate::Error::DuplicateTorrent(info_hash));
                    }
                    if self.torrents.len() >= self.settings.max_torrents {
                        return Err(crate::Error::SessionAtCapacity(self.settings.max_torrents));
                    }
                    Ok(self.build_add_torrent_prep_bundle(
                        meta,
                        None,
                        resolved_dir,
                        tags,
                        Some(M170PostAdd {
                            category: resolved_category,
                            paused,
                        }),
                    ))
                })();
                match setup {
                    Ok(bundle) => self.try_spawn_add_torrent(bundle, reply),
                    Err(e) => {
                        let _ = reply.send(Err(e));
                    }
                }
            }
        }
    }

    /// Resolve the effective download directory + the category label to
    /// store on the `TorrentConfig`, following the M170 precedence rules.
    fn resolve_download_dir_and_category(
        &self,
        params: &AddTorrentParams,
    ) -> crate::Result<(Option<PathBuf>, Option<String>)> {
        match (&params.download_dir, &params.category) {
            (Some(explicit), cat) => {
                // Explicit path wins even when a category is set — qBt
                // preserves the category label either way.
                Ok((Some(explicit.clone()), cat.clone()))
            }
            (None, Some(name)) => {
                let registry = self.category_registry.read();
                match registry.get(name) {
                    Some(meta) => Ok((Some(meta.save_path.clone()), Some(name.clone()))),
                    None => Err(crate::Error::CategoryNotFound(name.clone())),
                }
            }
            (None, None) => Ok((None, None)),
        }
    }

    /// Return an error if `info_hash` is currently being removed by a
    /// deleteFiles=true call in another task.
    fn reject_if_in_deletion_grace(&self, info_hash: Id20) -> crate::Result<()> {
        if self.deletion_grace.lock().contains(&info_hash) {
            return Err(crate::Error::TorrentBeingRemoved(info_hash));
        }
        Ok(())
    }

    /// Post-add M170 hooks: stash the category label and mark the torrent
    /// paused if requested. Category is recorded for the initial stats
    /// snapshot; paused-on-add uses the existing pause path.
    fn apply_post_add_m170(&self, info_hash: Id20, category: Option<String>, paused: bool) {
        if let Some(entry) = self.torrents.get(&info_hash) {
            // Category label: stored on the torrent handle's config mirror
            // so future `stats()` calls include it. Fire-and-forget
            // because the field is non-load-bearing for the add path.
            if let Some(name) = category {
                let handle = entry.handle.clone();
                tokio::spawn(async move {
                    if let Err(e) = handle.set_category(Some(name)).await {
                        warn!(%info_hash, "failed to propagate category: {e}");
                    }
                });
            }
            if paused {
                let handle = entry.handle.clone();
                tokio::spawn(async move {
                    if let Err(e) = handle.pause().await {
                        warn!(%info_hash, "failed to pause on add: {e}");
                    }
                });
            }
        }
    }

    /// M170: create a category, persist the registry on success.
    async fn handle_create_category(
        &self,
        name: String,
        save_path: PathBuf,
    ) -> Result<(), crate::category_manager::CategoryError> {
        {
            let mut registry = self.category_registry.write();
            registry.create(name, save_path)?;
        }
        self.persist_category_registry().await
    }

    /// M170: edit a category, persist the registry on success.
    async fn handle_edit_category(
        &self,
        name: String,
        save_path: PathBuf,
    ) -> Result<(), crate::category_manager::CategoryError> {
        {
            let mut registry = self.category_registry.write();
            registry.edit(&name, save_path)?;
        }
        self.persist_category_registry().await
    }

    /// M170: remove categories, clear labels on affected torrents, and
    /// persist the registry. Returns the names that were actually
    /// removed so the CLI / qBt handler can log or echo them.
    async fn handle_remove_categories(&self, names: Vec<String>) -> Vec<String> {
        let removed: Vec<String> = {
            let mut registry = self.category_registry.write();
            registry.remove(&names)
        };
        if removed.is_empty() {
            return removed;
        }

        // Clear the `category` label on every torrent assigned to a
        // removed name. Fire-and-forget per torrent — failure only
        // costs us label-sync (not data).
        for entry in self.torrents.values() {
            let handle = entry.handle.clone();
            let to_check: Vec<String> = removed.clone();
            tokio::spawn(async move {
                if let Ok(stats) = handle.stats().await
                    && let Some(current) = stats.category
                    && to_check.iter().any(|n| n.as_str() == current.as_str())
                    && let Err(e) = handle.set_category(None).await
                {
                    warn!(
                        cat = %current,
                        "failed to clear category label after removeCategories: {e}"
                    );
                }
            });
        }

        if let Err(e) = self.persist_category_registry().await {
            warn!("failed to persist category registry after remove: {e}");
        }
        removed
    }

    /// Spawn a blocking task to persist the registry to disk.
    async fn persist_category_registry(
        &self,
    ) -> Result<(), crate::category_manager::CategoryError> {
        let registry = Arc::clone(&self.category_registry);
        // Clone the current registry state out of the lock to avoid
        // holding it across the spawn_blocking boundary.
        let snapshot = registry.read().clone();
        tokio::task::spawn_blocking(move || snapshot.save())
            .await
            .map_err(|join_err| {
                crate::category_manager::CategoryError::Persistence(std::io::Error::other(format!(
                    "category registry save join error: {join_err}"
                )))
            })?
    }

    /// M171: delete a batch of tags. Returns the subset of names that
    /// were actually present at call time (unknown names are silently
    /// ignored, matching qBt `deleteTags`).
    ///
    /// After removal, any torrent carrying a deleted tag has that tag
    /// pruned from its label set via `TorrentHandle::set_tags`.
    async fn handle_delete_tags(&self, names: Vec<String>) -> Vec<String> {
        let removed = {
            let mut reg = self.tag_registry.write();
            reg.delete(&names)
        };
        if !removed.is_empty() {
            let to_remove: std::collections::HashSet<String> = removed.iter().cloned().collect();
            for entry in self.torrents.values() {
                let handle = entry.handle.clone();
                let to_remove = to_remove.clone();
                tokio::spawn(async move {
                    if let Ok(stats) = handle.stats().await {
                        let new_tags: Vec<String> = stats
                            .tags
                            .into_iter()
                            .filter(|t| !to_remove.contains(t))
                            .collect();
                        if let Err(e) = handle.set_tags(new_tags).await {
                            tracing::warn!(error = %e, "failed to apply tag deletion to torrent");
                        }
                    }
                });
            }
            if let Err(e) = self.persist_tag_registry().await {
                tracing::warn!(error = %e, "persist tag registry after DeleteTags");
            }
        }
        removed
    }

    /// M171: add the given tags to each torrent in `info_hashes`. The
    /// engine-layer command is a wholesale replacement, so this reads
    /// the current tag set for each torrent, unions in the requested
    /// tags (sorted + deduped), and replays the result via
    /// `TorrentHandle::set_tags`. Unknown info hashes are silently
    /// skipped — qBt's `addTags` behaviour.
    ///
    /// # Errors
    ///
    /// Propagates [`crate::Error::Shutdown`] if a torrent actor has
    /// stopped while the batch was in flight.
    async fn handle_add_tags_to_torrents(
        &self,
        info_hashes: Vec<Id20>,
        tags_to_add: Vec<String>,
    ) -> crate::Result<()> {
        for hash in info_hashes {
            let Some(entry) = self.torrents.get(&hash) else {
                continue;
            };
            let current = entry.handle.stats().await?;
            let mut new_tags = current.tags;
            for t in &tags_to_add {
                if !new_tags.contains(t) {
                    new_tags.push(t.clone());
                }
            }
            new_tags.sort();
            new_tags.dedup();
            entry.handle.set_tags(new_tags).await?;
        }
        Ok(())
    }

    /// M171: remove the given tags from each torrent in `info_hashes`.
    /// Unknown info hashes are silently skipped — qBt's `removeTags`
    /// behaviour.
    ///
    /// # Errors
    ///
    /// Propagates [`crate::Error::Shutdown`] if a torrent actor has
    /// stopped while the batch was in flight.
    async fn handle_remove_tags_from_torrents(
        &self,
        info_hashes: Vec<Id20>,
        tags_to_remove: Vec<String>,
    ) -> crate::Result<()> {
        for hash in info_hashes {
            let Some(entry) = self.torrents.get(&hash) else {
                continue;
            };
            let current = entry.handle.stats().await?;
            let new_tags: Vec<String> = current
                .tags
                .into_iter()
                .filter(|t| !tags_to_remove.contains(t))
                .collect();
            entry.handle.set_tags(new_tags).await?;
        }
        Ok(())
    }

    /// M171: spawn a blocking task to persist the tag registry to disk.
    /// Mirrors `persist_category_registry`.
    async fn persist_tag_registry(&self) -> Result<(), crate::tag_manager::TagError> {
        let to_save: crate::tag_manager::TagRegistry = { self.tag_registry.read().clone() };
        tokio::task::spawn_blocking(move || to_save.save())
            .await
            .unwrap_or_else(|_| {
                Err(crate::tag_manager::TagError::Persistence(
                    std::io::Error::other("spawn_blocking failed"),
                ))
            })
    }

    /// M170: remove a torrent and delete its files from disk.
    async fn handle_remove_torrent_with_files(&mut self, info_hash: Id20) -> crate::Result<()> {
        // v0.173.1: query the TorrentActor for metadata instead of reading
        // the deleted `TorrentEntry.meta` cache. For magnet torrents with
        // resolved metadata this returns the real file list (fixing the
        // v0.173.0 silent-no-op-on-disk bug). For magnets *still resolving*
        // we treat it as an empty file list and still proceed with the
        // session-level removal — matches the pre-v0.173.1 observable
        // behaviour that the *arr e2e test relies on (`deleteFiles=true` on
        // a pre-metadata magnet leaves `download_dir` untouched but cleanly
        // removes the torrent from the registry).
        let handle = {
            let entry = self
                .torrents
                .get(&info_hash)
                .ok_or(crate::Error::TorrentNotFound(info_hash))?;
            entry.handle.clone()
        };
        let file_paths: Vec<PathBuf> = match handle.get_meta().await {
            Ok(Some(meta)) => meta
                .info
                .files()
                .iter()
                .map(|f| f.path.iter().collect::<PathBuf>())
                .collect(),
            // Meta not yet resolved (pre-metadata magnet) or actor shut down:
            // nothing to walk on disk. Session-level removal still proceeds.
            Ok(None) | Err(_) => Vec::new(),
        };
        let download_dir = self.settings.download_dir.clone();
        let _ = handle.pause().await;

        // Enter the deletion grace window BEFORE dropping the in-memory
        // entry — any add that races in during the walk will see the
        // grace set and get 409'd.
        self.deletion_grace.lock().insert(info_hash);

        // Remove from session (same as the existing path — closes
        // storage handles, deletes resume file, etc.).
        let remove_result = self.handle_remove_torrent(info_hash).await;
        if let Err(e) = &remove_result {
            warn!(
                %info_hash,
                error = %e,
                "remove_torrent_with_files: in-memory removal failed; continuing with file delete"
            );
        }

        // Now blast the files. `download_dir` is the session default (good
        // enough for M170 because add_torrent threads the same dir through
        // to storage). Once per-torrent save path is recorded (future
        // milestone), swap this out.
        let grace = Arc::clone(&self.deletion_grace);
        tokio::task::spawn_blocking(move || {
            irontide_storage::delete_torrent_files_sync(download_dir, file_paths);
            grace.lock().remove(&info_hash);
        });

        Ok(())
    }

    async fn handle_pause_torrent(&mut self, info_hash: Id20) -> crate::Result<()> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        entry.handle.pause().await
    }

    async fn handle_resume_torrent(&mut self, info_hash: Id20) -> crate::Result<()> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        entry.handle.resume().await
    }

    async fn handle_force_resume_torrent(&mut self, info_hash: Id20) -> crate::Result<()> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        entry
            .handle
            .cmd_tx
            .send(crate::types::TorrentCommand::ForceResume)
            .await
            .map_err(|_| crate::Error::Shutdown)
    }

    async fn handle_set_torrent_seed_ratio(
        &self,
        info_hash: Id20,
        limit: Option<f64>,
    ) -> crate::Result<()> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        let (tx, rx) = oneshot::channel();
        entry
            .handle
            .cmd_tx
            .send(crate::types::TorrentCommand::SetSeedRatioLimit { limit, reply: tx })
            .await
            .map_err(|_| crate::Error::Shutdown)?;
        rx.await.map_err(|_| crate::Error::Shutdown)
    }

    async fn handle_move_torrent_storage(
        &self,
        info_hash: Id20,
        new_path: std::path::PathBuf,
    ) -> crate::Result<()> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        entry.handle.move_storage(new_path).await
    }

    async fn handle_torrent_stats(&self, info_hash: Id20) -> crate::Result<TorrentStats> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        let mut stats = entry.handle.stats().await?;
        // Enrich with session-level data that the torrent actor doesn't own.
        stats.queue_position = entry.queue_position;
        stats.auto_managed = entry.auto_managed;
        Ok(stats)
    }

    async fn handle_torrent_info(&self, info_hash: Id20) -> crate::Result<TorrentInfo> {
        // v0.173.1: queries the TorrentActor (single source of truth) instead
        // of reading the deleted `TorrentEntry.meta` cache. For magnet torrents
        // this returns the real meta once assembled, where v0.173.0 always saw
        // `None` → 404 on `/api/v2/torrents/files`.
        let meta = self.get_entry_meta(info_hash).await?;
        let files: Vec<FileInfo> = if let Some(ref file_list) = meta.info.files {
            file_list
                .iter()
                .map(|f| FileInfo {
                    path: f.path.iter().collect::<PathBuf>(),
                    length: f.length,
                })
                .collect()
        } else {
            vec![FileInfo {
                path: PathBuf::from(&meta.info.name),
                length: meta.info.total_length(),
            }]
        };

        Ok(TorrentInfo {
            info_hash,
            name: meta.info.name.clone(),
            total_length: meta.info.total_length(),
            piece_length: meta.info.piece_length,
            num_pieces: meta.info.num_pieces() as u32,
            files,
            private: meta.info.private == Some(1),
        })
    }

    /// Update gauge metrics that come from session-level state.
    fn update_session_gauges(&self) {
        use crate::stats::{
            DHT_NODES, DHT_NODES_V4, DHT_NODES_V6, PEER_NUM_BANNED, SES_ACTIVE_TORRENTS,
            SES_NUM_TORRENTS,
        };
        let c = &self.counters;
        c.set(SES_NUM_TORRENTS, self.torrents.len() as i64);
        c.set(SES_ACTIVE_TORRENTS, self.torrents.len() as i64);

        // DHT presence (instance count, not routing table size)
        let dht_nodes = i64::from(self.dht_v4.is_some()) + i64::from(self.dht_v6.is_some());
        c.set(DHT_NODES, dht_nodes);
        c.set(DHT_NODES_V4, i64::from(self.dht_v4.is_some()));
        c.set(DHT_NODES_V6, i64::from(self.dht_v6.is_some()));

        // Ban count
        let ban_count = self.ban_manager.read().banned_list().len() as i64;
        c.set(PEER_NUM_BANNED, ban_count);
    }

    /// Snapshot counters and fire a `SessionStatsAlert`.
    fn fire_stats_alert(&self) {
        self.update_session_gauges();
        let values = self.counters.snapshot();
        crate::alert::post_alert(
            &self.alert_tx,
            &self.alert_mask,
            crate::alert::AlertKind::SessionStatsAlert { values },
        );
    }

    /// Fire a periodic BEP 51 `sample_infohashes` query to the DHT (M111).
    async fn fire_sample_infohashes(&self) {
        let ((Some(dht), _) | (_, Some(dht))) = (&self.dht_v4, &self.dht_v6) else {
            return;
        };
        let mut buf = [0u8; 20];
        irontide_core::random_bytes(&mut buf);
        let target = Id20::from(buf);
        match dht.sample_infohashes(target).await {
            Ok(result) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtSampleInfohashes {
                        num_samples: result.samples.len(),
                        total_estimate: result.num,
                    },
                );
            }
            Err(e) => {
                debug!("sample_infohashes failed: {e}");
            }
        }
    }

    async fn make_session_stats(&self) -> SessionStats {
        self.update_session_gauges();

        let mut total_downloaded = 0u64;
        let mut total_uploaded = 0u64;

        for entry in self.torrents.values() {
            if let Ok(stats) = entry.handle.stats().await {
                total_downloaded += stats.downloaded;
                total_uploaded += stats.uploaded;
            }
        }

        SessionStats {
            active_torrents: self.torrents.len(),
            total_downloaded,
            total_uploaded,
            dht_nodes: usize::from(self.dht_v4.is_some()) + usize::from(self.dht_v6.is_some()),
        }
    }

    /// Build a debug state snapshot across all torrents, collecting per-torrent
    /// stats and per-peer details. Torrents that time out are skipped so a
    /// single slow actor never blocks the whole response.
    async fn make_debug_state(&self) -> crate::types::DebugState {
        use crate::stats::{
            DISPATCH_ACQUIRE_NONE_TOTAL, DISPATCH_ACQUIRE_TOTAL, DISPATCH_ACQUIRE_US,
            DISPATCH_NOTIFY_WAKEUP_TOTAL,
        };

        // Session-wide dispatch counters from the atomic counters array.
        let snap = self.counters.snapshot();
        let dispatch = crate::types::DebugDispatchState {
            acquire_total: snap[DISPATCH_ACQUIRE_TOTAL],
            acquire_none_total: snap[DISPATCH_ACQUIRE_NONE_TOTAL],
            acquire_us: snap[DISPATCH_ACQUIRE_US],
            notify_wakeup_total: snap[DISPATCH_NOTIFY_WAKEUP_TOTAL],
            pieces_queued: 0,
            pieces_inflight: 0,
        };

        let mut torrents = Vec::with_capacity(self.torrents.len());
        for (&info_hash, entry) in &self.torrents {
            // Per-torrent stats — skip if the actor is slow.
            let Ok(Ok(stats)) =
                tokio::time::timeout(std::time::Duration::from_millis(500), entry.handle.stats())
                    .await
            else {
                continue;
            };

            // Per-peer details — skip on timeout.
            let peers_raw = match tokio::time::timeout(
                std::time::Duration::from_millis(500),
                entry.handle.get_peer_info(),
            )
            .await
            {
                Ok(Ok(p)) => p,
                _ => Vec::new(),
            };

            let peers: Vec<crate::types::DebugPeerState> = peers_raw
                .iter()
                .map(|p| crate::types::DebugPeerState {
                    addr: p.addr,
                    in_flight: p.in_flight_requests,
                    target_depth: p.target_pipeline_depth,
                    choking: p.peer_choking,
                    download_rate: p.download_rate,
                })
                .collect();

            let mut per_torrent_dispatch = dispatch.clone();
            per_torrent_dispatch.pieces_queued = stats.dispatch_pieces_queued;
            per_torrent_dispatch.pieces_inflight = stats.dispatch_pieces_inflight;

            torrents.push(crate::types::DebugTorrentState {
                info_hash: info_hash.to_hex(),
                state: format!("{:?}", stats.state),
                num_peers: stats.peers_connected,
                dispatch: per_torrent_dispatch,
                peers,
            });
        }

        crate::types::DebugState { torrents }
    }

    async fn handle_save_torrent_resume(
        &self,
        info_hash: Id20,
    ) -> crate::Result<irontide_core::FastResumeData> {
        let entry = self
            .torrents
            .get(&info_hash)
            .ok_or(crate::Error::TorrentNotFound(info_hash))?;
        let mut resume = entry.handle.save_resume_data().await?;
        // Patch in queue state from SessionActor's TorrentEntry (the
        // TorrentHandle doesn't know about queue position / auto-managed).
        resume.queue_position = i64::from(entry.queue_position);
        resume.auto_managed = i64::from(entry.auto_managed);
        Ok(resume)
    }

    async fn handle_save_session_state(&self) -> crate::Result<crate::persistence::SessionState> {
        use crate::persistence::SessionState;

        let mut torrents = Vec::new();
        for (info_hash, entry) in &self.torrents {
            match entry.handle.save_resume_data().await {
                Ok(rd) => torrents.push(rd),
                Err(e) => {
                    warn!(%info_hash, "failed to save resume data: {e}");
                }
            }
        }

        // Serialize smart ban state (scoped to drop RwLockReadGuard before awaits)
        let (banned_peers, peer_strikes) = {
            let ban_mgr = self.ban_manager.read();
            let banned_peers: Vec<String> = ban_mgr
                .banned_list()
                .iter()
                .map(std::string::ToString::to_string)
                .collect();
            let peer_strikes: Vec<crate::persistence::PeerStrikeEntry> = ban_mgr
                .strikes_map()
                .iter()
                .map(|(ip, &count)| crate::persistence::PeerStrikeEntry {
                    ip: ip.to_string(),
                    count: i64::from(count),
                })
                .collect();
            (banned_peers, peer_strikes)
        };

        let mut dht_entries = Vec::new();
        let mut dht_node_id = None;
        if let Some(ref dht) = self.dht_v4 {
            // Save the (possibly BEP 42-regenerated) node ID for next session
            if let Ok(stats) = dht.stats().await {
                dht_node_id = Some(stats.node_id.to_hex());
            }
            for (_id, addr) in dht.get_routing_nodes().await {
                dht_entries.push(crate::persistence::DhtNodeEntry {
                    host: addr.ip().to_string(),
                    port: i64::from(addr.port()),
                });
            }
        }
        if let Some(ref dht) = self.dht_v6 {
            for (_id, addr) in dht.get_routing_nodes().await {
                dht_entries.push(crate::persistence::DhtNodeEntry {
                    host: addr.ip().to_string(),
                    port: i64::from(addr.port()),
                });
            }
        }

        Ok(SessionState {
            dht_nodes: dht_entries,
            dht_node_id,
            torrents,
            banned_peers,
            peer_strikes,
        })
    }

    /// Compute the effective resume data directory from settings.
    fn effective_resume_dir(&self) -> PathBuf {
        self.settings
            .resume_data_dir
            .clone()
            .unwrap_or_else(crate::resume_file::default_resume_dir)
    }

    /// Load and restore torrents from per-torrent resume files on disk.
    ///
    /// Scans the resume directory, deserializes each `.resume` file, reconstructs
    /// the torrent metadata or magnet, adds it to the session, and restores the
    /// piece bitmap where available.
    async fn handle_load_resume_state(&mut self) -> crate::Result<ResumeLoadResult> {
        let resume_dir = self.effective_resume_dir();
        let paths = crate::resume_file::scan_resume_dir(&resume_dir);

        let mut restored = 0usize;
        let mut skipped = 0usize;
        let mut failed = 0usize;

        for path in &paths {
            let file_name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("<unknown>");

            // Read and deserialize
            let bytes = match std::fs::read(path) {
                Ok(b) => b,
                Err(e) => {
                    warn!(file = %file_name, "failed to read resume file: {e}");
                    failed = failed.saturating_add(1);
                    continue;
                }
            };

            let rd = match crate::resume_file::deserialize_resume(&bytes) {
                Ok(rd) => rd,
                Err(e) => {
                    warn!(file = %file_name, "failed to deserialize resume file: {e}");
                    failed = failed.saturating_add(1);
                    continue;
                }
            };

            // Try to reconstruct as a resolved torrent (info dict present).
            if let Some(meta) = crate::resume_file::reconstruct_torrent_meta(&rd) {
                let info_hash = meta.info_hash;
                let pieces = rd.pieces.clone();
                let torrent_meta = irontide_core::TorrentMeta::V1(meta);

                // Restore to the original save_path (per-torrent download dir).
                let restore_dir = if rd.save_path.is_empty() {
                    None
                } else {
                    Some(PathBuf::from(&rd.save_path))
                };
                // M171: restore tags by baking them into the TorrentConfig
                // at add-time, matching the `AddTorrentParams::with_tags`
                // semantics. Category still goes through the post-add
                // fire-and-forget path (M170 behaviour preserved).
                let restore_tags = rd.tags.clone();
                match self
                    .handle_add_torrent(torrent_meta, None, restore_dir, restore_tags)
                    .await
                {
                    Ok(added_hash) => {
                        // Restore the piece bitmap if non-empty.
                        if !pieces.is_empty()
                            && let Some(entry) = self.torrents.get(&added_hash)
                            && let Err(e) = entry.handle.restore_resume_bitmap(pieces).await
                        {
                            warn!(
                                %info_hash,
                                "failed to restore piece bitmap, torrent will recheck: {e}"
                            );
                        }
                        // M170: restore the category label if persisted.
                        if let Some(ref cat) = rd.category
                            && let Some(entry) = self.torrents.get(&added_hash)
                        {
                            let handle = entry.handle.clone();
                            let cat_owned = cat.clone();
                            tokio::spawn(async move {
                                let _ = handle.set_category(Some(cat_owned)).await;
                            });
                        }
                        // M178: restore per-URL web-seed stats so cumulative
                        // bytes and error history survive app restart.
                        if !rd.web_seed_stats.is_empty()
                            && let Some(entry) = self.torrents.get(&added_hash)
                        {
                            let handle = entry.handle.clone();
                            let stats_owned = rd.web_seed_stats.clone();
                            tokio::spawn(async move {
                                let _ = handle.restore_web_seed_stats(stats_owned).await;
                            });
                        }
                        if self.settings.queueing_enabled
                            && let Some(entry) = self.torrents.get(&added_hash)
                        {
                            let _ = entry.handle.queue().await;
                        }
                        if let Some(entry) = self.torrents.get_mut(&added_hash) {
                            entry.queue_position = rd.queue_position as i32;
                            entry.auto_managed = rd.auto_managed != 0;
                        }
                        info!(%info_hash, "restored torrent from resume file");
                        restored = restored.saturating_add(1);
                    }
                    Err(crate::Error::DuplicateTorrent(_)) => {
                        debug!(%info_hash, "skipped duplicate torrent from resume");
                        skipped = skipped.saturating_add(1);
                    }
                    Err(e) => {
                        warn!(%info_hash, "failed to add restored torrent: {e}");
                        failed = failed.saturating_add(1);
                    }
                }
            } else if let Some(magnet) = crate::resume_file::reconstruct_magnet(&rd) {
                // Unresolved magnet: re-add as magnet link.
                let info_hash = magnet.info_hash();
                let restore_dir = if rd.save_path.is_empty() {
                    None
                } else {
                    Some(PathBuf::from(&rd.save_path))
                };
                // M171: restore tags via the add-time config bake path.
                let restore_tags = rd.tags.clone();
                match self
                    .handle_add_magnet(magnet, restore_dir, restore_tags)
                    .await
                {
                    Ok(added_hash) => {
                        // M170: restore category on magnet too.
                        if let Some(ref cat) = rd.category
                            && let Some(entry) = self.torrents.get(&added_hash)
                        {
                            let handle = entry.handle.clone();
                            let cat_owned = cat.clone();
                            tokio::spawn(async move {
                                let _ = handle.set_category(Some(cat_owned)).await;
                            });
                        }
                        // M178: restore per-URL web-seed stats on magnet too,
                        // so resumes from a magnet-added torrent that already
                        // had web-seed activity recover correctly.
                        if !rd.web_seed_stats.is_empty()
                            && let Some(entry) = self.torrents.get(&added_hash)
                        {
                            let handle = entry.handle.clone();
                            let stats_owned = rd.web_seed_stats.clone();
                            tokio::spawn(async move {
                                let _ = handle.restore_web_seed_stats(stats_owned).await;
                            });
                        }
                        if self.settings.queueing_enabled
                            && let Some(entry) = self.torrents.get(&added_hash)
                        {
                            let _ = entry.handle.queue().await;
                        }
                        if let Some(entry) = self.torrents.get_mut(&added_hash) {
                            entry.queue_position = rd.queue_position as i32;
                            entry.auto_managed = rd.auto_managed != 0;
                        }
                        info!(%info_hash, "restored magnet from resume file");
                        restored = restored.saturating_add(1);
                    }
                    Err(crate::Error::DuplicateTorrent(_)) => {
                        debug!(%info_hash, "skipped duplicate magnet from resume");
                        skipped = skipped.saturating_add(1);
                    }
                    Err(e) => {
                        warn!(%info_hash, "failed to add restored magnet: {e}");
                        failed = failed.saturating_add(1);
                    }
                }
            } else {
                warn!(file = %file_name, "resume file has no valid info dict and no valid info hash");
                failed = failed.saturating_add(1);
            }
        }

        // Renormalize queue positions to contiguous 0..N-1. Handles
        // duplicate positions from crash mid-save, manual edits, or
        // older resume formats that default all positions to 0.
        {
            let mut entries: Vec<(Id20, i32)> = self
                .torrents
                .iter()
                .filter(|(_, e)| e.auto_managed)
                .map(|(h, e)| (*h, e.queue_position))
                .collect();
            entries.sort_by_key(|&(_, pos)| pos);
            for (new_pos, (hash, _)) in entries.into_iter().enumerate() {
                if let Some(entry) = self.torrents.get_mut(&hash) {
                    entry.queue_position = new_pos as i32;
                }
            }
        }

        info!(restored, skipped, failed, "resume state loaded");
        Ok(ResumeLoadResult {
            restored,
            skipped,
            failed,
        })
    }

    /// Save resume files for all torrents with a dirty `need_save_resume` flag.
    ///
    /// Returns the number of resume files successfully written.
    async fn save_dirty_resume_files(&mut self) -> usize {
        let resume_dir = self.effective_resume_dir();

        if let Err(e) = std::fs::create_dir_all(resume_dir.join("torrents")) {
            warn!("failed to create resume dir: {e}");
            return 0;
        }

        let mut saved = 0usize;
        // Collect info_hashes first to avoid borrow conflict with `self`.
        let info_hashes: Vec<Id20> = self.torrents.keys().copied().collect();

        for info_hash in &info_hashes {
            let Some(entry) = self.torrents.get(info_hash) else {
                continue;
            };

            // Check dirty flag via stats
            let needs_save = match entry.handle.stats().await {
                Ok(stats) => stats.need_save_resume,
                Err(_) => continue,
            };
            if !needs_save {
                continue;
            }

            // Build resume data and patch in session-level queue state.
            let mut rd = match entry.handle.save_resume_data().await {
                Ok(rd) => rd,
                Err(e) => {
                    warn!(%info_hash, "failed to build resume data: {e}");
                    continue;
                }
            };
            rd.queue_position = i64::from(entry.queue_position);
            rd.auto_managed = i64::from(entry.auto_managed);

            // Serialize
            let bytes = match crate::resume_file::serialize_resume(&rd) {
                Ok(b) => b,
                Err(e) => {
                    warn!(%info_hash, "failed to serialize resume data: {e}");
                    continue;
                }
            };

            // Atomic write
            let path = crate::resume_file::resume_file_path(&resume_dir, info_hash);
            if let Err(e) = crate::resume_file::atomic_write(&path, &bytes) {
                warn!(%info_hash, "failed to write resume file: {e}");
                continue;
            }

            // Reset dirty flag
            if let Err(e) = entry.handle.clear_save_resume_flag().await {
                warn!(%info_hash, "failed to clear save_resume flag: {e}");
            }

            saved = saved.saturating_add(1);
        }
        saved
    }

    /// Apply new settings at runtime, transactionally (M173 Lane B, B1).
    ///
    /// Phases (executed in order; rollback in REVERSE on first failure):
    ///
    /// 1. Rate limits + alert mask (cheap; rollback restores)
    /// 2. Listen-port rebind (B4 wires the real reconfig — B1 stub no-op)
    /// 3. DHT enable/disable (B5-B7 wire — B1 stub no-op)
    /// 4. LSD enable/disable (B9 wires — B1 stub no-op)
    ///
    /// On any phase failure, already-applied phases roll back (LIFO) and
    /// the caller sees the original [`crate::Error`] that triggered the
    /// failure. Until B4-B9 land, phases 2-4 are no-ops, so this method
    /// behaves identically to the M171 implementation for callers that
    /// only patch rate limits / alert mask. Listen-port / DHT / LSD
    /// changes are still classified as "`restart_required`" by
    /// [`classify_restart_required`] until B10 graduates them.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::InvalidSettings`] if `Settings::validate`
    /// rejects the new patch. Future variants from B4-B9 will surface
    /// listener / DHT / LSD restart failures via [`crate::apply::ApplyError`].
    fn handle_apply_settings(&mut self, new: Settings) -> crate::Result<()> {
        // Validate FIRST so that an invalid patch never even enters the
        // transactional pipeline. This matches the M171 behaviour.
        new.validate()?;

        // Snapshot pre-call values for rollback closures. These are
        // captured by-value so the rollback closures can run without
        // borrowing `self` (the executor needs `&mut self`).
        let old_upload_rate = self.settings.upload_rate_limit;
        let old_download_rate = self.settings.download_rate_limit;
        let old_alert_mask = self.settings.alert_mask;
        let old_settings = self.settings.clone();
        let old_settings_for_delta = self.settings.clone();

        let new_upload_rate = new.upload_rate_limit;
        let new_download_rate = new.download_rate_limit;
        let new_alert_mask = new.alert_mask;

        // Phase 1: rate limits + alert mask + Settings struct.
        // The rollback restores all four mutations (rate buckets +
        // mask atomic + Settings struct) — Settings is cloned for
        // restoration so the caller sees the original on failure.
        let upload_bucket = Arc::clone(&self.global_upload_bucket);
        let download_bucket = Arc::clone(&self.global_download_bucket);
        let alert_mask = Arc::clone(&self.alert_mask);

        let phase1: crate::apply::Phase<Self> = crate::apply::Phase {
            name: "rate_limits_and_mask",
            forward: Box::new(move |this: &mut Self| {
                if new_upload_rate != old_upload_rate {
                    upload_bucket.lock().set_rate(new_upload_rate);
                }
                if new_download_rate != old_download_rate {
                    download_bucket.lock().set_rate(new_download_rate);
                }
                if new_alert_mask != old_alert_mask {
                    alert_mask.store(new_alert_mask.bits(), Ordering::Relaxed);
                }
                this.settings = new;
                Ok(())
            }),
            rollback: Box::new(move |this: &mut Self| {
                // Restore in the reverse order of forward mutations.
                this.settings = old_settings;
                if new_alert_mask != old_alert_mask {
                    this.alert_mask
                        .store(old_alert_mask.bits(), Ordering::Relaxed);
                }
                if new_download_rate != old_download_rate {
                    this.global_download_bucket
                        .lock()
                        .set_rate(old_download_rate);
                }
                if new_upload_rate != old_upload_rate {
                    this.global_upload_bucket.lock().set_rate(old_upload_rate);
                }
            }),
        };

        // Phase 2 (listen_port) and Phase 4 (LSD) remain unimplemented.
        let phases = vec![phase1];

        match crate::apply::apply_phases_with_rollback(self, phases) {
            Ok(()) => {
                // M226 Step 5: broadcast the new Settings to the
                // notification dispatcher. `send` on a watch channel
                // returns Err only when every receiver has dropped,
                // which means the dispatcher has already exited — at
                // that point the toggle is academic and we silently
                // discard the error so apply_settings stays infallible
                // on the notification axis.
                let _ = self.notification_settings_tx.send(self.settings.clone());

                // Phase 3: DHT toggle (v0.187.1).
                if (old_settings_for_delta.enable_dht != self.settings.enable_dht
                    || old_settings_for_delta.anonymous_mode != self.settings.anonymous_mode)
                    && (!self.settings.enable_dht || self.settings.anonymous_mode)
                {
                    tracing::info!("DHT disabled via settings");
                    self.dht_v4 = None;
                    self.dht_v6 = None;
                    self.dht_v4_broadcast.replace(None);
                    self.dht_v6_broadcast.replace(None);
                }

                // M224 D3: keep the listener's cap atomic in sync. The
                // listener reads this on every TCP accept, so the new cap
                // applies to the next accepted connection without a restart.
                // Update is unconditional — `store` is cheap, and skipping
                // when unchanged would require an additional read first.
                self.max_connections_global.store(
                    self.settings.max_connections_global,
                    std::sync::atomic::Ordering::SeqCst,
                );

                let delta =
                    crate::types::SettingsDelta::from_diff(&old_settings_for_delta, &self.settings);
                if delta.save_resume_interval_secs.is_some() {
                    self.resume_save_notify.notify_one();
                }
                if let Some(enabled) = delta.ip_filter_enabled {
                    self.ip_filter.write().enabled = enabled;
                }
                // M226 Step 6: poke the watched-folder dispatcher to
                // rebuild its debouncer against the new path. We only
                // fire when the path itself OR the delete-after-add
                // flag changed — rate-limit / DHT tweaks must NOT
                // churn inotify FDs.
                if delta.watched_folder.is_some() || delta.delete_torrent_after_add.is_some() {
                    self.watched_folder_changed.notify_one();
                }
                if !delta.is_empty() {
                    // v0.187.3 / 1A: SettingsDelta fan-out. We use try_send so a
                    // saturated per-torrent channel doesn't block the apply call;
                    // the trade-off is that the dropped torrent will retain its
                    // old config until the next apply. Pre-v0.187.3 this was a
                    // silent `let _`; now we log at WARN so partial-failure
                    // events are observable without becoming fatal.
                    let mut failed: Vec<irontide_core::Id20> = Vec::new();
                    for (hash, entry) in &self.torrents {
                        if entry
                            .handle
                            .cmd_tx
                            .try_send(crate::types::TorrentCommand::UpdateSettings(delta.clone()))
                            .is_err()
                        {
                            failed.push(*hash);
                        }
                    }
                    if !failed.is_empty() {
                        tracing::warn!(
                            count = failed.len(),
                            "SettingsDelta fan-out: per-torrent channel saturated; \
                             affected torrents will pick up the change on the next apply"
                        );
                    }
                }
                post_alert(&self.alert_tx, &self.alert_mask, AlertKind::SettingsChanged);
                Ok(())
            }
            Err(crate::apply::ApplyError::ValidationFailed(msg)) => {
                Err(crate::Error::InvalidSettings(msg))
            }
            Err(e) => Err(crate::Error::Config(format!("apply settings: {e}"))),
        }
    }

    /// Build a `QueueEntry` snapshot from current auto-managed torrents.
    fn queue_entries(&self) -> Vec<crate::queue::QueueEntry> {
        self.torrents
            .iter()
            .filter(|(_, e)| e.auto_managed)
            .map(|(&hash, e)| crate::queue::QueueEntry {
                info_hash: hash,
                position: e.queue_position,
            })
            .collect()
    }

    fn handle_set_queue_position(&mut self, info_hash: Id20, pos: i32) -> crate::Result<()> {
        if !self.torrents.contains_key(&info_hash) {
            return Err(crate::Error::TorrentNotFound(info_hash));
        }
        let mut entries = self.queue_entries();
        let changed = crate::queue::set_position(&mut entries, info_hash, pos);
        self.apply_queue_changes(&changed);
        Ok(())
    }

    fn handle_queue_move(&mut self, info_hash: Id20, op: QueueMoveFn) -> crate::Result<()> {
        if !self.torrents.contains_key(&info_hash) {
            return Err(crate::Error::TorrentNotFound(info_hash));
        }
        let mut entries = self.queue_entries();
        let changed = op(&mut entries, info_hash);
        self.apply_queue_changes(&changed);
        Ok(())
    }

    /// Apply position changes back to `TorrentEntry` fields and fire alerts.
    fn apply_queue_changes(&mut self, changed: &[(Id20, i32, i32)]) {
        for &(hash, old_pos, new_pos) in changed {
            if let Some(entry) = self.torrents.get_mut(&hash) {
                entry.queue_position = new_pos;
            }
            crate::alert::post_alert(
                &self.alert_tx,
                &self.alert_mask,
                crate::alert::AlertKind::TorrentQueuePositionChanged {
                    info_hash: hash,
                    old_pos,
                    new_pos,
                },
            );
        }
    }

    async fn evaluate_queue(&mut self) {
        if !self.settings.queueing_enabled {
            return;
        }
        let now = tokio::time::Instant::now();
        let startup_duration = std::time::Duration::from_secs(self.settings.auto_manage_startup);
        let mut candidates = Vec::new();

        // Collect info hashes first to avoid borrow issues with async calls
        let hashes: Vec<Id20> = self.torrents.keys().copied().collect();

        for &info_hash in &hashes {
            let (queue_position, started_at) = {
                let Some(entry) = self.torrents.get(&info_hash) else {
                    continue;
                };
                if !entry.auto_managed {
                    continue;
                }
                (entry.queue_position, entry.started_at)
            };

            // Get current stats (async call — self.torrents is not borrowed here)
            let stats = match self.torrents.get(&info_hash) {
                Some(entry) => match entry.handle.stats().await {
                    Ok(s) => s,
                    Err(_) => continue,
                },
                None => continue,
            };

            let category = match stats.state {
                TorrentState::Checking | TorrentState::FetchingMetadata => {
                    crate::queue::QueueCategory::Checking
                }
                TorrentState::Downloading => crate::queue::QueueCategory::Downloading,
                TorrentState::Seeding | TorrentState::Complete => {
                    crate::queue::QueueCategory::Seeding
                }
                TorrentState::Queued => {
                    if stats.progress >= 1.0 {
                        crate::queue::QueueCategory::Seeding
                    } else {
                        crate::queue::QueueCategory::Downloading
                    }
                }
                TorrentState::Paused | TorrentState::Stopped | TorrentState::Sharing => continue,
            };

            let is_active = !matches!(stats.state, TorrentState::Paused | TorrentState::Queued);

            // EWMA-smooth the rates for stable inactive classification.
            let alpha = self.settings.queue_rate_ewma_alpha.clamp(0.0, 1.0);
            let (smoothed_dl, smoothed_ul) = if let Some(entry) = self.torrents.get_mut(&info_hash)
            {
                let raw_dl = stats.download_rate as f64;
                let raw_ul = stats.upload_rate as f64;
                entry.smoothed_download_rate =
                    alpha.mul_add(raw_dl, (1.0 - alpha) * entry.smoothed_download_rate);
                entry.smoothed_upload_rate =
                    alpha.mul_add(raw_ul, (1.0 - alpha) * entry.smoothed_upload_rate);
                (entry.smoothed_download_rate, entry.smoothed_upload_rate)
            } else {
                continue;
            };

            let past_startup = started_at.is_none_or(|t| now.duration_since(t) > startup_duration);

            let is_inactive = past_startup
                && match category {
                    crate::queue::QueueCategory::Downloading => {
                        (smoothed_dl as u64) < self.settings.inactive_down_rate
                    }
                    crate::queue::QueueCategory::Seeding => {
                        (smoothed_ul as u64) < self.settings.inactive_up_rate
                    }
                    crate::queue::QueueCategory::Checking => false,
                };

            let anti_flap_duration = if category == crate::queue::QueueCategory::Seeding {
                std::time::Duration::from_secs(self.settings.seed_queue_min_active_secs)
            } else {
                startup_duration
            };
            let recently_started =
                started_at.is_some_and(|t| now.duration_since(t) < anti_flap_duration);

            let seed_rank = if category == crate::queue::QueueCategory::Seeding {
                Some(crate::queue::compute_seed_rank(
                    stats.num_complete,
                    stats.num_incomplete,
                ))
            } else {
                None
            };

            candidates.push(crate::queue::QueueCandidate {
                info_hash,
                position: queue_position,
                category,
                is_active,
                is_inactive,
                recently_started,
                seed_rank,
            });
        }

        let config = crate::queue::QueueConfig {
            active_downloads: self.settings.active_downloads,
            active_seeds: self.settings.active_seeds,
            active_checking: self.settings.active_checking,
            active_limit: self.settings.active_limit,
            dont_count_slow: self.settings.dont_count_slow_torrents,
            prefer_seeds: self.settings.auto_manage_prefer_seeds,
        };
        let mut decision = crate::queue::evaluate(&candidates, &config);
        crate::queue::apply_preemption(&mut decision, &candidates);

        // Apply decisions
        for hash in &decision.to_pause {
            if let Some(entry) = self.torrents.get(hash) {
                let _ = entry.handle.queue().await;
            }
            post_alert(
                &self.alert_tx,
                &self.alert_mask,
                AlertKind::TorrentAutoManaged {
                    info_hash: *hash,
                    paused: true,
                },
            );
        }

        for hash in &decision.to_resume {
            if let Some(entry) = self.torrents.get_mut(hash) {
                let _ = entry.handle.resume().await;
                entry.started_at = Some(tokio::time::Instant::now());
            }
            post_alert(
                &self.alert_tx,
                &self.alert_mask,
                AlertKind::TorrentAutoManaged {
                    info_hash: *hash,
                    paused: false,
                },
            );
        }
    }

    /// Handle a pre-validated inbound connection from the `ListenerTask` (M114).
    fn handle_identified_inbound(&self, conn: crate::listener::IdentifiedConnection) {
        if let Some(entry) = self.torrents.get(&conn.info_hash) {
            debug!(%conn.addr, %conn.info_hash, "routing validated inbound peer");
            let handle = entry.handle.clone();
            tokio::spawn(async move {
                let _ = handle.send_incoming_peer(conn.stream, conn.addr).await;
            });
        } else {
            // Race: torrent removed between validation and receipt.
            debug!(%conn.addr, %conn.info_hash, "validated peer for removed torrent, dropping");
        }
    }

    /// Handle an incoming SSL/TLS connection (M42).
    ///
    /// Uses `LazyConfigAcceptor` to peek at the TLS `ClientHello` and extract
    /// the SNI (hex-encoded info hash) to route the connection to the right
    /// torrent. The full TLS handshake uses the torrent's CA cert to build
    /// the server config.
    async fn handle_ssl_incoming(
        &mut self,
        stream: crate::transport::BoxedStream,
        addr: std::net::SocketAddr,
    ) {
        use tokio_rustls::LazyConfigAcceptor;

        let acceptor = LazyConfigAcceptor::new(rustls::server::Acceptor::default(), stream);

        let start_handshake = match acceptor.await {
            Ok(sh) => sh,
            Err(e) => {
                debug!(%addr, error = %e, "SSL ClientHello read failed");
                return;
            }
        };

        // Extract SNI from ClientHello
        let client_hello = start_handshake.client_hello();
        let sni = if let Some(name) = client_hello.server_name() {
            name.to_string()
        } else {
            debug!(%addr, "SSL connection missing SNI");
            return;
        };

        // SNI is hex-encoded info hash (40 chars for SHA-1)
        let Ok(info_hash) = Id20::from_hex(&sni) else {
            debug!(%addr, sni = %sni, "SSL SNI is not a valid info hash");
            return;
        };

        // Look up the torrent
        let Some(torrent) = self.torrents.get(&info_hash) else {
            debug!(%addr, %info_hash, "SSL connection for unknown torrent");
            return;
        };

        // Get the SSL CA cert from the torrent's metadata.
        //
        // v0.173.1: `TorrentEntry.meta` was deleted. Query the TorrentActor
        // directly (single source of truth). Magnet torrents previously hit
        // the "non-SSL torrent" branch here because their entry.meta was
        // always None — BEP 4A handshakes silently dropped.
        let meta = match torrent.handle.get_meta().await {
            Ok(Some(m)) => m,
            Ok(None) => {
                debug!(%addr, %info_hash, "SSL connection for torrent still resolving metadata");
                return;
            }
            Err(_) => {
                debug!(%addr, %info_hash, "SSL connection but TorrentActor shut down");
                return;
            }
        };
        let ssl_cert = if let Some(cert) = meta.ssl_cert.as_ref() {
            cert.clone()
        } else {
            debug!(%addr, %info_hash, "SSL connection for non-SSL torrent (no ssl_cert in info dict)");
            return;
        };

        // Build server config using the torrent's CA cert
        let server_config = if let Some(mgr) = self.ssl_manager.as_ref() {
            match mgr.server_config(&ssl_cert) {
                Ok(cfg) => cfg,
                Err(e) => {
                    warn!(%addr, %info_hash, error = %e, "failed to build SSL server config");
                    return;
                }
            }
        } else {
            debug!(%addr, "SSL manager not initialized");
            return;
        };

        // Complete the TLS handshake
        let tls_stream = match start_handshake.into_stream(server_config).await {
            Ok(s) => s,
            Err(e) => {
                warn!(%addr, %info_hash, error = %e, "SSL handshake failed");
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::SslTorrentError {
                        info_hash,
                        message: format!("inbound TLS handshake from {addr}: {e}"),
                    },
                );
                return;
            }
        };

        // Route to the torrent actor via SpawnSslPeer command
        let _ = torrent.handle.spawn_ssl_peer(addr, tls_stream).await;
    }

    async fn handle_dht_put_immutable(&self, value: Vec<u8>) -> crate::Result<Id20> {
        let dht = self.dht_v4.as_ref().ok_or(crate::Error::DhtDisabled)?;
        match dht.put_immutable(value.clone()).await {
            Ok(target) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtPutComplete { target },
                );
                Ok(target)
            }
            Err(e) => {
                let target = irontide_core::sha1(&value);
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtItemError {
                        target,
                        message: e.to_string(),
                    },
                );
                Err(crate::Error::Dht(e))
            }
        }
    }

    async fn handle_dht_get_immutable(&self, target: Id20) -> crate::Result<Option<Vec<u8>>> {
        let dht = self.dht_v4.as_ref().ok_or(crate::Error::DhtDisabled)?;
        match dht.get_immutable(target).await {
            Ok(value) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtGetResult {
                        target,
                        value: value.clone(),
                    },
                );
                Ok(value)
            }
            Err(e) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtItemError {
                        target,
                        message: e.to_string(),
                    },
                );
                Err(crate::Error::Dht(e))
            }
        }
    }

    async fn handle_dht_put_mutable(
        &self,
        keypair_bytes: [u8; 32],
        value: Vec<u8>,
        seq: i64,
        salt: Vec<u8>,
    ) -> crate::Result<Id20> {
        let dht = self.dht_v4.as_ref().ok_or(crate::Error::DhtDisabled)?;
        match dht.put_mutable(keypair_bytes, value, seq, salt).await {
            Ok(target) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtMutablePutComplete { target, seq },
                );
                Ok(target)
            }
            Err(e) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtItemError {
                        target: Id20::from([0u8; 20]),
                        message: e.to_string(),
                    },
                );
                Err(crate::Error::Dht(e))
            }
        }
    }

    async fn handle_dht_get_mutable(
        &self,
        public_key: [u8; 32],
        salt: Vec<u8>,
    ) -> crate::Result<Option<(Vec<u8>, i64)>> {
        let dht = self.dht_v4.as_ref().ok_or(crate::Error::DhtDisabled)?;
        let target = irontide_dht::compute_mutable_target(&public_key, &salt);
        match dht.get_mutable(public_key, salt).await {
            Ok(result) => {
                let (value, seq) = match &result {
                    Some((v, s)) => (Some(v.clone()), Some(*s)),
                    None => (None, None),
                };
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtMutableGetResult {
                        target,
                        value,
                        seq,
                        public_key,
                    },
                );
                Ok(result)
            }
            Err(e) => {
                post_alert(
                    &self.alert_tx,
                    &self.alert_mask,
                    AlertKind::DhtItemError {
                        target,
                        message: e.to_string(),
                    },
                );
                Err(crate::Error::Dht(e))
            }
        }
    }

    async fn shutdown_all(&mut self) {
        // Save resume files before draining torrents (M161 Phase 5).
        let save_count = self.save_dirty_resume_files().await;
        if save_count > 0 {
            info!(save_count, "saved resume files on shutdown");
        }

        for (info_hash, entry) in self.torrents.drain() {
            debug!(%info_hash, "shutting down torrent");
            let _ = entry.handle.shutdown().await;
        }
        if let Some(ref dht) = self.dht_v4 {
            let _ = dht.shutdown().await;
        }
        if let Some(ref dht) = self.dht_v6 {
            let _ = dht.shutdown().await;
        }
        if let Some(ref nat) = self.nat {
            nat.shutdown().await;
        }
        if let Some(ref lsd) = self.lsd {
            lsd.shutdown().await;
        }
        if let Some(ref socket) = self.utp_socket
            && let Err(e) = socket.shutdown().await
        {
            debug!(error = %e, "uTP socket shutdown error");
        }
        if let Some(ref socket) = self.utp_socket_v6
            && let Err(e) = socket.shutdown().await
        {
            debug!(error = %e, "uTP v6 socket shutdown error");
        }
        self.disk_manager.shutdown().await;
    }
}

/// Helper to receive NAT events from an optional receiver.
/// Returns `pending` if no receiver is available, so the `select!` branch is skipped.
async fn recv_nat_event(
    rx: &mut Option<mpsc::Receiver<irontide_nat::NatEvent>>,
) -> irontide_nat::NatEvent {
    match rx {
        Some(r) => match r.recv().await {
            Some(event) => event,
            None => std::future::pending().await,
        },
        None => std::future::pending().await,
    }
}

/// Receive from an optional DHT IP consensus channel, pending forever if absent.
async fn recv_dht_ip(
    rx: &mut Option<mpsc::Receiver<std::net::IpAddr>>,
) -> Option<std::net::IpAddr> {
    match rx {
        Some(r) => r.recv().await,
        None => std::future::pending().await,
    }
}

/// Synthesize a minimal `TorrentMetaV1` from a `TorrentMetaV2` for session compatibility.
///
/// The session engine uses v1 structures internally (info hash as Id20, `InfoDict` for
/// piece hashing, etc.). For v2-only torrents, we create a "virtual" v1 representation
/// with the truncated SHA-256 hash as the `info_hash`.
/// M223 — off-actor add-torrent prep phase. Runs in a `tokio::spawn`'d
/// task launched by `SessionActor::try_spawn_add_torrent` so concurrent
/// adds do not serialise the actor's command queue. Performs the heavy
/// work that previously caused super-linear handler-cost growth in the
/// parallel-7 POST tail:
/// - synthesise / clone v1 metadata
/// - create the storage backend (filesystem or memory)
/// - `disk_manager.register_torrent` (async ack from disk actor)
/// - `TorrentHandle::from_torrent` (spawns the `TorrentActor`)
///
/// Returns `PreparedAddTorrent` on success — the `SessionActor` commit
/// arm then inserts it into `self.torrents` + queue position + alert +
/// LSD. Failures propagate untouched so the commit arm can reply with
/// the original error.
async fn prepare_add_torrent_off_actor(
    bundle: AddTorrentPrepBundle,
) -> crate::Result<PreparedAddTorrent> {
    let AddTorrentPrepBundle {
        torrent_meta,
        storage_override,
        torrent_config,
        disk_manager,
        dht_v4_broadcast,
        dht_v6_broadcast,
        global_up,
        global_down,
        slot_tuner,
        alert_tx,
        alert_mask,
        utp_socket,
        utp_socket_v6,
        ban_manager,
        ip_filter,
        plugins,
        sam_session,
        ssl_manager,
        factory,
        hash_pool,
        counters,
        m170_post,
    } = bundle;

    let version = torrent_meta.version();
    let meta_v2 = torrent_meta.as_v2().cloned();

    // For v2-only torrents, synthesize a minimal v1 metadata wrapper.
    // The session uses info_hash (Id20) as the primary key, so we use
    // the SHA-256 truncated to 20 bytes (per BEP 52 tracker/DHT compat).
    let meta = if let Some(v1) = torrent_meta.as_v1() {
        v1.clone()
    } else {
        let v2 = torrent_meta.as_v2().unwrap();
        synthesize_v1_from_v2(v2)
    };
    let info_hash = meta.info_hash;
    let is_private = meta.info.private == Some(1);

    // Create or use provided storage, then register with disk manager
    let storage: Arc<dyn TorrentStorage> = if let Some(s) = storage_override {
        s
    } else {
        let lengths = Lengths::new(
            meta.info.total_length(),
            meta.info.piece_length,
            DEFAULT_CHUNK_SIZE,
        );
        let files = meta.info.files();
        let file_paths: Vec<PathBuf> = files
            .iter()
            .map(|f| f.path.iter().collect::<PathBuf>())
            .collect();
        let file_lengths: Vec<u64> = files.iter().map(|f| f.length).collect();
        let prealloc_mode = torrent_config.preallocate_mode.unwrap_or_else(|| {
            irontide_storage::PreallocateMode::from(
                torrent_config.storage_mode == irontide_core::StorageMode::Full,
            )
        });
        match irontide_storage::FilesystemStorage::new(
            &torrent_config.download_dir,
            file_paths,
            file_lengths,
            lengths.clone(),
            None,
            prealloc_mode,
            torrent_config.filesystem_direct_io,
        ) {
            Ok(s) => Arc::new(s),
            Err(e) => {
                warn!("failed to create filesystem storage: {e}, falling back to memory");
                Arc::new(irontide_storage::MemoryStorage::new(lengths))
            }
        }
    };
    let disk_handle = disk_manager.register_torrent(info_hash, storage).await;

    let handle = TorrentHandle::from_torrent(
        meta.clone(),
        version,
        meta_v2,
        disk_handle,
        disk_manager,
        torrent_config,
        dht_v4_broadcast.subscribe(),
        dht_v6_broadcast.subscribe(),
        global_up,
        global_down,
        slot_tuner,
        alert_tx.clone(),
        Arc::clone(&alert_mask),
        utp_socket,
        utp_socket_v6,
        ban_manager,
        ip_filter,
        plugins,
        sam_session,
        ssl_manager,
        factory,
        Some(hash_pool),
        counters,
    )
    .await?;

    // M223 — post `TorrentAdded` here (sync, in the prep task) rather
    // than in `commit_add_torrent` (on the session actor) so the alert
    // ordering invariant survives spawn-per-add. `TorrentHandle::from_torrent`
    // spawns the `TorrentActor` internally but doesn't yield between
    // the spawn and its return, so this post races only with the
    // following `commit_tx.send.await` yield. The `TorrentActor`'s
    // first alert (`StateChanged → Checking` from `verify_existing_pieces`)
    // therefore fires AFTER this `TorrentAdded`.
    //
    // **Limitation**: parallel adds with the same info-hash both reach
    // here and both post `TorrentAdded`, even though the commit re-check
    // will fail one of them with `DuplicateTorrent`. The losing
    // `TorrentActor` shuts down cleanly when its `TorrentHandle` is
    // dropped in `commit_add_torrent`, but its `TorrentAdded` is a
    // false positive. Production callers do not parallelise same-hash
    // adds; accepted edge case.
    post_alert(
        &alert_tx,
        &alert_mask,
        AlertKind::TorrentAdded {
            info_hash,
            name: meta.info.name.clone(),
        },
    );
    Ok(PreparedAddTorrent {
        handle,
        info_hash,
        is_private,
        m170_post,
    })
}

fn synthesize_v1_from_v2(v2: &irontide_core::TorrentMetaV2) -> irontide_core::TorrentMetaV1 {
    use irontide_core::{FileEntry, InfoDict};

    let info_hash = v2.info_hashes.best_v1();

    // Build file entries from v2 file tree
    let v2_files = v2.info.files();
    let file_entries: Vec<FileEntry> = v2_files
        .iter()
        .map(|f| FileEntry {
            length: f.attr.length,
            path: f.path.clone(),
            attr: None,
            mtime: None,
            symlink_path: None,
        })
        .collect();

    // v2-only torrents have no v1 piece hashes — use placeholder pieces field.
    // Verification is done via v2 Merkle trees, not v1 SHA-1 hashes.
    let num_pieces = v2.info.num_pieces() as usize;
    let pieces = vec![0u8; num_pieces * 20];

    let info = InfoDict {
        name: v2.info.name.clone(),
        piece_length: v2.info.piece_length,
        pieces,
        length: if file_entries.len() == 1 {
            Some(file_entries[0].length)
        } else {
            None
        },
        files: if file_entries.len() > 1 {
            Some(file_entries)
        } else {
            None
        },
        private: None,
        source: None,
        ssl_cert: v2.ssl_cert.clone(),
        similar: Vec::new(),
        collections: Vec::new(),
    };

    irontide_core::TorrentMetaV1 {
        info_hash,
        announce: v2.announce.clone(),
        announce_list: v2.announce_list.clone(),
        comment: v2.comment.clone(),
        created_by: v2.created_by.clone(),
        creation_date: v2.creation_date,
        info,
        info_bytes: None,
        url_list: Vec::new(),
        httpseeds: Vec::new(),
        ssl_cert: v2.ssl_cert.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::TorrentState;
    use irontide_core::{DEFAULT_CHUNK_SIZE, Lengths, TorrentMetaV1, torrent_from_bytes};
    use irontide_storage::MemoryStorage;
    use std::time::Duration;

    fn make_test_torrent(data: &[u8], piece_length: u64) -> TorrentMetaV1 {
        use serde::Serialize;

        #[derive(Serialize)]
        struct Info<'a> {
            length: u64,
            name: &'a str,
            #[serde(rename = "piece length")]
            piece_length: u64,
            #[serde(with = "serde_bytes")]
            pieces: &'a [u8],
        }

        #[derive(Serialize)]
        struct Torrent<'a> {
            info: Info<'a>,
        }

        let mut pieces = Vec::new();
        let mut offset = 0;
        while offset < data.len() {
            let end = (offset + piece_length as usize).min(data.len());
            let hash = irontide_core::sha1(&data[offset..end]);
            pieces.extend_from_slice(hash.as_bytes());
            offset = end;
        }

        let t = Torrent {
            info: Info {
                length: data.len() as u64,
                name: "test",
                piece_length,
                pieces: &pieces,
            },
        };

        let bytes = irontide_bencode::to_bytes(&t).unwrap();
        torrent_from_bytes(&bytes).unwrap()
    }

    fn make_storage(data: &[u8], piece_length: u64) -> Arc<MemoryStorage> {
        let lengths = Lengths::new(data.len() as u64, piece_length, DEFAULT_CHUNK_SIZE);
        Arc::new(MemoryStorage::new(lengths))
    }

    static TEST_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

    fn test_settings() -> Settings {
        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let pid = std::process::id();
        let dl_dir = std::env::temp_dir().join(format!("irontide-session-lib-dl-{pid}-{n}"));
        let resume_dir =
            std::env::temp_dir().join(format!("irontide-session-lib-resume-{pid}-{n}"));
        let _ = std::fs::remove_dir_all(&dl_dir);
        let _ = std::fs::remove_dir_all(&resume_dir);
        let _ = std::fs::create_dir_all(&dl_dir);

        Settings {
            listen_port: 0,
            download_dir: dl_dir,
            resume_data_dir: Some(resume_dir),
            max_torrents: 10,
            enable_dht: false,
            enable_pex: false,
            enable_lsd: false,
            enable_fast_extension: false,
            enable_utp: false,
            enable_upnp: false,
            enable_natpmp: false,
            enable_ipv6: false,
            alert_channel_size: 64,
            disk_io_threads: 2,
            storage_mode: irontide_core::StorageMode::Sparse,
            disk_cache_size: 1024 * 1024,
            ..Settings::default()
        }
    }

    // ---- Test 1: Start and shutdown ----

    #[tokio::test]
    async fn session_start_and_shutdown() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let stats = session.session_stats().await.unwrap();
        assert_eq!(stats.active_torrents, 0);
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn peer_unchoke_durations_returns_none_for_missing_torrent() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let bogus = Id20([0u8; 20]);
        let result = session.peer_unchoke_durations(bogus).await.unwrap();
        assert!(
            result.is_none(),
            "missing torrent must yield None, not an empty map"
        );
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn peer_unchoke_durations_returns_empty_map_for_known_torrent_with_no_peers() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        let result = session
            .peer_unchoke_durations(info_hash)
            .await
            .unwrap()
            .expect("known torrent must yield Some, even with no peers");
        assert!(
            result.is_empty(),
            "fresh torrent with no peers has no unchoke history"
        );
        session.shutdown().await.unwrap();
    }

    // ---- Test 2: Add and list torrent ----

    #[tokio::test]
    async fn add_and_list_torrent() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let expected_hash = meta.info_hash;

        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        assert_eq!(info_hash, expected_hash);

        let list = session.list_torrents().await.unwrap();
        assert_eq!(list.len(), 1);
        assert!(list.contains(&info_hash));

        session.shutdown().await.unwrap();
    }

    // ---- Test 3: Remove torrent ----

    #[tokio::test]
    async fn remove_torrent() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        session.remove_torrent(info_hash).await.unwrap();

        tokio::time::sleep(Duration::from_millis(50)).await;

        let list = session.list_torrents().await.unwrap();
        assert!(list.is_empty());

        session.shutdown().await.unwrap();
    }

    // ---- Test 4: Duplicate rejection ----

    #[tokio::test]
    async fn duplicate_torrent_rejected() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage1 = make_storage(&data, 16384);
        let storage2 = make_storage(&data, 16384);

        session
            .add_torrent_with_meta(meta.clone().into(), Some(storage1))
            .await
            .unwrap();
        let result = session
            .add_torrent_with_meta(meta.into(), Some(storage2))
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("duplicate"));

        session.shutdown().await.unwrap();
    }

    // ---- Test 5: Max capacity ----

    #[tokio::test]
    async fn session_at_capacity() {
        let mut config = test_settings();
        config.max_torrents = 1;
        let session = SessionHandle::start(config).await.unwrap();

        let data1 = vec![0xAA; 16384];
        let meta1 = make_test_torrent(&data1, 16384);
        let storage1 = make_storage(&data1, 16384);
        session
            .add_torrent_with_meta(meta1.into(), Some(storage1))
            .await
            .unwrap();

        let data2 = vec![0xBB; 16384];
        let meta2 = make_test_torrent(&data2, 16384);
        let storage2 = make_storage(&data2, 16384);
        let result = session
            .add_torrent_with_meta(meta2.into(), Some(storage2))
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("capacity"));

        session.shutdown().await.unwrap();
    }

    // ---- Test 6: Torrent stats ----

    #[tokio::test]
    async fn torrent_stats_via_session() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 32768];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        let stats = session.torrent_stats(info_hash).await.unwrap();
        assert_eq!(stats.state, TorrentState::Downloading);
        assert_eq!(stats.pieces_total, 2);

        session.shutdown().await.unwrap();
    }

    // ---- Test 7: Torrent info ----

    #[tokio::test]
    async fn torrent_info_via_session() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 32768];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        let info = session.torrent_info(info_hash).await.unwrap();
        assert_eq!(info.info_hash, info_hash);
        assert_eq!(info.name, "test");
        assert_eq!(info.total_length, 32768);
        assert_eq!(info.num_pieces, 2);
        assert!(!info.private);
        assert_eq!(info.files.len(), 1);
        assert_eq!(info.files[0].length, 32768);

        session.shutdown().await.unwrap();
    }

    // ---- Test 8: Pause/resume via session ----

    #[tokio::test]
    async fn pause_resume_via_session() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        session.pause_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        let stats = session.torrent_stats(info_hash).await.unwrap();
        assert_eq!(stats.state, TorrentState::Paused);

        session.resume_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        let stats = session.torrent_stats(info_hash).await.unwrap();
        assert_eq!(stats.state, TorrentState::Downloading);

        session.shutdown().await.unwrap();
    }

    // ---- Test 9: Not-found errors ----

    #[tokio::test]
    async fn not_found_errors() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let fake_hash = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();

        assert!(session.torrent_stats(fake_hash).await.is_err());
        assert!(session.torrent_info(fake_hash).await.is_err());
        assert!(session.pause_torrent(fake_hash).await.is_err());
        assert!(session.resume_torrent(fake_hash).await.is_err());
        assert!(session.remove_torrent(fake_hash).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test 10: Session stats ----

    #[tokio::test]
    async fn session_stats_aggregate() {
        let session = SessionHandle::start(test_settings()).await.unwrap();

        let data1 = vec![0xAA; 16384];
        let meta1 = make_test_torrent(&data1, 16384);
        let storage1 = make_storage(&data1, 16384);
        session
            .add_torrent_with_meta(meta1.into(), Some(storage1))
            .await
            .unwrap();

        let data2 = vec![0xBB; 16384];
        let meta2 = make_test_torrent(&data2, 16384);
        let storage2 = make_storage(&data2, 16384);
        session
            .add_torrent_with_meta(meta2.into(), Some(storage2))
            .await
            .unwrap();

        let stats = session.session_stats().await.unwrap();
        assert_eq!(stats.active_torrents, 2);

        session.shutdown().await.unwrap();
    }

    // ---- Test 11: Add magnet and list ----

    #[tokio::test]
    async fn add_magnet_and_list() {
        use irontide_core::Magnet;

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let magnet = Magnet {
            info_hashes: irontide_core::InfoHashes::v1_only(
                Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap(),
            ),
            display_name: Some("test-magnet".into()),
            trackers: vec![],
            peers: vec![],
            selected_files: None,
        };
        let expected_hash = magnet.info_hash();

        let info_hash = session.add_magnet(magnet).await.unwrap();
        assert_eq!(info_hash, expected_hash);

        let list = session.list_torrents().await.unwrap();
        assert_eq!(list.len(), 1);
        assert!(list.contains(&info_hash));

        // torrent_info should fail with MetadataNotReady
        let err = session.torrent_info(info_hash).await.unwrap_err();
        assert!(err.to_string().contains("metadata not yet available"));

        session.shutdown().await.unwrap();
    }

    // ---- Test 12: Duplicate magnet rejected ----

    #[tokio::test]
    async fn add_magnet_duplicate_rejected() {
        use irontide_core::Magnet;

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let magnet = Magnet {
            info_hashes: irontide_core::InfoHashes::v1_only(
                Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap(),
            ),
            display_name: Some("test-magnet".into()),
            trackers: vec![],
            peers: vec![],
            selected_files: None,
        };

        session.add_magnet(magnet.clone()).await.unwrap();
        let result = session.add_magnet(magnet).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("duplicate"));

        session.shutdown().await.unwrap();
    }

    // ---- Test 13: Session with LSD enabled ----

    #[tokio::test]
    async fn session_with_lsd_enabled() {
        use irontide_core::Magnet;

        // LSD may fail to bind port 6771 — session should still start
        let mut config = test_settings();
        config.enable_lsd = true;

        let session = SessionHandle::start(config).await.unwrap();

        // Add a torrent (triggers LSD announce if available)
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Add a magnet (also triggers LSD announce)
        let magnet = Magnet {
            info_hashes: irontide_core::InfoHashes::v1_only(
                Id20::from_hex("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").unwrap(),
            ),
            display_name: Some("lsd-test".into()),
            trackers: vec![],
            peers: vec![],
            selected_files: None,
        };
        session.add_magnet(magnet).await.unwrap();

        let list = session.list_torrents().await.unwrap();
        assert_eq!(list.len(), 2);

        session.shutdown().await.unwrap();
    }

    // ---- Test: v2-only torrent addition ----

    #[tokio::test]
    async fn add_v2_only_torrent() {
        use irontide_bencode::BencodeValue;
        use std::collections::BTreeMap;

        let session = SessionHandle::start(test_settings()).await.unwrap();

        // Build a minimal v2-only torrent
        let mut attr_map: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
        attr_map.insert(b"length".to_vec(), BencodeValue::Integer(16384));
        let mut file_node: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
        file_node.insert(b"".to_vec(), BencodeValue::Dict(attr_map));
        let mut ft_map: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
        ft_map.insert(b"test.dat".to_vec(), BencodeValue::Dict(file_node));

        let mut info_map: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
        info_map.insert(b"file tree".to_vec(), BencodeValue::Dict(ft_map));
        info_map.insert(b"meta version".to_vec(), BencodeValue::Integer(2));
        info_map.insert(b"name".to_vec(), BencodeValue::Bytes(b"v2test".to_vec()));
        info_map.insert(b"piece length".to_vec(), BencodeValue::Integer(16384));

        let mut root_map: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
        root_map.insert(b"info".to_vec(), BencodeValue::Dict(info_map));

        let bytes = irontide_bencode::to_bytes(&BencodeValue::Dict(root_map)).unwrap();
        let meta = irontide_core::torrent_from_bytes_any(&bytes).unwrap();
        assert!(meta.is_v2());

        // This should NOT return an error now (v2-only is supported)
        let info_hash = session.add_torrent_with_meta(meta, None).await.unwrap();
        let list = session.list_torrents().await.unwrap();
        assert!(list.contains(&info_hash));

        session.shutdown().await.unwrap();
    }

    // ---- Test 14: Save torrent resume data via session ----

    #[tokio::test]
    async fn save_torrent_resume_data_via_session() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 32768];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let rd = session.save_torrent_resume_data(info_hash).await.unwrap();
        assert_eq!(rd.info_hash, info_hash.as_bytes().as_slice());
        assert_eq!(rd.name, "test");
        assert_eq!(rd.file_format, "libtorrent resume file");
        assert_eq!(rd.file_version, 1);
        assert!(!rd.pieces.is_empty());
        assert_eq!(rd.paused, 0);

        session.shutdown().await.unwrap();
    }

    // ---- Test 15: Save session state captures all torrents ----

    #[tokio::test]
    async fn save_session_state_captures_all_torrents() {
        let session = SessionHandle::start(test_settings()).await.unwrap();

        let data1 = vec![0xAA; 16384];
        let meta1 = make_test_torrent(&data1, 16384);
        let storage1 = make_storage(&data1, 16384);
        session
            .add_torrent_with_meta(meta1.into(), Some(storage1))
            .await
            .unwrap();

        let data2 = vec![0xBB; 16384];
        let meta2 = make_test_torrent(&data2, 16384);
        let storage2 = make_storage(&data2, 16384);
        session
            .add_torrent_with_meta(meta2.into(), Some(storage2))
            .await
            .unwrap();

        let state = session.save_session_state().await.unwrap();
        assert_eq!(state.torrents.len(), 2);

        for rd in &state.torrents {
            assert_eq!(rd.file_format, "libtorrent resume file");
            assert_eq!(rd.info_hash.len(), 20);
        }

        session.shutdown().await.unwrap();
    }

    // ---- Test 16: Save resume data not found ----

    #[tokio::test]
    async fn save_resume_data_not_found() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let fake_hash = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        let result = session.save_torrent_resume_data(fake_hash).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
        session.shutdown().await.unwrap();
    }

    // ---- Test 17: Subscribe receives TorrentAdded alert ----

    #[tokio::test]
    async fn subscribe_receives_torrent_added_alert() {
        use crate::alert::AlertKind;

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut alerts = session.subscribe();

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let _info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let alert = tokio::time::timeout(Duration::from_secs(2), alerts.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(alert.kind, AlertKind::TorrentAdded { .. }));
        session.shutdown().await.unwrap();
    }

    // ---- Test 18: Subscribe receives TorrentRemoved alert ----

    #[tokio::test]
    async fn subscribe_receives_torrent_removed_alert() {
        use crate::alert::AlertKind;
        use crate::types::TorrentState;

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut alerts = session.subscribe();

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Drain TorrentAdded and any checking alerts
        while let Ok(Ok(a)) = tokio::time::timeout(Duration::from_secs(1), alerts.recv()).await {
            if matches!(
                a.kind,
                AlertKind::StateChanged {
                    new_state: TorrentState::Downloading,
                    ..
                }
            ) {
                break;
            }
        }

        session.remove_torrent(info_hash).await.unwrap();

        // Find TorrentRemoved (skip any interleaved alerts)
        loop {
            let alert = tokio::time::timeout(Duration::from_secs(2), alerts.recv())
                .await
                .unwrap()
                .unwrap();
            if matches!(alert.kind, AlertKind::TorrentRemoved { .. }) {
                break;
            }
        }
        session.shutdown().await.unwrap();
    }

    // ---- Test 19: Multiple subscribers each receive alerts ----

    #[tokio::test]
    async fn multiple_subscribers_each_receive_alerts() {
        use crate::alert::AlertKind;

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut sub1 = session.subscribe();
        let mut sub2 = session.subscribe();

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let a1 = tokio::time::timeout(Duration::from_secs(2), sub1.recv())
            .await
            .unwrap()
            .unwrap();
        let a2 = tokio::time::timeout(Duration::from_secs(2), sub2.recv())
            .await
            .unwrap()
            .unwrap();

        assert!(matches!(a1.kind, AlertKind::TorrentAdded { .. }));
        assert!(matches!(a2.kind, AlertKind::TorrentAdded { .. }));
        session.shutdown().await.unwrap();
    }

    // ---- Test 20: set_alert_mask filters at runtime ----

    #[tokio::test]
    async fn set_alert_mask_filters_at_runtime() {
        use crate::alert::{AlertCategory, AlertKind};

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut alerts = session.subscribe();

        // Start with ALL — TorrentAdded (STATUS) should arrive
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let alert = tokio::time::timeout(Duration::from_secs(2), alerts.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(alert.kind, AlertKind::TorrentAdded { .. }));

        // Drain any remaining alerts from the first torrent (StateChanged, CheckingProgress, etc.)
        while tokio::time::timeout(Duration::from_millis(200), alerts.recv())
            .await
            .is_ok()
        {}

        // Change mask to empty — no alerts should pass
        session.set_alert_mask(AlertCategory::empty());

        let data2 = vec![0xBB; 16384];
        let meta2 = make_test_torrent(&data2, 16384);
        let storage2 = make_storage(&data2, 16384);
        session
            .add_torrent_with_meta(meta2.into(), Some(storage2))
            .await
            .unwrap();

        // Give a small window — nothing should arrive
        let result = tokio::time::timeout(Duration::from_millis(200), alerts.recv()).await;
        assert!(result.is_err(), "should have timed out with empty mask");

        // Restore STATUS — adding another torrent should arrive
        session.set_alert_mask(AlertCategory::STATUS);

        let data3 = vec![0xCC; 16384];
        let meta3 = make_test_torrent(&data3, 16384);
        let storage3 = make_storage(&data3, 16384);
        session
            .add_torrent_with_meta(meta3.into(), Some(storage3))
            .await
            .unwrap();

        let alert = tokio::time::timeout(Duration::from_secs(2), alerts.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(alert.kind, AlertKind::TorrentAdded { .. }));

        session.shutdown().await.unwrap();
    }

    // ---- Test 21: AlertStream filters per subscriber ----

    #[tokio::test]
    async fn alert_stream_filters_per_subscriber() {
        use crate::alert::{AlertCategory, AlertKind};

        let session = SessionHandle::start(test_settings()).await.unwrap();

        // subscriber A: STATUS only
        let mut status_sub = session.subscribe_filtered(AlertCategory::STATUS);
        // subscriber B: PEER only
        let mut peer_sub = session.subscribe_filtered(AlertCategory::PEER);

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // STATUS sub gets TorrentAdded
        let alert = tokio::time::timeout(Duration::from_secs(2), status_sub.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(alert.kind, AlertKind::TorrentAdded { .. }));

        // PEER sub should NOT receive TorrentAdded (it's STATUS category)
        let result = tokio::time::timeout(Duration::from_millis(200), peer_sub.recv()).await;
        assert!(
            result.is_err(),
            "PEER subscriber should not get STATUS alerts"
        );

        session.shutdown().await.unwrap();
    }

    // ---- Test 22: State changed tracks transitions ----

    #[tokio::test]
    async fn state_changed_tracks_transitions() {
        use crate::alert::AlertKind;

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut alerts = session.subscribe();

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Drain TorrentAdded
        let _ = tokio::time::timeout(Duration::from_secs(1), alerts.recv())
            .await
            .unwrap();

        // Pause — should get StateChanged(Downloading → Paused) + TorrentPaused
        session.pause_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Collect alerts over a short window
        let mut state_changes = Vec::new();
        let mut paused_alerts = Vec::new();
        while let Ok(Ok(a)) = tokio::time::timeout(Duration::from_millis(200), alerts.recv()).await
        {
            match &a.kind {
                AlertKind::StateChanged {
                    prev_state,
                    new_state,
                    ..
                } => {
                    state_changes.push((*prev_state, *new_state));
                }
                AlertKind::TorrentPaused { .. } => {
                    paused_alerts.push(a);
                }
                _ => {} // other alerts (PeerConnected etc)
            }
        }

        assert!(
            state_changes.contains(&(TorrentState::Downloading, TorrentState::Paused)),
            "expected Downloading→Paused, got: {state_changes:?}"
        );
        assert!(!paused_alerts.is_empty(), "expected TorrentPaused alert");

        // Resume — should get StateChanged(Paused → Downloading) + TorrentResumed
        session.resume_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        let mut resume_state_changes = Vec::new();
        let mut resumed_alerts = Vec::new();
        while let Ok(Ok(a)) = tokio::time::timeout(Duration::from_millis(200), alerts.recv()).await
        {
            match &a.kind {
                AlertKind::StateChanged {
                    prev_state,
                    new_state,
                    ..
                } => {
                    resume_state_changes.push((*prev_state, *new_state));
                }
                AlertKind::TorrentResumed { .. } => {
                    resumed_alerts.push(a);
                }
                _ => {}
            }
        }

        assert!(
            resume_state_changes.contains(&(TorrentState::Paused, TorrentState::Downloading)),
            "expected Paused→Downloading, got: {resume_state_changes:?}"
        );
        assert!(!resumed_alerts.is_empty(), "expected TorrentResumed alert");

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn session_config_creates_utp_socket() {
        // Start session with uTP enabled — should succeed without errors
        let mut config = test_settings();
        config.enable_utp = true;
        let session = SessionHandle::start(config).await.unwrap();
        let stats = session.session_stats().await.unwrap();
        assert_eq!(stats.active_torrents, 0);
        session.shutdown().await.unwrap();
    }

    #[test]
    fn settings_nat_defaults() {
        let s = Settings::default();
        assert!(s.enable_upnp, "enable_upnp should default to true");
        assert!(s.enable_natpmp, "enable_natpmp should default to true");
    }

    #[tokio::test]
    async fn session_with_nat_disabled() {
        let config = test_settings();
        // test_session_config already sets enable_upnp: false, enable_natpmp: false
        assert!(!config.enable_upnp);
        assert!(!config.enable_natpmp);
        let session = SessionHandle::start(config).await.unwrap();
        let stats = session.session_stats().await.unwrap();
        assert_eq!(stats.active_torrents, 0);
        session.shutdown().await.unwrap();
    }

    // ---- M29: Anonymous mode, force proxy, proxy config tests ----

    #[test]
    fn anonymous_mode_disables_discovery() {
        let mut config = test_settings();
        config.anonymous_mode = true;
        config.enable_dht = true;
        config.enable_lsd = true;
        config.enable_upnp = true;
        config.enable_natpmp = true;

        // SessionHandle::start() will override these when anonymous_mode is true.
        // We test the enforcement logic directly here.
        if config.anonymous_mode {
            config.enable_dht = false;
            config.enable_lsd = false;
            config.enable_upnp = false;
            config.enable_natpmp = false;
        }

        assert!(!config.enable_dht);
        assert!(!config.enable_lsd);
        assert!(!config.enable_upnp);
        assert!(!config.enable_natpmp);
    }

    #[tokio::test]
    async fn anonymous_mode_session_starts_with_discovery_disabled() {
        let mut config = test_settings();
        config.anonymous_mode = true;
        // Even if we enable these, anonymous_mode should override
        config.enable_dht = true;
        config.enable_lsd = true;

        let session = SessionHandle::start(config).await.unwrap();
        let stats = session.session_stats().await.unwrap();
        assert_eq!(stats.active_torrents, 0);
        session.shutdown().await.unwrap();
    }

    #[test]
    fn force_proxy_requires_proxy_configured() {
        let mut config = test_settings();
        config.force_proxy = true;
        config.proxy = crate::proxy::ProxyConfig::default(); // no proxy

        // Validate the config error
        assert_eq!(config.proxy.proxy_type, crate::proxy::ProxyType::None);
        assert!(config.force_proxy);
        // This would error in SessionHandle::start()
    }

    #[tokio::test]
    async fn force_proxy_errors_without_proxy() {
        let mut config = test_settings();
        config.force_proxy = true;
        // proxy_type is None by default

        let result = SessionHandle::start(config).await;
        assert!(result.is_err());
        match result {
            Err(e) => assert!(
                e.to_string().contains("force_proxy"),
                "error should mention force_proxy: {e}"
            ),
            Ok(_) => panic!("expected error"),
        }
    }

    #[test]
    fn force_proxy_disables_features() {
        let mut config = test_settings();
        config.force_proxy = true;
        config.proxy = crate::proxy::ProxyConfig {
            proxy_type: crate::proxy::ProxyType::Socks5,
            hostname: "proxy.example.com".into(),
            port: 1080,
            ..Default::default()
        };
        config.enable_dht = true;
        config.enable_lsd = true;
        config.enable_upnp = true;
        config.enable_natpmp = true;

        // Simulate the enforcement from start()
        if config.force_proxy {
            config.enable_upnp = false;
            config.enable_natpmp = false;
            config.enable_dht = false;
            config.enable_lsd = false;
        }

        assert!(!config.enable_dht);
        assert!(!config.enable_lsd);
        assert!(!config.enable_upnp);
        assert!(!config.enable_natpmp);
    }

    #[test]
    fn proxy_config_round_trip() {
        let s = Settings {
            proxy: crate::proxy::ProxyConfig {
                proxy_type: crate::proxy::ProxyType::Socks5Password,
                hostname: "localhost".into(),
                port: 9050,
                username: Some("user".into()),
                password: Some("pass".into()),
                ..Default::default()
            },
            force_proxy: true,
            anonymous_mode: true,
            ..test_settings()
        };

        assert_eq!(s.proxy.proxy_type, crate::proxy::ProxyType::Socks5Password);
        assert_eq!(s.proxy.hostname, "localhost");
        assert_eq!(s.proxy.port, 9050);
        assert!(s.force_proxy);
        assert!(s.anonymous_mode);
        assert_eq!(s.proxy.to_url(), "socks5://user:pass@localhost:9050");
    }

    #[tokio::test]
    async fn apply_settings_runtime() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let original = session.settings().await.unwrap();
        assert_eq!(original.max_torrents, 10);

        let mut new = original.clone();
        new.max_torrents = 200;
        new.upload_rate_limit = 1_000_000;
        session.apply_settings(new).await.unwrap();

        let updated = session.settings().await.unwrap();
        assert_eq!(updated.max_torrents, 200);
        assert_eq!(updated.upload_rate_limit, 1_000_000);

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn apply_settings_validation_error() {
        let session = SessionHandle::start(test_settings()).await.unwrap();

        // force_proxy=true without a proxy configured should fail validation
        let bad = Settings {
            force_proxy: true,
            ..Settings::default()
        };
        let result = session.apply_settings(bad).await;
        assert!(result.is_err());

        // Original settings should be unchanged
        let current = session.settings().await.unwrap();
        assert!(!current.force_proxy);

        session.shutdown().await.unwrap();
    }

    // ---- M50: Session stats counters tests ----

    #[tokio::test]
    async fn session_stats_counters_accessible() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let counters = session.counters();
        // Exercise the uptime accessor (returns u64, so >= 0 is tautological;
        // the meaningful check is that the call doesn't panic and counters
        // are wired up).
        let _ = counters.uptime_secs();
        assert_eq!(counters.len(), crate::stats::NUM_METRICS);
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn post_session_stats_fires_alert() {
        use crate::alert::{AlertCategory, AlertKind};

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut stats_sub = session.subscribe_filtered(AlertCategory::STATS);

        session.post_session_stats().await.unwrap();

        let alert = tokio::time::timeout(Duration::from_secs(2), stats_sub.recv())
            .await
            .expect("timed out waiting for SessionStatsAlert")
            .expect("recv error");
        assert!(
            matches!(alert.kind, AlertKind::SessionStatsAlert { ref values } if values.len() == crate::stats::NUM_METRICS),
            "expected SessionStatsAlert with {} values, got {:?}",
            crate::stats::NUM_METRICS,
            alert.kind,
        );
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn session_stats_include_torrent_count() {
        use crate::alert::{AlertCategory, AlertKind};

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let mut stats_sub = session.subscribe_filtered(AlertCategory::STATS);

        // Add a torrent
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        session.post_session_stats().await.unwrap();

        let alert = tokio::time::timeout(Duration::from_secs(2), stats_sub.recv())
            .await
            .expect("timed out waiting for SessionStatsAlert")
            .expect("recv error");
        match alert.kind {
            AlertKind::SessionStatsAlert { values } => {
                assert!(
                    values[crate::stats::SES_NUM_TORRENTS] > 0,
                    "SES_NUM_TORRENTS should be > 0 after adding a torrent, got {}",
                    values[crate::stats::SES_NUM_TORRENTS],
                );
            }
            other => panic!("expected SessionStatsAlert, got {other:?}"),
        }
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn stats_timer_disabled_when_zero() {
        use crate::alert::AlertCategory;

        let mut config = test_settings();
        config.stats_report_interval = 0;
        let session = SessionHandle::start(config).await.unwrap();
        let mut stats_sub = session.subscribe_filtered(AlertCategory::STATS);

        // Wait 200ms — no periodic stats alert should arrive
        let result = tokio::time::timeout(Duration::from_millis(200), stats_sub.recv()).await;
        assert!(
            result.is_err(),
            "no SessionStatsAlert should fire when stats_report_interval is 0"
        );
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn sample_infohashes_timer_disabled_when_zero() {
        use crate::alert::AlertCategory;

        let mut config = test_settings();
        config.dht_sample_infohashes_interval = 0;
        let session = SessionHandle::start(config).await.unwrap();
        let mut dht_sub = session.subscribe_filtered(AlertCategory::DHT);

        // Wait 200ms — no DhtSampleInfohashes alert should arrive
        let result = tokio::time::timeout(Duration::from_millis(200), dht_sub.recv()).await;
        assert!(
            result.is_err(),
            "no DhtSampleInfohashes alert should fire when interval is 0"
        );
        session.shutdown().await.unwrap();
    }

    // ---- Test: open_file returns TorrentNotFound for unknown hash ----

    #[tokio::test]
    async fn open_file_not_found() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let fake_hash = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        let result = session.open_file(fake_hash, 0).await;
        assert!(result.is_err());
        let err = result.err().unwrap();
        assert!(err.to_string().contains("not found"));
        session.shutdown().await.unwrap();
    }

    // ---- Test: open_file on a real torrent routes to TorrentHandle ----

    #[tokio::test]
    async fn open_file_routes_to_torrent() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 32768];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // open_file should succeed for file_index 0 (single-file torrent)
        let stream = session.open_file(info_hash, 0).await;
        assert!(stream.is_ok(), "open_file should succeed for file_index 0");

        // open_file should fail for out-of-range file_index
        let result = session.open_file(info_hash, 999).await;
        assert!(
            result.is_err(),
            "open_file should fail for invalid file_index"
        );

        session.shutdown().await.unwrap();
    }

    // ---- Test: force_reannounce via session ----

    #[tokio::test]
    async fn session_force_reannounce() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should succeed for a known torrent.
        let result = session.force_reannounce(info_hash).await;
        assert!(
            result.is_ok(),
            "force_reannounce should succeed: {result:?}"
        );

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.force_reannounce(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: tracker_list via session ----

    #[tokio::test]
    async fn session_tracker_list() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should succeed (empty list since test torrent has no announce URL).
        let trackers = session.tracker_list(info_hash).await.unwrap();
        assert!(trackers.is_empty(), "test torrent has no trackers");

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.tracker_list(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: scrape via session ----

    #[tokio::test]
    async fn session_scrape() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should succeed (None since test torrent has no trackers to scrape).
        let scrape = session.scrape(info_hash).await.unwrap();
        assert!(scrape.is_none(), "test torrent has no trackers to scrape");

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.scrape(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: set_file_priority via session ----

    #[tokio::test]
    async fn session_set_file_priority() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should succeed for file index 0 (single-file torrent).
        let result = session
            .set_file_priority(info_hash, 0, irontide_core::FilePriority::Normal)
            .await;
        assert!(
            result.is_ok(),
            "set_file_priority should succeed: {result:?}"
        );

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(
            session
                .set_file_priority(fake, 0, irontide_core::FilePriority::Normal)
                .await
                .is_err()
        );

        session.shutdown().await.unwrap();
    }

    // ---- Test: file_priorities via session ----

    #[tokio::test]
    async fn session_file_priorities() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should return priorities for the single file.
        let priorities = session.file_priorities(info_hash).await.unwrap();
        assert_eq!(
            priorities.len(),
            1,
            "single-file torrent should have 1 file priority"
        );
        assert_eq!(priorities[0], irontide_core::FilePriority::Normal);

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.file_priorities(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: set_download_limit zero means unlimited ----

    #[tokio::test]
    async fn set_download_limit_zero_means_unlimited() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Set limit to non-zero, then back to zero (unlimited).
        session.set_download_limit(info_hash, 50_000).await.unwrap();
        session.set_download_limit(info_hash, 0).await.unwrap();
        let limit = session.download_limit(info_hash).await.unwrap();
        assert_eq!(limit, 0, "0 means unlimited");

        session.shutdown().await.unwrap();
    }

    // ---- Test: set_upload_limit persists ----

    #[tokio::test]
    async fn set_upload_limit_persists() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        session.set_upload_limit(info_hash, 100_000).await.unwrap();
        let limit = session.upload_limit(info_hash).await.unwrap();
        assert_eq!(limit, 100_000);

        session.shutdown().await.unwrap();
    }

    // ---- Test: download_limit default is zero ----

    #[tokio::test]
    async fn download_limit_default_is_zero() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Default config has download_rate_limit = 0.
        let limit = session.download_limit(info_hash).await.unwrap();
        assert_eq!(limit, 0, "default download limit should be 0 (unlimited)");

        session.shutdown().await.unwrap();
    }

    // ---- Test: rate_limit_round_trip ----

    #[tokio::test]
    async fn rate_limit_round_trip() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Set both limits.
        session
            .set_download_limit(info_hash, 1_000_000)
            .await
            .unwrap();
        session.set_upload_limit(info_hash, 500_000).await.unwrap();

        // Read them back.
        let dl = session.download_limit(info_hash).await.unwrap();
        let ul = session.upload_limit(info_hash).await.unwrap();
        assert_eq!(dl, 1_000_000);
        assert_eq!(ul, 500_000);

        // Update and verify again.
        session
            .set_download_limit(info_hash, 2_000_000)
            .await
            .unwrap();
        let dl = session.download_limit(info_hash).await.unwrap();
        assert_eq!(dl, 2_000_000);

        // Unknown torrent should fail.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.download_limit(fake).await.is_err());
        assert!(session.upload_limit(fake).await.is_err());
        assert!(session.set_download_limit(fake, 100).await.is_err());
        assert!(session.set_upload_limit(fake, 100).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: sequential_download_toggle ----

    #[tokio::test]
    async fn sequential_download_toggle() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Enable sequential download.
        session
            .set_sequential_download(info_hash, true)
            .await
            .unwrap();
        assert!(session.is_sequential_download(info_hash).await.unwrap());

        // Disable it again.
        session
            .set_sequential_download(info_hash, false)
            .await
            .unwrap();
        assert!(!session.is_sequential_download(info_hash).await.unwrap());

        session.shutdown().await.unwrap();
    }

    // ---- Test: super_seeding_toggle ----

    #[tokio::test]
    async fn super_seeding_toggle() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Enable super seeding.
        session.set_super_seeding(info_hash, true).await.unwrap();
        assert!(session.is_super_seeding(info_hash).await.unwrap());

        // Disable it again.
        session.set_super_seeding(info_hash, false).await.unwrap();
        assert!(!session.is_super_seeding(info_hash).await.unwrap());

        session.shutdown().await.unwrap();
    }

    // ---- Test: sequential_download_default_false ----

    #[tokio::test]
    async fn sequential_download_default_false() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Default config has sequential_download = false.
        assert!(!session.is_sequential_download(info_hash).await.unwrap());

        session.shutdown().await.unwrap();
    }

    // ---- Test: super_seeding_default_false ----

    #[tokio::test]
    async fn super_seeding_default_false() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Default config has super_seeding = false.
        assert!(!session.is_super_seeding(info_hash).await.unwrap());

        session.shutdown().await.unwrap();
    }

    // ---- M159 Test: seed_mode_flips_user_flag ----

    #[tokio::test]
    async fn seed_mode_flips_user_flag() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Initial state: user_seed_mode defaults to false.
        let stats_before = session.torrent_stats(info_hash).await.unwrap();
        assert!(
            !stats_before.user_seed_mode,
            "new torrent should not start in user seed mode"
        );

        // Enable user seed mode.
        session.set_seed_mode(info_hash, true).await.unwrap();
        let stats_on = session.torrent_stats(info_hash).await.unwrap();
        assert!(
            stats_on.user_seed_mode,
            "stats should reflect user_seed_mode=true after enabling"
        );

        // Disable it again.
        session.set_seed_mode(info_hash, false).await.unwrap();
        let stats_off = session.torrent_stats(info_hash).await.unwrap();
        assert!(
            !stats_off.user_seed_mode,
            "stats should reflect user_seed_mode=false after disabling"
        );

        session.shutdown().await.unwrap();
    }

    // ---- M159 Test: seed_mode_round_trip ----

    #[tokio::test]
    async fn seed_mode_round_trip() {
        // Five flips in a row, exercising the actor's toggle idempotency and
        // piece-reservation cleanup logic. Must not panic and must leave the
        // flag consistent with the most recent call.
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        for (i, enabled) in [true, false, true, true, false].iter().enumerate() {
            session.set_seed_mode(info_hash, *enabled).await.unwrap();
            let stats = session.torrent_stats(info_hash).await.unwrap();
            assert_eq!(
                stats.user_seed_mode, *enabled,
                "iteration {i}: stats.user_seed_mode should track the toggle"
            );
        }

        session.shutdown().await.unwrap();
    }

    // ---- M159 Test: seed_mode_missing_info_hash_errors ----

    #[tokio::test]
    async fn seed_mode_missing_info_hash_errors() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let fake =
            irontide_core::Id20::from_hex("ffffffffffffffffffffffffffffffffffffffff").unwrap();
        let err = session
            .set_seed_mode(fake, true)
            .await
            .expect_err("set_seed_mode on unknown info hash must return an error");
        match err {
            crate::Error::TorrentNotFound(h) => assert_eq!(h, fake),
            other => panic!("expected TorrentNotFound, got {other:?}"),
        }
        session.shutdown().await.unwrap();
    }

    // ---- M159 Test: seed_mode_idempotent ----

    #[tokio::test]
    async fn seed_mode_idempotent() {
        // Setting the same value twice must not panic or corrupt state.
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Set true twice — second call is a no-op.
        session.set_seed_mode(info_hash, true).await.unwrap();
        session.set_seed_mode(info_hash, true).await.unwrap();
        assert!(
            session
                .torrent_stats(info_hash)
                .await
                .unwrap()
                .user_seed_mode
        );

        // Set false twice — also a no-op the second time.
        session.set_seed_mode(info_hash, false).await.unwrap();
        session.set_seed_mode(info_hash, false).await.unwrap();
        assert!(
            !session
                .torrent_stats(info_hash)
                .await
                .unwrap()
                .user_seed_mode
        );

        session.shutdown().await.unwrap();
    }

    // ---- Test: add_tracker_increases_count ----

    #[tokio::test]
    async fn add_tracker_increases_count() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Test torrent has no trackers initially.
        let before = session.tracker_list(info_hash).await.unwrap();
        assert!(before.is_empty());

        // Add a tracker.
        session
            .add_tracker(info_hash, "udp://tracker.example.com:6969/announce".into())
            .await
            .unwrap();

        let after = session.tracker_list(info_hash).await.unwrap();
        assert_eq!(after.len(), 1);
        assert_eq!(after[0].url, "udp://tracker.example.com:6969/announce");

        session.shutdown().await.unwrap();
    }

    // ---- Test: replace_trackers_replaces_all ----

    #[tokio::test]
    async fn replace_trackers_replaces_all() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Add 2 trackers.
        session
            .add_tracker(info_hash, "udp://tracker1.example.com:6969/announce".into())
            .await
            .unwrap();
        session
            .add_tracker(info_hash, "http://tracker2.example.com/announce".into())
            .await
            .unwrap();
        assert_eq!(session.tracker_list(info_hash).await.unwrap().len(), 2);

        // Replace with 1 different tracker.
        session
            .replace_trackers(
                info_hash,
                vec!["http://replacement.example.com/announce".into()],
            )
            .await
            .unwrap();

        let after = session.tracker_list(info_hash).await.unwrap();
        assert_eq!(after.len(), 1);
        assert_eq!(after[0].url, "http://replacement.example.com/announce");

        session.shutdown().await.unwrap();
    }

    // ---- Test: add_tracker_deduplicates ----

    #[tokio::test]
    async fn add_tracker_deduplicates() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Add the same tracker URL twice.
        session
            .add_tracker(info_hash, "udp://tracker.example.com:6969/announce".into())
            .await
            .unwrap();
        session
            .add_tracker(info_hash, "udp://tracker.example.com:6969/announce".into())
            .await
            .unwrap();

        // Should only have 1 tracker (deduplicated).
        let trackers = session.tracker_list(info_hash).await.unwrap();
        assert_eq!(trackers.len(), 1);

        session.shutdown().await.unwrap();
    }

    // ---- Test: info_hashes_matches_added_torrent ----

    #[tokio::test]
    async fn info_hashes_matches_added_torrent() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let expected_v1 = meta.info_hash;
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        let hashes = session.info_hashes(info_hash).await.unwrap();
        assert_eq!(hashes.v1, Some(expected_v1));
        // v1-only torrent should not have v2 hash
        assert!(hashes.v2.is_none());

        session.shutdown().await.unwrap();
    }

    // ---- Test: torrent_file_returns_meta ----

    #[tokio::test]
    async fn torrent_file_returns_meta() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 32768];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();
        let torrent = session.torrent_file(info_hash).await.unwrap();
        assert!(torrent.is_some());
        let torrent = torrent.unwrap();
        assert_eq!(torrent.info_hash, info_hash);
        assert_eq!(torrent.info.name, "test");
        assert_eq!(torrent.info.total_length(), 32768);

        session.shutdown().await.unwrap();
    }

    // ---- Test: torrent_file_none_before_metadata ----

    #[tokio::test]
    async fn torrent_file_none_before_metadata() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let magnet = irontide_core::Magnet::parse(
            "magnet:?xt=urn:btih:aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d&dn=test",
        )
        .unwrap();

        let info_hash = session.add_magnet(magnet).await.unwrap();
        let torrent = session.torrent_file(info_hash).await.unwrap();
        // Before metadata is received, torrent_file should return None.
        assert!(torrent.is_none());

        session.shutdown().await.unwrap();
    }

    // ---- Test: force_dht_announce_no_error ----

    #[tokio::test]
    async fn force_dht_announce_no_error() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should succeed even without DHT enabled (no-op, no error).
        let result = session.force_dht_announce(info_hash).await;
        assert!(
            result.is_ok(),
            "force_dht_announce should succeed: {result:?}"
        );

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.force_dht_announce(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: force_lsd_announce_no_error ----

    #[tokio::test]
    async fn force_lsd_announce_no_error() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Should succeed even without LSD enabled (no-op announce, no error).
        let result = session.force_lsd_announce(info_hash).await;
        assert!(
            result.is_ok(),
            "force_lsd_announce should succeed: {result:?}"
        );

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.force_lsd_announce(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: read_piece_after_download ----

    #[tokio::test]
    async fn read_piece_after_download() {
        let data = vec![0xCD; 32768]; // 2 pieces of 16384
        let meta = make_test_torrent(&data, 16384);
        let lengths = Lengths::new(data.len() as u64, 16384, DEFAULT_CHUNK_SIZE);
        let storage = Arc::new(MemoryStorage::new(lengths));
        // Pre-fill storage with the data
        storage.write_chunk(0, 0, &data[..16384]).unwrap();
        storage.write_chunk(1, 0, &data[16384..]).unwrap();

        let session = SessionHandle::start(test_settings()).await.unwrap();
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Read piece 0
        let piece_data = session.read_piece(info_hash, 0).await.unwrap();
        assert_eq!(piece_data.len(), 16384);
        assert!(piece_data.iter().all(|&b| b == 0xCD));

        // Read piece 1
        let piece_data = session.read_piece(info_hash, 1).await.unwrap();
        assert_eq!(piece_data.len(), 16384);
        assert!(piece_data.iter().all(|&b| b == 0xCD));

        // Out-of-range piece should fail
        let result = session.read_piece(info_hash, 999).await;
        assert!(result.is_err(), "read_piece out of range should fail");

        // Unknown torrent should fail
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.read_piece(fake, 0).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- Test: flush_cache_completes ----

    #[tokio::test]
    async fn flush_cache_completes() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // flush_cache should succeed.
        let result = session.flush_cache(info_hash).await;
        assert!(result.is_ok(), "flush_cache should succeed: {result:?}");

        // Should fail for unknown torrent.
        let fake = Id20::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert!(session.flush_cache(fake).await.is_err());

        session.shutdown().await.unwrap();
    }

    // ---- BEP 44 session API tests ----

    fn test_settings_with_dht() -> Settings {
        let mut s = test_settings();
        s.enable_dht = true;
        s
    }

    fn test_settings_with_lsd() -> Settings {
        let mut s = test_settings();
        s.enable_lsd = true;
        s
    }

    #[tokio::test]
    async fn test_dht_disabled_returns_error() {
        let session = SessionHandle::start(test_settings()).await.unwrap();

        // All 4 methods should fail with DhtDisabled when DHT is off
        let err = session
            .dht_put_immutable(b"test".to_vec())
            .await
            .unwrap_err();
        assert!(
            format!("{err:?}").contains("DhtDisabled"),
            "expected DhtDisabled, got {err:?}"
        );

        let target = Id20::from([0u8; 20]);
        let err = session.dht_get_immutable(target).await.unwrap_err();
        assert!(
            format!("{err:?}").contains("DhtDisabled"),
            "expected DhtDisabled, got {err:?}"
        );

        let err = session
            .dht_put_mutable([42u8; 32], b"val".to_vec(), 1, Vec::new())
            .await
            .unwrap_err();
        assert!(
            format!("{err:?}").contains("DhtDisabled"),
            "expected DhtDisabled, got {err:?}"
        );

        let err = session
            .dht_get_mutable([42u8; 32], Vec::new())
            .await
            .unwrap_err();
        assert!(
            format!("{err:?}").contains("DhtDisabled"),
            "expected DhtDisabled, got {err:?}"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_dht_put_get_immutable_round_trip() {
        let session = SessionHandle::start(test_settings_with_dht())
            .await
            .unwrap();

        // Give DHT a moment to bootstrap (it won't find real nodes, but the handle should work)
        let value = b"hello BEP 44".to_vec();
        let target = session.dht_put_immutable(value.clone()).await.unwrap();

        // The target should be the SHA-1 of the bencoded value
        // Try to get it back — since we're the only node, the local store should have it
        let got = session.dht_get_immutable(target).await.unwrap();
        assert_eq!(got, Some(value));

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_dht_put_immutable_fires_alert() {
        use crate::alert::{AlertCategory, AlertKind};

        let session = SessionHandle::start(test_settings_with_dht())
            .await
            .unwrap();
        let mut alerts = session.subscribe_filtered(AlertCategory::DHT);

        let value = b"alert test".to_vec();
        let target = session.dht_put_immutable(value).await.unwrap();

        // Should receive DhtPutComplete alert
        let alert = tokio::time::timeout(Duration::from_secs(5), alerts.recv())
            .await
            .expect("timeout waiting for alert")
            .expect("alert channel closed");

        match alert.kind {
            AlertKind::DhtPutComplete { target: t } => {
                assert_eq!(t, target);
            }
            other => panic!("expected DhtPutComplete, got {other:?}"),
        }

        session.shutdown().await.unwrap();
    }

    // ---- BEP 27: Private torrent LSD tests ----

    /// Creates a private torrent (.torrent bytes with private=1 in the info dict).
    fn make_private_torrent(data: &[u8], piece_length: u64) -> TorrentMetaV1 {
        use serde::Serialize;

        #[derive(Serialize)]
        struct Info<'a> {
            length: u64,
            name: &'a str,
            #[serde(rename = "piece length")]
            piece_length: u64,
            #[serde(with = "serde_bytes")]
            pieces: &'a [u8],
            private: i64,
        }

        #[derive(Serialize)]
        struct Torrent<'a> {
            info: Info<'a>,
        }

        let mut pieces = Vec::new();
        let mut offset = 0;
        while offset < data.len() {
            let end = (offset + piece_length as usize).min(data.len());
            let hash = irontide_core::sha1(&data[offset..end]);
            pieces.extend_from_slice(hash.as_bytes());
            offset = end;
        }

        let t = Torrent {
            info: Info {
                length: data.len() as u64,
                name: "private-test",
                piece_length,
                pieces: &pieces,
                private: 1,
            },
        };

        let bytes = irontide_bencode::to_bytes(&t).unwrap();
        torrent_from_bytes(&bytes).unwrap()
    }

    #[test]
    fn is_private_true_via_parsed_meta() {
        // Verify that a torrent parsed from private .torrent bytes has private == Some(1)
        let data = vec![0xAB; 16384];
        let meta = make_private_torrent(&data, 16384);
        assert_eq!(
            meta.info.private,
            Some(1),
            "private field should be Some(1)"
        );
    }

    #[test]
    fn is_private_false_for_public_torrent() {
        // Verify that a regular torrent has private == None
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        assert_eq!(
            meta.info.private, None,
            "public torrent should have no private flag"
        );
    }

    #[test]
    fn private_torrent_config_disables_lsd() {
        // Verify that TorrentConfig::default() has LSD enabled (so disable is meaningful)
        let config = TorrentConfig::default();
        assert!(
            config.enable_lsd,
            "default TorrentConfig should have LSD enabled"
        );
    }

    #[tokio::test]
    async fn force_lsd_announce_private_torrent_returns_error() {
        let session = SessionHandle::start(test_settings()).await.unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_private_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // BEP 27: force_lsd_announce on a private torrent must return an error
        let result = session.force_lsd_announce(info_hash).await;
        assert!(
            result.is_err(),
            "force_lsd_announce on private torrent should return error, got: {result:?}"
        );
        let err_str = format!("{:?}", result.unwrap_err());
        assert!(
            err_str.contains("InvalidSettings") || err_str.contains("LSD disabled"),
            "expected InvalidSettings error, got: {err_str}"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn force_lsd_announce_public_torrent_does_not_trigger_bep27_error() {
        // v0.173.2 A10 companion to the DHT negative-form test added in T1.
        //
        // NEGATIVE form (codex finding #2): we only assert the BEP 27 gate doesn't
        // reject. We do NOT assert Ok — LSD may return Ok for a different reason
        // (e.g., self.lsd is None per session.rs:945's startup-failure swallow),
        // and asserting Ok would mask that case while still passing. We also
        // don't assert a specific Err — public torrents on an enabled-LSD session
        // typically return Ok, but a test-sandbox LSD init glitch could legitimately
        // error without the BEP 27 gate being involved.
        let session = SessionHandle::start(test_settings_with_lsd())
            .await
            .unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let result = session.force_lsd_announce(info_hash).await;
        if let Err(e) = &result {
            assert!(
                !format!("{e:?}").contains("LSD disabled for private torrent"),
                "public torrent must NOT trigger BEP 27 error; got {e:?}"
            );
        }

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn force_dht_announce_private_torrent_returns_error() {
        let session = SessionHandle::start(test_settings_with_dht())
            .await
            .unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_private_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // BEP 27: force_dht_announce on a private torrent must return an error
        let result = session.force_dht_announce(info_hash).await;
        assert!(
            result.is_err(),
            "force_dht_announce on private torrent should return error, got: {result:?}"
        );
        let err_str = format!("{:?}", result.unwrap_err());
        assert!(
            err_str.contains("InvalidSettings")
                || err_str.contains("DHT disabled for private torrent"),
            "expected InvalidSettings / DHT-disabled error, got: {err_str}"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn force_dht_announce_public_torrent_does_not_trigger_bep27_error() {
        let session = SessionHandle::start(test_settings_with_dht())
            .await
            .unwrap();
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let result = session.force_dht_announce(info_hash).await;
        // NEGATIVE form: we only assert the BEP 27 gate doesn't reject. We do NOT
        // assert Ok — DHT may not be initialised in the test sandbox, returning a
        // different error. Asserting Ok here would mask both the test sandbox
        // limitation AND a future regression where the BEP 27 gate accidentally
        // catches public torrents.
        if let Err(e) = &result {
            assert!(
                !format!("{e:?}").contains("DHT disabled for private torrent"),
                "public torrent must NOT trigger BEP 27 error; got {e:?}"
            );
        }

        session.shutdown().await.unwrap();
    }

    // ---- M161: save_resume_state tests ----

    fn resume_test_settings(dir: &std::path::Path) -> Settings {
        Settings {
            resume_data_dir: Some(dir.to_path_buf()),
            save_resume_interval_secs: 0, // disable periodic timer for tests
            ..test_settings()
        }
    }

    #[tokio::test]
    async fn save_resume_state_empty_session_returns_zero() {
        let tmp = tempfile::TempDir::new().unwrap();
        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        let count = session.save_resume_state().await.unwrap();
        assert_eq!(count, 0, "empty session should save 0 resume files");

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn save_resume_state_saves_dirty_torrents() {
        let tmp = tempfile::TempDir::new().unwrap();
        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        // Add two torrents with different data so they get different hashes
        let data1 = vec![0xAA; 16384];
        let meta1 = make_test_torrent(&data1, 16384);
        let hash1 = meta1.info_hash;
        let storage1 = make_storage(&data1, 16384);
        session
            .add_torrent_with_meta(meta1.into(), Some(storage1))
            .await
            .unwrap();

        let data2 = vec![0xBB; 16384];
        let meta2 = make_test_torrent(&data2, 16384);
        let hash2 = meta2.info_hash;
        let storage2 = make_storage(&data2, 16384);
        session
            .add_torrent_with_meta(meta2.into(), Some(storage2))
            .await
            .unwrap();

        // Both torrents should be dirty (newly added → need_save_resume = true
        // after any state change). Give the actors a moment to settle.
        tokio::time::sleep(Duration::from_millis(50)).await;

        let count = session.save_resume_state().await.unwrap();
        // Newly created torrents may or may not have the dirty flag set
        // depending on whether state changes have occurred. Verify that
        // at least the files are created for any that were dirty.
        assert!(count <= 2, "should save at most 2 resume files");

        // Verify files exist on disk for saved torrents
        let torrents_dir = tmp.path().join("torrents");
        if count > 0 {
            assert!(torrents_dir.exists(), "torrents/ directory should exist");
        }

        // Check specific file paths
        let path1 = crate::resume_file::resume_file_path(tmp.path(), &hash1);
        let path2 = crate::resume_file::resume_file_path(tmp.path(), &hash2);
        let files_exist = usize::from(path1.exists()) + usize::from(path2.exists());
        assert_eq!(
            files_exist, count,
            "number of files on disk should match returned count"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn save_resume_state_round_trip() {
        let tmp = tempfile::TempDir::new().unwrap();
        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        let data = vec![0xCD; 32768];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Let the actor settle so dirty flag is set
        tokio::time::sleep(Duration::from_millis(50)).await;

        let count = session.save_resume_state().await.unwrap();

        // If the torrent was dirty and saved, verify round-trip
        if count > 0 {
            let path = crate::resume_file::resume_file_path(tmp.path(), &info_hash);
            assert!(path.exists(), "resume file should exist after save");

            let bytes = std::fs::read(&path).unwrap();
            let rd = crate::resume_file::deserialize_resume(&bytes).unwrap();
            assert_eq!(
                rd.info_hash,
                info_hash.as_bytes().to_vec(),
                "deserialized info_hash should match"
            );
            assert_eq!(rd.name, "test", "deserialized name should match");
        }

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn save_resume_state_clears_dirty_flag() {
        let tmp = tempfile::TempDir::new().unwrap();
        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        let data = vec![0xEE; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        tokio::time::sleep(Duration::from_millis(50)).await;

        let first_count = session.save_resume_state().await.unwrap();

        // Second save should return 0 because dirty flag was cleared
        let second_count = session.save_resume_state().await.unwrap();
        assert_eq!(
            second_count, 0,
            "second save should return 0 after dirty flag cleared (first saved {first_count})"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn save_resume_state_second_save_skips_clean() {
        let tmp = tempfile::TempDir::new().unwrap();
        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        let data1 = vec![0xAA; 16384];
        let meta1 = make_test_torrent(&data1, 16384);
        let storage1 = make_storage(&data1, 16384);
        session
            .add_torrent_with_meta(meta1.into(), Some(storage1))
            .await
            .unwrap();

        let data2 = vec![0xBB; 16384];
        let meta2 = make_test_torrent(&data2, 16384);
        let storage2 = make_storage(&data2, 16384);
        session
            .add_torrent_with_meta(meta2.into(), Some(storage2))
            .await
            .unwrap();

        tokio::time::sleep(Duration::from_millis(50)).await;

        // First save
        let first = session.save_resume_state().await.unwrap();

        // Second save — all flags should be cleared, nothing to write
        let second = session.save_resume_state().await.unwrap();
        assert_eq!(
            second, 0,
            "second save should skip all clean torrents (first saved {first})"
        );

        session.shutdown().await.unwrap();
    }

    // ==== M161 Phase 4: load_resume_state tests ====

    // ---- Test: empty dir → zeros ----

    #[tokio::test]
    async fn load_resume_empty_dir_returns_zeros() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut settings = test_settings();
        settings.resume_data_dir = Some(tmp.path().to_path_buf());

        let session = SessionHandle::start(settings).await.unwrap();
        let result = session.load_resume_state().await.unwrap();
        assert_eq!(result.restored, 0);
        assert_eq!(result.skipped, 0);
        assert_eq!(result.failed, 0);

        session.shutdown().await.unwrap();
    }

    // ---- Test: corrupt file skipped ----

    #[tokio::test]
    async fn load_resume_corrupt_file_counted_as_failed() {
        let tmp = tempfile::TempDir::new().unwrap();
        let torrents_dir = tmp.path().join("torrents");
        std::fs::create_dir_all(&torrents_dir).unwrap();

        let mut settings = test_settings();
        settings.resume_data_dir = Some(tmp.path().to_path_buf());

        // Start session first (auto-restore runs but dir is empty).
        let session = SessionHandle::start(settings).await.unwrap();

        // Wait for auto-restore to complete before writing the file,
        // otherwise the actor may race with file creation.
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Write garbage to a .resume file *after* startup so auto-restore
        // does not consume it.
        std::fs::write(
            torrents_dir.join("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef.resume"),
            b"this is not valid bencode",
        )
        .unwrap();

        let result = session.load_resume_state().await.unwrap();
        assert_eq!(result.restored, 0);
        assert_eq!(result.skipped, 0);
        assert_eq!(result.failed, 1);

        session.shutdown().await.unwrap();
    }

    // ---- Test: duplicate torrent skipped ----

    #[tokio::test]
    async fn load_resume_duplicate_skipped() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut settings = test_settings();
        settings.resume_data_dir = Some(tmp.path().to_path_buf());

        let session = SessionHandle::start(settings).await.unwrap();

        // Add a torrent first.
        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Wait for the torrent to settle.
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Save resume state so we have a file on disk.
        let _ = session.save_resume_state().await;

        // Load again — the torrent already exists so it should be skipped.
        let result = session.load_resume_state().await.unwrap();
        assert!(
            session.list_torrents().await.unwrap().contains(&info_hash),
            "original torrent should still exist"
        );
        assert_eq!(result.skipped, 1, "duplicate should be skipped");
        assert_eq!(result.failed, 0);

        session.shutdown().await.unwrap();
    }

    // ---- Test: reconstruct_torrent_meta with info present ----

    #[test]
    fn reconstruct_torrent_meta_returns_some_with_correct_fields() {
        use crate::resume_file::reconstruct_torrent_meta;
        use irontide_core::FastResumeData;

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;

        // Create resume data with a stored info dict.
        let info_bytes = irontide_bencode::to_bytes(&meta.info).unwrap();
        let mut rd = FastResumeData::new(
            info_hash.as_bytes().to_vec(),
            "test-torrent".into(),
            "/downloads".into(),
        );
        rd.info = Some(info_bytes);
        rd.trackers = vec![
            vec!["http://tracker1.example.com/announce".into()],
            vec!["http://tracker2.example.com/announce".into()],
        ];
        rd.url_seeds = vec!["http://seed.example.com/".into()];
        rd.http_seeds = vec!["http://httpseed.example.com/".into()];

        let reconstructed = reconstruct_torrent_meta(&rd).expect("should reconstruct");

        assert_eq!(reconstructed.info_hash, info_hash);
        assert_eq!(
            reconstructed.announce.as_deref(),
            Some("http://tracker1.example.com/announce")
        );
        assert!(reconstructed.announce_list.is_some());
        assert_eq!(reconstructed.announce_list.as_ref().unwrap().len(), 2);
        assert_eq!(
            reconstructed.url_list,
            vec!["http://seed.example.com/".to_string()]
        );
        assert_eq!(
            reconstructed.httpseeds,
            vec!["http://httpseed.example.com/".to_string()]
        );
        assert!(reconstructed.info_bytes.is_some());
        assert!(reconstructed.comment.is_none());
        assert!(reconstructed.created_by.is_none());
        assert!(reconstructed.creation_date.is_none());
    }

    // ---- Test: reconstruct_torrent_meta returns None for unresolved magnet ----

    #[test]
    fn reconstruct_torrent_meta_returns_none_without_info() {
        use crate::resume_file::reconstruct_torrent_meta;
        use irontide_core::FastResumeData;

        let rd = FastResumeData::new(vec![0xAB; 20], "magnet".into(), "/tmp".into());
        // info is None by default — simulates unresolved magnet.
        assert!(rd.info.is_none());
        assert!(reconstruct_torrent_meta(&rd).is_none());
    }

    // ---- Test: reconstruct_magnet returns Some ----

    #[test]
    fn reconstruct_magnet_returns_some_with_correct_fields() {
        use crate::resume_file::reconstruct_magnet;
        use irontide_core::FastResumeData;

        let mut rd = FastResumeData::new(vec![0xCC; 20], "my-torrent".into(), "/downloads".into());
        rd.trackers = vec![
            vec!["http://tracker1.com/announce".into()],
            vec![
                "http://tracker2.com/announce".into(),
                "http://tracker3.com/announce".into(),
            ],
        ];

        let magnet = reconstruct_magnet(&rd).expect("should reconstruct magnet");

        assert!(magnet.info_hashes.v1.is_some());
        assert!(magnet.info_hashes.v2.is_none());
        assert_eq!(magnet.display_name.as_deref(), Some("my-torrent"));
        // Trackers flattened: 3 total from 2 tiers.
        assert_eq!(magnet.trackers.len(), 3);
        assert!(magnet.peers.is_empty());
        assert!(magnet.selected_files.is_none());
    }

    // ---- Test: reconstruct_magnet with info_hash2 preserved ----

    #[test]
    fn reconstruct_magnet_preserves_info_hash2() {
        use crate::resume_file::reconstruct_magnet;
        use irontide_core::FastResumeData;

        let mut rd = FastResumeData::new(vec![0xDD; 20], "v2-magnet".into(), "/tmp".into());
        rd.info_hash2 = Some(vec![0xEE; 32]);

        let magnet = reconstruct_magnet(&rd).expect("should reconstruct");
        assert!(magnet.info_hashes.v1.is_some());
        assert!(magnet.info_hashes.v2.is_some());

        let v2 = magnet.info_hashes.v2.unwrap();
        assert_eq!(v2.as_bytes(), &[0xEE; 32]);
    }

    // ---- Test: reconstruct_magnet with empty name ----

    #[test]
    fn reconstruct_magnet_empty_name_is_none() {
        use crate::resume_file::reconstruct_magnet;
        use irontide_core::FastResumeData;

        let rd = FastResumeData::new(vec![0xFF; 20], String::new(), "/tmp".into());
        let magnet = reconstruct_magnet(&rd).expect("should reconstruct");
        assert!(
            magnet.display_name.is_none(),
            "empty name should map to None"
        );
    }

    // ==== M161 Phase 5: auto-save / auto-restore / orphan cleanup ====

    // ---- Test: shutdown writes resume files ----

    #[tokio::test]
    async fn shutdown_saves_resume_files() {
        let tmp = tempfile::TempDir::new().unwrap();
        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Force a state change to set the dirty flag: pause then resume.
        session.pause_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        session.resume_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let path = crate::resume_file::resume_file_path(tmp.path(), &info_hash);

        // Shutdown triggers save_dirty_resume_files internally.
        // SessionHandle::shutdown() is fire-and-forget, so we need to
        // wait briefly for the actor to finish writing to disk.
        session.shutdown().await.unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;

        assert!(path.exists(), "resume file should exist after shutdown");
    }

    // ---- Test: auto-restore on startup ----

    #[tokio::test]
    async fn auto_restore_on_startup() {
        let tmp = tempfile::TempDir::new().unwrap();

        let info_hash;
        {
            // First session: add a torrent, save, and shut down.
            let session = SessionHandle::start(resume_test_settings(tmp.path()))
                .await
                .unwrap();

            let data = vec![0xAB; 16384];
            let meta = make_test_torrent(&data, 16384);
            info_hash = meta.info_hash;
            let storage = make_storage(&data, 16384);
            session
                .add_torrent_with_meta(meta.into(), Some(storage))
                .await
                .unwrap();

            tokio::time::sleep(Duration::from_millis(50)).await;
            let _ = session.save_resume_state().await;
            session.shutdown().await.unwrap();
        }

        // Verify the resume file exists before starting a new session.
        let path = crate::resume_file::resume_file_path(tmp.path(), &info_hash);
        assert!(path.exists(), "resume file should exist before restart");

        {
            // Second session: should auto-restore the torrent on startup.
            let session = SessionHandle::start(resume_test_settings(tmp.path()))
                .await
                .unwrap();

            // Give the actor a moment to process the auto-restore.
            tokio::time::sleep(Duration::from_millis(100)).await;

            let list = session.list_torrents().await.unwrap();
            assert!(
                list.contains(&info_hash),
                "torrent should be auto-restored on startup"
            );

            session.shutdown().await.unwrap();
        }
    }

    // ---- Test: shutdown with read-only resume dir completes without error ----

    #[tokio::test]
    async fn shutdown_with_readonly_resume_dir_completes() {
        let tmp = tempfile::TempDir::new().unwrap();
        // Point resume_data_dir to a non-existent path under a read-only root.
        // On Linux, /proc is always read-only for directory creation.
        let readonly_dir = PathBuf::from("/proc/irontide-test-nonexistent");
        let mut settings = test_settings();
        settings.resume_data_dir = Some(readonly_dir);

        let session = SessionHandle::start(settings).await.unwrap();

        let data = vec![0xAB; 16384];
        let meta = make_test_torrent(&data, 16384);
        let storage = make_storage(&data, 16384);
        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        tokio::time::sleep(Duration::from_millis(50)).await;

        // Shutdown should complete without panic or error even though
        // the resume dir is not writable.
        session.shutdown().await.unwrap();

        // If we got here, the test passed — errors were logged, not propagated.
        drop(tmp);
    }

    // ---- Test: orphan resume file deleted on startup ----

    #[tokio::test]
    async fn orphan_resume_file_deleted_on_startup() {
        let tmp = tempfile::TempDir::new().unwrap();
        let torrents_dir = tmp.path().join("torrents");
        std::fs::create_dir_all(&torrents_dir).unwrap();

        // Write a fake .resume file that does not match any torrent.
        // Use valid bencode so it parses but with a hash that won't match
        // anything added to the session. The file must parse correctly for
        // the load to attempt adding it (which will fail or produce a torrent
        // with a mismatched hash that gets cleaned up as orphan).
        // Simplest: write garbage bencode — it will fail to deserialize,
        // not be added, and then orphan cleanup should remove it.
        let orphan_path = torrents_dir.join("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef.resume");
        std::fs::write(&orphan_path, b"not valid bencode").unwrap();
        assert!(orphan_path.exists(), "orphan file should exist before test");

        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        // Give the actor time to auto-restore + orphan cleanup.
        tokio::time::sleep(Duration::from_millis(100)).await;

        assert!(
            !orphan_path.exists(),
            "orphan resume file should be deleted on startup"
        );

        session.shutdown().await.unwrap();
    }

    // ==== M161 Phase 7: integration tests for resume file lifecycle ====

    // ---- Test: multi-torrent save-load round-trip ----
    //
    // Creates 3 torrents in session 1, saves resume state, verifies 3 `.resume`
    // files on disk. Starts session 2 with the same resume dir and verifies all
    // 3 torrents are restored via `load_resume_state()`.

    #[tokio::test]
    async fn multi_torrent_save_load_round_trip() {
        let tmp = tempfile::TempDir::new().unwrap();

        // Distinct data per torrent to produce unique info hashes.
        let datasets: [u8; 3] = [0xAA, 0xBB, 0xCC];
        let mut hashes = Vec::with_capacity(3);

        {
            // Session 1: add 3 torrents, save resume state.
            let session = SessionHandle::start(resume_test_settings(tmp.path()))
                .await
                .unwrap();

            for &byte in &datasets {
                let data = vec![byte; 16384];
                let meta = make_test_torrent(&data, 16384);
                let info_hash = meta.info_hash;
                let storage = make_storage(&data, 16384);
                session
                    .add_torrent_with_meta(meta.into(), Some(storage))
                    .await
                    .unwrap();
                hashes.push(info_hash);
            }

            // Let actors settle so dirty flags are set.
            tokio::time::sleep(Duration::from_millis(100)).await;

            let saved = session.save_resume_state().await.unwrap();
            assert_eq!(saved, 3, "all 3 torrents should be saved");

            // Verify .resume files exist on disk.
            let files = crate::resume_file::scan_resume_dir(tmp.path());
            assert_eq!(files.len(), 3, "3 .resume files should be on disk");

            for hash in &hashes {
                let path = crate::resume_file::resume_file_path(tmp.path(), hash);
                assert!(
                    path.exists(),
                    "resume file for {} should exist",
                    hex::encode(hash.as_bytes())
                );
            }

            session.shutdown().await.unwrap();
        }

        {
            // Session 2: fresh session with the same resume dir.
            // Disable auto-restore by starting first, then calling
            // load_resume_state manually.
            //
            // NOTE: the auto-restore runs during `start()` before we get the
            // handle back, so the torrents will already be loaded. Use
            // list_torrents to verify instead.
            let session = SessionHandle::start(resume_test_settings(tmp.path()))
                .await
                .unwrap();

            // Give the actor time to process auto-restore.
            tokio::time::sleep(Duration::from_millis(200)).await;

            let list = session.list_torrents().await.unwrap();
            assert_eq!(list.len(), 3, "all 3 torrents should be auto-restored");

            for hash in &hashes {
                assert!(
                    list.contains(hash),
                    "torrent {} should be present after restore",
                    hex::encode(hash.as_bytes())
                );
            }

            session.shutdown().await.unwrap();
        }
    }

    // ---- Test: corrupt 1 of 3 resume files → 2 restored + 1 failed ----
    //
    // Saves 3 torrents to resume files, corrupts one with garbage bytes,
    // then starts a fresh session and verifies that 2 are restored and 1 failed.

    #[tokio::test]
    async fn corrupt_one_of_three_resume_files() {
        let tmp = tempfile::TempDir::new().unwrap();

        let datasets: [u8; 3] = [0xDD, 0xEE, 0xFF];
        let mut hashes = Vec::with_capacity(3);

        {
            // Session 1: add 3 torrents, save resume state.
            let session = SessionHandle::start(resume_test_settings(tmp.path()))
                .await
                .unwrap();

            for &byte in &datasets {
                let data = vec![byte; 16384];
                let meta = make_test_torrent(&data, 16384);
                let info_hash = meta.info_hash;
                let storage = make_storage(&data, 16384);
                session
                    .add_torrent_with_meta(meta.into(), Some(storage))
                    .await
                    .unwrap();
                hashes.push(info_hash);
            }

            tokio::time::sleep(Duration::from_millis(100)).await;

            let saved = session.save_resume_state().await.unwrap();
            assert_eq!(saved, 3, "all 3 torrents should be saved");

            session.shutdown().await.unwrap();
        }

        // Corrupt the second resume file with garbage bytes.
        let corrupt_path = crate::resume_file::resume_file_path(tmp.path(), &hashes[1]);
        assert!(
            corrupt_path.exists(),
            "file to corrupt must exist before overwrite"
        );
        std::fs::write(&corrupt_path, b"CORRUPTED GARBAGE DATA 0xDEAD").unwrap();

        {
            // Session 2: auto-restore should recover 2, fail 1, and the
            // orphan cleanup should delete the corrupt file.
            let session = SessionHandle::start(resume_test_settings(tmp.path()))
                .await
                .unwrap();

            // Give actor time for auto-restore + orphan cleanup.
            tokio::time::sleep(Duration::from_millis(200)).await;

            let list = session.list_torrents().await.unwrap();
            assert_eq!(
                list.len(),
                2,
                "2 torrents should be restored (1 corrupt skipped)"
            );

            // The good hashes should be present.
            assert!(
                list.contains(&hashes[0]),
                "first torrent should be restored"
            );
            assert!(
                list.contains(&hashes[2]),
                "third torrent should be restored"
            );

            // The corrupt hash should NOT be present.
            assert!(
                !list.contains(&hashes[1]),
                "corrupted torrent should not be restored"
            );

            // Also verify the corrupt file was cleaned up as orphan.
            assert!(
                !corrupt_path.exists(),
                "corrupt resume file should be deleted by orphan cleanup"
            );

            session.shutdown().await.unwrap();
        }
    }

    // ---- Test: remove torrent → `.resume` file deleted from disk ----
    //
    // Adds a torrent, saves resume state (creates the `.resume` file), then
    // removes the torrent via `session.remove_torrent()`. The removal handler
    // eagerly deletes the `.resume` file so it is not orphaned.

    #[tokio::test]
    async fn remove_torrent_deletes_resume_file() {
        let tmp = tempfile::TempDir::new().unwrap();

        let data = vec![0x42; 16384];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;
        let storage = make_storage(&data, 16384);

        let session = SessionHandle::start(resume_test_settings(tmp.path()))
            .await
            .unwrap();

        session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Let the actor settle so the dirty flag is set.
        tokio::time::sleep(Duration::from_millis(100)).await;

        let saved = session.save_resume_state().await.unwrap();
        assert!(saved > 0, "torrent should be saved to a resume file");

        let resume_path = crate::resume_file::resume_file_path(tmp.path(), &info_hash);
        assert!(resume_path.exists(), "resume file should exist after save");

        // Remove the torrent — this should also delete the .resume file.
        session.remove_torrent(info_hash).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let list = session.list_torrents().await.unwrap();
        assert!(
            !list.contains(&info_hash),
            "torrent should be gone from session after removal"
        );

        assert!(
            !resume_path.exists(),
            "resume file should be deleted when torrent is removed"
        );

        // Verify no .resume files remain in the torrents directory.
        let remaining = crate::resume_file::scan_resume_dir(tmp.path());
        assert!(
            remaining.is_empty(),
            "no resume files should remain after removing the only torrent"
        );

        session.shutdown().await.unwrap();
    }

    // ── M170: session-level storage-path tests ─────────────────────────

    /// Test settings that use an isolated `resume_data_dir` so that
    /// auto-restore from a prior test run doesn't pollute `torrents`.
    /// Matches the precedent set by `test_settings_with_dht`.
    fn test_settings_isolated_resume(resume_dir: &std::path::Path) -> Settings {
        Settings {
            resume_data_dir: Some(resume_dir.to_path_buf()),
            ..test_settings()
        }
    }

    #[tokio::test]
    async fn remove_torrent_with_files_deletes_disk_files() {
        // Build a real on-disk torrent via FilesystemStorage, then call
        // remove_torrent_with_files. The files MUST be gone from disk
        // after the spawn_blocking walk completes.
        let download_dir = tempfile::tempdir().unwrap();
        let resume_dir = tempfile::tempdir().unwrap();
        let mut settings = test_settings_isolated_resume(resume_dir.path());
        settings.download_dir = download_dir.path().to_path_buf();
        let session = SessionHandle::start(settings).await.unwrap();

        let data = vec![0xAB_u8; 16384];
        let meta = make_test_torrent(&data, 16384);
        let lengths = Lengths::new(data.len() as u64, 16384, DEFAULT_CHUNK_SIZE);
        let storage: Arc<dyn TorrentStorage> = Arc::new(
            irontide_storage::FilesystemStorage::new(
                download_dir.path(),
                vec![PathBuf::from("test")],
                vec![data.len() as u64],
                lengths,
                None,
                irontide_storage::PreallocateMode::None,
                false,
            )
            .unwrap(),
        );

        // Write actual piece data so the file is non-empty and cannot
        // be mistaken for a sparse leftover.
        storage.write_chunk(0, 0, &data).unwrap();

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        let file_on_disk = download_dir.path().join("test");
        assert!(file_on_disk.exists(), "file should exist before delete");

        session.remove_torrent_with_files(info_hash).await.unwrap();

        // The spawn_blocking task is fire-and-forget; poll briefly.
        for _ in 0..20 {
            if !file_on_disk.exists() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        assert!(
            !file_on_disk.exists(),
            "file should have been removed from disk"
        );
        assert!(
            download_dir.path().exists(),
            "download_dir root must never be removed"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn remove_torrent_with_files_tolerates_already_deleted_files() {
        // Partial-failure semantics: the user removed files out-of-band
        // before the session got the deleteFiles command. The call must
        // still succeed (always returns Ok).
        let download_dir = tempfile::tempdir().unwrap();
        let resume_dir = tempfile::tempdir().unwrap();
        let mut settings = test_settings_isolated_resume(resume_dir.path());
        settings.download_dir = download_dir.path().to_path_buf();
        let session = SessionHandle::start(settings).await.unwrap();

        let data = vec![0xCD_u8; 16384];
        let meta = make_test_torrent(&data, 16384);
        let lengths = Lengths::new(data.len() as u64, 16384, DEFAULT_CHUNK_SIZE);
        let storage: Arc<dyn TorrentStorage> = Arc::new(
            irontide_storage::FilesystemStorage::new(
                download_dir.path(),
                vec![PathBuf::from("test")],
                vec![data.len() as u64],
                lengths,
                None,
                irontide_storage::PreallocateMode::None,
                false,
            )
            .unwrap(),
        );
        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Manually delete the file before calling remove_torrent_with_files.
        std::fs::remove_file(download_dir.path().join("test")).unwrap();

        // Must still succeed.
        let result = session.remove_torrent_with_files(info_hash).await;
        assert!(
            result.is_ok(),
            "remove_torrent_with_files must return Ok on missing files"
        );

        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn remove_torrent_with_files_grace_guards_fast_re_add() {
        // Fast re-add during an in-flight delete must 409 until the
        // deletion grace window closes. Because the delete is fire-and-
        // forget, we simulate by calling remove_torrent_with_files and
        // then immediately re-adding the same info hash via
        // add_torrent(AddTorrentParams::bytes(...)).  The grace set is
        // populated synchronously inside the actor so the re-add sees it.
        use serde::Serialize;

        #[derive(Serialize)]
        struct Info<'a> {
            length: u64,
            name: &'a str,
            #[serde(rename = "piece length")]
            piece_length: u64,
            #[serde(with = "serde_bytes")]
            pieces: &'a [u8],
        }
        #[derive(Serialize)]
        struct Torrent<'a> {
            info: Info<'a>,
        }

        let download_dir = tempfile::tempdir().unwrap();
        let resume_dir = tempfile::tempdir().unwrap();
        let mut settings = test_settings_isolated_resume(resume_dir.path());
        settings.download_dir = download_dir.path().to_path_buf();
        let session = SessionHandle::start(settings).await.unwrap();

        // Build + serialize a single-file torrent so we can re-add via
        // bytes after deleting.
        let data = vec![0xEE_u8; 16384];
        let meta = make_test_torrent(&data, 16384);
        let lengths = Lengths::new(data.len() as u64, 16384, DEFAULT_CHUNK_SIZE);
        let storage: Arc<dyn TorrentStorage> = Arc::new(
            irontide_storage::FilesystemStorage::new(
                download_dir.path(),
                vec![PathBuf::from("test")],
                vec![data.len() as u64],
                lengths,
                None,
                irontide_storage::PreallocateMode::None,
                false,
            )
            .unwrap(),
        );
        // Re-serialise the TorrentMetaV1 so we can feed the bytes back
        // through AddTorrentParams::bytes.
        let mut pieces = Vec::new();
        let hash = irontide_core::sha1(&data);
        pieces.extend_from_slice(hash.as_bytes());
        let bytes = irontide_bencode::to_bytes(&Torrent {
            info: Info {
                length: data.len() as u64,
                name: "test",
                piece_length: 16384,
                pieces: &pieces,
            },
        })
        .unwrap();

        let info_hash = session
            .add_torrent_with_meta(meta.into(), Some(storage))
            .await
            .unwrap();

        // Kick off the delete — the deletion_grace set is populated
        // inside the actor before we return.
        session.remove_torrent_with_files(info_hash).await.unwrap();

        // Immediately try to re-add. The grace window may still be
        // open; if it is, we expect 409/CategoryBeingRemoved. If the
        // spawn_blocking happened to finish first, we expect success.
        // Either way the system must NOT panic or leak a half-deleted
        // torrent.
        let params = AddTorrentParams::bytes(bytes);
        let result = session.add_torrent(params).await;
        match result {
            Ok(_) => {
                // grace window closed before the re-add — fine.
            }
            Err(crate::Error::TorrentBeingRemoved(h)) => {
                assert_eq!(h, info_hash, "grace error must name the same hash");
            }
            Err(e) => panic!("unexpected error on re-add: {e}"),
        }

        session.shutdown().await.unwrap();
    }

    // ---- v0.173.2 T2: synchronous debug_inject_metadata ----

    /// Synthesise a v1 info dict and its SHA-1 info hash. Returns
    /// `(info_bytes, info_hash)` where `info_bytes` is the bencoded info
    /// dict alone (not the outer .torrent wrapper) and `info_hash` is the
    /// SHA-1 of those bytes.
    ///
    /// The injected info hash MUST match the magnet URI's info hash, so
    /// this helper owns that invariant: hash exactly the bytes that will
    /// later be injected.
    #[cfg(feature = "test-util")]
    fn make_debug_inject_info() -> (Vec<u8>, Id20) {
        use serde::Serialize;

        #[derive(Serialize)]
        struct Info<'a> {
            length: u64,
            name: &'a str,
            #[serde(rename = "piece length")]
            piece_length: u64,
            #[serde(with = "serde_bytes")]
            pieces: &'a [u8],
        }

        let data = vec![0xAB_u8; 1024];
        let piece_hash = irontide_core::sha1(&data);
        let mut pieces = Vec::new();
        pieces.extend_from_slice(piece_hash.as_bytes());

        let info = Info {
            length: data.len() as u64,
            name: "sync-inject-test",
            piece_length: 1024,
            pieces: &pieces,
        };

        let info_bytes = irontide_bencode::to_bytes(&info).unwrap();
        let info_hash = irontide_core::sha1(&info_bytes);
        (info_bytes, info_hash)
    }

    #[cfg(feature = "test-util")]
    #[tokio::test]
    async fn debug_inject_metadata_resolves_magnet_meta_synchronously() {
        use crate::session::AddTorrentParams;

        let (info_bytes, info_hash) = make_debug_inject_info();

        // Isolate resume dir — magnet adds persist .resume files; without
        // isolation, parallel tests and re-runs pollute one another. See
        // feedback_irontide_resume_test_isolation memory entry.
        let resume_dir = tempfile::tempdir().unwrap();
        let session = SessionHandle::start(test_settings_isolated_resume(resume_dir.path()))
            .await
            .unwrap();

        let magnet_uri = format!(
            "magnet:?xt=urn:btih:{}&dn=sync-inject-test",
            info_hash.to_hex()
        );
        let added = session
            .add_torrent(AddTorrentParams::magnet(magnet_uri))
            .await
            .unwrap();
        assert_eq!(
            added, info_hash,
            "magnet info hash must equal synth info hash"
        );

        // The synchronous contract: when `debug_inject_metadata` returns
        // Ok, the metadata must already be visible via `torrent_file` — no
        // polling, no sleep. This is what distinguishes it from the M147
        // fire-and-forget path.
        session
            .debug_inject_metadata(info_hash, info_bytes)
            .await
            .expect("debug_inject_metadata must succeed");

        let meta = session
            .torrent_file(info_hash)
            .await
            .expect("torrent_file call")
            .expect("metadata must be present immediately after sync inject");
        assert_eq!(meta.info_hash, info_hash);

        session.shutdown().await.unwrap();
    }

    #[cfg(feature = "test-util")]
    #[tokio::test]
    async fn debug_inject_metadata_returns_torrent_not_found_for_unknown_hash() {
        let resume_dir = tempfile::tempdir().unwrap();
        let session = SessionHandle::start(test_settings_isolated_resume(resume_dir.path()))
            .await
            .unwrap();

        let bogus = Id20::from_hex("ffffffffffffffffffffffffffffffffffffffff").unwrap();
        let result = session.debug_inject_metadata(bogus, vec![]).await;
        assert!(
            matches!(result, Err(crate::Error::TorrentNotFound(_))),
            "expected TorrentNotFound for unknown hash; got {result:?}"
        );

        session.shutdown().await.unwrap();
    }

    // ---- v0.173.2 T7: A11 ssl_cert metadata propagation regression ----

    /// Synthesise a v1 info dict with optional `private` and `ssl-cert`
    /// fields. Unlike [`make_debug_inject_info`], this helper exists
    /// specifically to exercise the BEP 35 `ssl-cert` propagation path
    /// from the bencoded info dict into `TorrentMetaV1::info.ssl_cert`
    /// after synchronous metadata injection (T2's `debug_inject_metadata`).
    ///
    /// The bencode key name is `ssl-cert` (with hyphen) per BEP 35; serde
    /// renames it on the synthesised `Info` struct below so the emitted
    /// bytes match `InfoDict`'s deserialiser exactly.
    ///
    /// The caller hashes the returned bytes directly to compute the info
    /// hash — the returned bytes are the info dict alone (no wrapper).
    #[cfg(feature = "test-util")]
    fn build_synth_info_bytes_with_options(
        name: &str,
        length_bytes: u64,
        piece_length: u64,
        private: Option<i64>,
        ssl_cert: Option<Vec<u8>>,
    ) -> Vec<u8> {
        use serde::Serialize;

        #[derive(Serialize)]
        struct Info {
            length: u64,
            name: String,
            #[serde(rename = "piece length")]
            piece_length: u64,
            pieces: serde_bytes::ByteBuf,
            #[serde(skip_serializing_if = "Option::is_none")]
            private: Option<i64>,
            #[serde(rename = "ssl-cert", skip_serializing_if = "Option::is_none")]
            ssl_cert: Option<serde_bytes::ByteBuf>,
        }

        // pieces = SHA-1 of an all-zero piece, repeated. The injected data
        // is never verified against disk during these tests — we only care
        // that the bencoded info dict round-trips through the session's
        // metadata-resolution path with ssl_cert intact.
        let num_pieces = length_bytes.div_ceil(piece_length);
        let zero_piece_hash = irontide_core::sha1(&vec![0_u8; piece_length as usize]);
        let mut pieces = Vec::with_capacity(20 * num_pieces as usize);
        for _ in 0..num_pieces {
            pieces.extend_from_slice(zero_piece_hash.as_bytes());
        }

        let info = Info {
            length: length_bytes,
            name: name.to_owned(),
            piece_length,
            pieces: serde_bytes::ByteBuf::from(pieces),
            private,
            ssl_cert: ssl_cert.map(serde_bytes::ByteBuf::from),
        };
        irontide_bencode::to_bytes(&info).expect("bencode synth info dict")
    }

    #[cfg(feature = "test-util")]
    #[tokio::test]
    async fn ssl_cert_propagates_to_meta_after_inject() {
        use crate::session::AddTorrentParams;

        let resume_dir = tempfile::tempdir().unwrap();
        let session = SessionHandle::start(test_settings_isolated_resume(resume_dir.path()))
            .await
            .unwrap();

        let cert_pem = b"-----BEGIN CERT-----\nfake\n-----END CERT-----\n".to_vec();
        let info_bytes = build_synth_info_bytes_with_options(
            "ssl-fixture",
            16_384,
            16_384,
            None,
            Some(cert_pem.clone()),
        );
        let info_hash = irontide_core::sha1(&info_bytes);

        let magnet = format!("magnet:?xt=urn:btih:{}&dn=ssl-fixture", info_hash.to_hex());
        let added = session
            .add_torrent(AddTorrentParams::magnet(magnet))
            .await
            .unwrap();
        assert_eq!(
            added, info_hash,
            "magnet info hash must equal synth info hash"
        );

        session
            .debug_inject_metadata(info_hash, info_bytes)
            .await
            .expect("debug_inject_metadata must succeed");

        let meta = session
            .torrent_file(info_hash)
            .await
            .expect("torrent_file Ok")
            .expect("metadata must be present immediately after sync inject");
        assert_eq!(
            meta.info.ssl_cert.as_ref(),
            Some(&cert_pem),
            "ssl_cert from synth info dict must propagate to meta.info.ssl_cert"
        );

        session.shutdown().await.unwrap();
    }

    #[cfg(feature = "test-util")]
    #[tokio::test]
    async fn ssl_cert_absent_remains_none_in_meta_after_inject() {
        use crate::session::AddTorrentParams;

        let resume_dir = tempfile::tempdir().unwrap();
        let session = SessionHandle::start(test_settings_isolated_resume(resume_dir.path()))
            .await
            .unwrap();

        let info_bytes =
            build_synth_info_bytes_with_options("no-ssl-fixture", 16_384, 16_384, None, None);
        let info_hash = irontide_core::sha1(&info_bytes);

        let magnet = format!(
            "magnet:?xt=urn:btih:{}&dn=no-ssl-fixture",
            info_hash.to_hex()
        );
        let added = session
            .add_torrent(AddTorrentParams::magnet(magnet))
            .await
            .unwrap();
        assert_eq!(
            added, info_hash,
            "magnet info hash must equal synth info hash"
        );

        session
            .debug_inject_metadata(info_hash, info_bytes)
            .await
            .expect("debug_inject_metadata must succeed");

        let meta = session
            .torrent_file(info_hash)
            .await
            .expect("torrent_file Ok")
            .expect("metadata must be present immediately after sync inject");
        assert!(
            meta.info.ssl_cert.is_none(),
            "absent ssl-cert in info dict must remain None in meta; got {:?}",
            meta.info.ssl_cert
        );

        session.shutdown().await.unwrap();
    }

    // ---- P2C4: Startup init throttle tests ----

    #[tokio::test]
    async fn init_throttle_queues_restored_torrents() {
        let tmp = tempfile::TempDir::new().unwrap();
        let resume_dir = tmp.path().to_path_buf();

        // Phase 1: create a session, add 5 torrents, save resume data.
        {
            let mut settings = resume_test_settings(&resume_dir);
            settings.queueing_enabled = false;
            let session = SessionHandle::start(settings).await.unwrap();
            for i in 0u8..5 {
                let data = vec![i.wrapping_add(0xA0); 16384];
                let meta = make_test_torrent(&data, 16384);
                let storage = make_storage(&data, 16384);
                session
                    .add_torrent_with_meta(meta.into(), Some(storage))
                    .await
                    .unwrap();
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
            let saved = session.save_resume_state().await.unwrap();
            assert!(saved >= 3, "should save most resume files, got {saved}");
            session.shutdown().await.unwrap();
        }

        // Phase 2: restart with queueing_enabled and active_checking=2.
        {
            let mut settings = resume_test_settings(&resume_dir);
            settings.queueing_enabled = true;
            settings.active_checking = 2;
            settings.active_downloads = 2;
            settings.active_seeds = 2;
            settings.active_limit = 4;
            let session = SessionHandle::start(settings).await.unwrap();
            tokio::time::sleep(Duration::from_millis(200)).await;

            let list = session.list_torrent_summaries().await.unwrap();
            let queued = list
                .iter()
                .filter(|t| t.state == TorrentState::Queued)
                .count();
            let active = list
                .iter()
                .filter(|t| t.state != TorrentState::Queued)
                .count();

            assert!(
                queued > 0,
                "at least one torrent should be Queued, but all {active} are active"
            );
            assert!(
                active <= 4,
                "active torrents ({active}) should not exceed active_limit (4)"
            );
            session.shutdown().await.unwrap();
        }
    }

    #[tokio::test]
    async fn init_throttle_disabled_restores_all_immediately() {
        let tmp = tempfile::TempDir::new().unwrap();
        let resume_dir = tmp.path().to_path_buf();

        // Phase 1: add torrents, save resume.
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            for i in 0u8..3 {
                let data = vec![i.wrapping_add(0xC0); 16384];
                let meta = make_test_torrent(&data, 16384);
                let storage = make_storage(&data, 16384);
                session
                    .add_torrent_with_meta(meta.into(), Some(storage))
                    .await
                    .unwrap();
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
            session.save_resume_state().await.unwrap();
            session.shutdown().await.unwrap();
        }

        // Phase 2: restart with queueing DISABLED.
        {
            let mut settings = resume_test_settings(&resume_dir);
            settings.queueing_enabled = false;
            let session = SessionHandle::start(settings).await.unwrap();
            tokio::time::sleep(Duration::from_millis(200)).await;

            let list = session.list_torrent_summaries().await.unwrap();
            let queued = list
                .iter()
                .filter(|t| t.state == TorrentState::Queued)
                .count();
            assert_eq!(
                queued, 0,
                "with queueing disabled, no torrents should be Queued"
            );
            session.shutdown().await.unwrap();
        }
    }

    #[tokio::test]
    async fn checking_complete_triggers_immediate_eval() {
        use crate::alert::AlertKind;

        let mut settings = test_settings();
        settings.queueing_enabled = true;
        settings.active_checking = 1;
        settings.active_downloads = 5;
        settings.active_seeds = 5;
        settings.active_limit = 10;
        settings.auto_manage_interval = 300;
        let session = SessionHandle::start(settings).await.unwrap();
        let mut alerts = session.subscribe();

        // Add 3 small torrents with correct data so checking completes.
        let mut hashes = Vec::new();
        for i in 0u8..3 {
            let data = vec![i.wrapping_add(0xD0); 16384];
            let meta = make_test_torrent(&data, 16384);
            let storage = make_storage(&data, 16384);
            let h = session
                .add_torrent_with_meta(meta.into(), Some(storage))
                .await
                .unwrap();
            hashes.push(h);
        }

        // Wait for at least one checking-complete state change. The trigger
        // should cause evaluate_queue to promote the next candidate without
        // waiting for the 300s auto_manage_interval.
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        let mut saw_checking_transition = false;
        while tokio::time::Instant::now() < deadline {
            if let Ok(Ok(alert)) =
                tokio::time::timeout(Duration::from_millis(500), alerts.recv()).await
                && matches!(
                    alert.kind,
                    AlertKind::StateChanged {
                        prev_state: TorrentState::Checking,
                        ..
                    }
                )
            {
                saw_checking_transition = true;
                break;
            }
        }

        assert!(
            saw_checking_transition,
            "should have seen a Checking→* state transition"
        );

        // After the checking-complete trigger, the evaluator should have
        // promoted another torrent. Give a moment for the evaluate_queue
        // triggered by the alert arm to run.
        tokio::time::sleep(Duration::from_millis(200)).await;

        let list = session.list_torrent_summaries().await.unwrap();
        let active = list
            .iter()
            .filter(|t| t.state != TorrentState::Queued)
            .count();
        assert!(
            active >= 1,
            "at least one torrent should be active after checking-complete trigger"
        );

        session.shutdown().await.unwrap();
    }

    // ---- P2C5: Restore queue position from resume data tests ----

    #[tokio::test]
    async fn resume_restores_queue_position() {
        let tmp = tempfile::TempDir::new().unwrap();
        let resume_dir = tmp.path().to_path_buf();

        let data = vec![0xF0; 16384];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;

        // Phase 1: add torrent, set queue position, save resume.
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            let storage = make_storage(&data, 16384);
            session
                .add_torrent_with_meta(meta.clone().into(), Some(storage))
                .await
                .unwrap();
            session.set_queue_position(info_hash, 3).await.unwrap();
            tokio::time::sleep(Duration::from_millis(100)).await;
            session.save_resume_state().await.unwrap();
            session.shutdown().await.unwrap();
        }

        // Phase 2: restart and verify position survived.
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            tokio::time::sleep(Duration::from_millis(200)).await;

            let pos = session.queue_position(info_hash).await.unwrap();
            // Renormalization reassigns 0..N-1; with a single torrent
            // the position is 0 regardless of saved value.
            assert_eq!(pos, 0, "single torrent renormalizes to position 0");
            session.shutdown().await.unwrap();
        }
    }

    #[tokio::test]
    async fn resume_restores_auto_managed_false() {
        let tmp = tempfile::TempDir::new().unwrap();
        let resume_dir = tmp.path().to_path_buf();

        let data = vec![0xF1; 16384];
        let meta = make_test_torrent(&data, 16384);
        let info_hash = meta.info_hash;

        // Phase 1: add torrent, disable auto-manage, save resume.
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            let storage = make_storage(&data, 16384);
            session
                .add_torrent_with_meta(meta.clone().into(), Some(storage))
                .await
                .unwrap();
            // Currently there's no direct API to set auto_managed on
            // SessionHandle — it's internal to TorrentEntry. Verify that
            // the resume round-trip preserves the default (true → 1).
            tokio::time::sleep(Duration::from_millis(100)).await;
            session.save_resume_state().await.unwrap();
            session.shutdown().await.unwrap();
        }

        // Manually patch the resume file to set auto_managed=0.
        {
            let path = crate::resume_file::resume_file_path(&resume_dir, &info_hash);
            if path.exists() {
                let bytes = std::fs::read(&path).unwrap();
                let mut rd = crate::resume_file::deserialize_resume(&bytes).unwrap();
                rd.auto_managed = 0;
                let patched = crate::resume_file::serialize_resume(&rd).unwrap();
                std::fs::write(&path, patched).unwrap();
            }
        }

        // Phase 2: restart and verify auto_managed was restored as false.
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            tokio::time::sleep(Duration::from_millis(200)).await;

            let stats = session.torrent_stats(info_hash).await.unwrap();
            assert!(
                !stats.auto_managed,
                "auto_managed should be false after restore"
            );
            session.shutdown().await.unwrap();
        }
    }

    #[tokio::test]
    async fn resume_renormalizes_duplicate_positions() {
        let tmp = tempfile::TempDir::new().unwrap();
        let resume_dir = tmp.path().to_path_buf();

        // Phase 1: add 3 torrents, save resume.
        let mut hashes = Vec::new();
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            for i in 0u8..3 {
                let data = vec![i.wrapping_add(0xE0); 16384];
                let meta = make_test_torrent(&data, 16384);
                let storage = make_storage(&data, 16384);
                let h = session
                    .add_torrent_with_meta(meta.into(), Some(storage))
                    .await
                    .unwrap();
                hashes.push(h);
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
            session.save_resume_state().await.unwrap();
            session.shutdown().await.unwrap();
        }

        // Manually patch ALL resume files to have queue_position=0.
        for hash in &hashes {
            let path = crate::resume_file::resume_file_path(&resume_dir, hash);
            if path.exists() {
                let bytes = std::fs::read(&path).unwrap();
                let mut rd = crate::resume_file::deserialize_resume(&bytes).unwrap();
                rd.queue_position = 0;
                let patched = crate::resume_file::serialize_resume(&rd).unwrap();
                std::fs::write(&path, patched).unwrap();
            }
        }

        // Phase 2: restart and verify positions are contiguous 0,1,2.
        {
            let settings = resume_test_settings(&resume_dir);
            let session = SessionHandle::start(settings).await.unwrap();
            tokio::time::sleep(Duration::from_millis(200)).await;

            let mut positions = Vec::new();
            for hash in &hashes {
                if let Ok(pos) = session.queue_position(*hash).await {
                    positions.push(pos);
                }
            }
            positions.sort_unstable();
            let expected: Vec<i32> = (0..positions.len() as i32).collect();
            assert_eq!(
                positions, expected,
                "positions should be contiguous 0..N-1 after renormalization"
            );
            session.shutdown().await.unwrap();
        }
    }

    // ---- P2C6: EWMA rate smoothing tests ----

    #[test]
    fn ewma_smooths_transient_drop() {
        let alpha = 0.3_f64;
        let prev = 100_000.0_f64;
        let sample = 0.0_f64;
        let smoothed = alpha.mul_add(sample, (1.0 - alpha) * prev);
        assert!(
            (smoothed - 70_000.0).abs() < 1.0,
            "smoothed rate should be ~70000, got {smoothed}"
        );
    }

    #[test]
    fn ewma_alpha_one_equals_raw() {
        let alpha = 1.0_f64;
        let prev = 100_000.0_f64;
        let sample = 42_000.0_f64;
        let smoothed = alpha.mul_add(sample, (1.0 - alpha) * prev);
        assert!(
            (smoothed - sample).abs() < 0.001,
            "alpha=1.0 should produce raw rate, got {smoothed}"
        );
    }

    // ---- P2C7: Configurable seed anti-flap duration tests ----

    #[test]
    fn seed_anti_flap_uses_longer_duration() {
        let seed_queue_min_active_secs = 1800_u64;
        let auto_manage_startup = 60_u64;
        let started_5_min_ago = std::time::Duration::from_mins(5);
        let seed_duration = std::time::Duration::from_secs(seed_queue_min_active_secs);

        // Seeding torrent started 5 min ago: still recently_started
        // with seed_queue_min_active_secs=1800.
        assert!(
            started_5_min_ago < seed_duration,
            "5 min < 30 min, seeding torrent should be recently_started"
        );

        // Downloading torrent started 5 min ago: NOT recently_started
        // with auto_manage_startup=60.
        let dl_duration = std::time::Duration::from_secs(auto_manage_startup);
        assert!(
            started_5_min_ago > dl_duration,
            "5 min > 60s, downloading torrent should NOT be recently_started"
        );
    }

    #[test]
    fn download_anti_flap_uses_startup_duration() {
        let auto_manage_startup = 60_u64;
        let started_5_min_ago = std::time::Duration::from_mins(5);
        let dl_duration = std::time::Duration::from_secs(auto_manage_startup);
        assert!(
            started_5_min_ago > dl_duration,
            "downloading torrent started 5 min ago should NOT be recently_started"
        );
    }

    // ── M214: classify round-trip for Connection + Speed fields ──────

    #[test]
    fn classify_restart_required_upnp_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.enable_upnp = !old.enable_upnp;
        assert_eq!(classify_immediate(&old, &new), Vec::<&str>::new());
        assert_eq!(classify_restart_required(&old, &new), vec!["upnp"]);
    }

    #[test]
    fn classify_restart_required_natpmp_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.enable_natpmp = !old.enable_natpmp;
        assert_eq!(classify_immediate(&old, &new), Vec::<&str>::new());
        assert_eq!(classify_restart_required(&old, &new), vec!["natpmp"]);
    }

    #[test]
    fn classify_immediate_max_connec_global_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.max_connections_global = if old.max_connections_global == 500 {
            501
        } else {
            500
        };
        assert_eq!(classify_immediate(&old, &new), vec!["max_connec_global"]);
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_immediate_max_uploads_per_torrent_change() {
        // M224: per-torrent upload slot cap is classified immediate; the
        // choker reads the new cap at its next unchoke tick. Mirrors the
        // max_connec_global pattern from M214.
        let old = Settings::default();
        let mut new = old.clone();
        new.max_uploads_per_torrent = 4;
        assert_eq!(
            classify_immediate(&old, &new),
            vec!["max_uploads_per_torrent"]
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_restart_required_proxy_type_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.proxy.proxy_type = crate::proxy::ProxyType::Socks5;
        assert_eq!(classify_immediate(&old, &new), Vec::<&str>::new());
        assert_eq!(classify_restart_required(&old, &new), vec!["proxy_type"]);
    }

    #[test]
    fn classify_restart_required_proxy_credentials_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.proxy.username = Some("alice".into());
        new.proxy.password = Some("secret".into());
        assert_eq!(classify_immediate(&old, &new), Vec::<&str>::new());
        let restart = classify_restart_required(&old, &new);
        // Both fields must surface; order is implementation-defined but the
        // set must equal {proxy_username, proxy_password}.
        let set: std::collections::HashSet<&str> = restart.iter().copied().collect();
        assert_eq!(
            set,
            ["proxy_username", "proxy_password"]
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
        );
    }

    #[test]
    fn classify_combined_immediate_and_restart() {
        // Multi-field diff: max_connec_global + max_uploads_per_torrent
        // (both immediate) + upnp + proxy_type (both restart) should populate
        // both lists. M224 extends the immediate side.
        let old = Settings::default();
        let mut new = old.clone();
        new.max_connections_global = old.max_connections_global + 1;
        new.max_uploads_per_torrent = 4;
        new.enable_upnp = !old.enable_upnp;
        new.proxy.proxy_type = crate::proxy::ProxyType::Http;

        let immediate = classify_immediate(&old, &new);
        let imm_set: std::collections::HashSet<&str> = immediate.iter().copied().collect();
        assert_eq!(
            imm_set,
            ["max_connec_global", "max_uploads_per_torrent"]
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
        );
        let restart = classify_restart_required(&old, &new);
        let set: std::collections::HashSet<&str> = restart.iter().copied().collect();
        assert_eq!(
            set,
            ["upnp", "proxy_type"]
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
        );
    }

    // ── M215: BitTorrent + Advanced classify-list verification ──────

    #[test]
    fn classify_immediate_seed_time_limit_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.seed_time_limit_secs = Some(3600);
        assert_eq!(classify_immediate(&old, &new), vec!["max_seeding_time"]);
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_immediate_inactive_seed_time_limit_change() {
        let old = Settings::default();
        let mut new = old.clone();
        new.inactive_seed_time_limit_secs = Some(1800);
        assert_eq!(
            classify_immediate(&old, &new),
            vec!["max_inactive_seeding_time"]
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    // M225: `classify_restart_required_hashing_threads_change` and
    // `classify_restart_required_save_resume_interval_change` (formerly here)
    // were DELETED in M225 — those fields are now `classify_immediate` per
    // OV F2c / F4. Replacement immediate-dispatch coverage follows.

    #[test]
    fn classify_immediate_save_resume_interval_change() {
        // M225 Step 1: save_resume_interval graduated from restart_required
        // to immediate. SessionActor rebuilds the resume_save_interval timer
        // via Arc<Notify> on dispatch — no daemon restart needed.
        let old = Settings::default();
        let mut new = old.clone();
        new.save_resume_interval_secs = old.save_resume_interval_secs.saturating_add(60);
        assert_eq!(
            classify_immediate(&old, &new),
            vec!["save_resume_interval"]
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_immediate_hashing_threads_change() {
        // M225 Step 2: hashing_threads graduated from restart_required to
        // immediate. The per-torrent piece-verify batch reads
        // self.config.hashing_threads at the start of each batch, so a value
        // change applies on the NEXT batch via the existing
        // TorrentCommand::UpdateSettings(SettingsDelta) fan-out path.
        let old = Settings::default();
        let mut new = old.clone();
        new.hashing_threads = old.hashing_threads.saturating_add(2);
        assert_eq!(classify_immediate(&old, &new), vec!["hashing_threads"]);
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_immediate_ip_filter_enabled_change() {
        // M225 Step 3: ip_filter_enabled graduated to immediate. apply_settings
        // writes through Arc<RwLock<IpFilter>> with self.ip_filter.write().enabled
        // = enabled; future is_blocked calls observe the new value on the next
        // RwLock read.
        let old = Settings::default();
        let mut new = old.clone();
        new.ip_filter_enabled = !old.ip_filter_enabled;
        assert_eq!(
            classify_immediate(&old, &new),
            vec!["ip_filter_enabled"]
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn settings_delta_from_diff_includes_save_resume_interval() {
        // M225 Step 1: SettingsDelta carries save_resume_interval_secs so
        // apply_settings can dispatch the Notify on observed change.
        use crate::types::SettingsDelta;
        let old = Settings::default();
        let mut new = old.clone();
        new.save_resume_interval_secs = old.save_resume_interval_secs.saturating_add(30);
        let d = SettingsDelta::from_diff(&old, &new);
        assert_eq!(d.save_resume_interval_secs, Some(new.save_resume_interval_secs));
        assert!(d.hashing_threads.is_none());
        assert!(d.ip_filter_enabled.is_none());
        assert!(!d.is_empty());
    }

    #[test]
    fn settings_delta_from_diff_includes_hashing_threads() {
        // M225 Step 2: SettingsDelta carries hashing_threads so the existing
        // TorrentCommand::UpdateSettings fan-out propagates per-torrent.
        use crate::types::SettingsDelta;
        let old = Settings::default();
        let mut new = old.clone();
        new.hashing_threads = old.hashing_threads.saturating_add(1);
        let d = SettingsDelta::from_diff(&old, &new);
        assert_eq!(d.hashing_threads, Some(new.hashing_threads));
        assert!(d.save_resume_interval_secs.is_none());
        assert!(d.ip_filter_enabled.is_none());
        assert!(!d.is_empty());
    }

    #[test]
    fn settings_delta_from_diff_includes_ip_filter_enabled() {
        // M225 Step 3: SettingsDelta carries ip_filter_enabled. apply_settings
        // applies it through the outer Arc<RwLock<IpFilter>> write-lock.
        use crate::types::SettingsDelta;
        let old = Settings::default();
        let mut new = old.clone();
        new.ip_filter_enabled = !old.ip_filter_enabled;
        let d = SettingsDelta::from_diff(&old, &new);
        assert_eq!(d.ip_filter_enabled, Some(new.ip_filter_enabled));
        assert!(d.save_resume_interval_secs.is_none());
        assert!(d.hashing_threads.is_none());
        assert!(!d.is_empty());
    }

    #[test]
    fn settings_delta_is_empty_honours_m225_fields() {
        // M225: is_empty must return false when any M225 field is set so the
        // fan-out path runs.
        use crate::types::SettingsDelta;
        let mut d = SettingsDelta::default();
        assert!(d.is_empty());
        d.save_resume_interval_secs = Some(120);
        assert!(!d.is_empty());
        d = SettingsDelta::default();
        d.hashing_threads = Some(8);
        assert!(!d.is_empty());
        d = SettingsDelta::default();
        d.ip_filter_enabled = Some(false);
        assert!(!d.is_empty());
    }

    // ── M226: SettingsDelta + classify_immediate coverage ──────────────────

    /// Helper for compact M226 delta+classify tests: toggle one field, verify
    /// the delta picks it up AND [`classify_immediate`] yields the expected
    /// alias AND [`classify_restart_required`] stays empty.
    fn m226_delta_and_classify_check<F>(mutate: F, alias: &'static str)
    where
        F: FnOnce(&mut Settings),
    {
        use crate::types::SettingsDelta;
        let old = Settings::default();
        let mut new = old.clone();
        mutate(&mut new);
        let d = SettingsDelta::from_diff(&old, &new);
        assert!(!d.is_empty(), "{alias}: delta must not be empty after toggle");
        let imm = classify_immediate(&old, &new);
        assert!(
            imm.contains(&alias),
            "{alias}: classify_immediate must contain alias, got {imm:?}"
        );
        let rr = classify_restart_required(&old, &new);
        assert!(
            !rr.contains(&alias),
            "{alias}: must NOT appear in classify_restart_required"
        );
    }

    #[test]
    fn m226_notify_on_complete_immediate() {
        m226_delta_and_classify_check(|s| s.notify_on_complete = true, "notify_on_complete");
    }

    #[test]
    fn m226_notify_on_error_immediate() {
        m226_delta_and_classify_check(|s| s.notify_on_error = true, "notify_on_error");
    }

    #[test]
    fn m226_on_complete_program_immediate() {
        m226_delta_and_classify_check(
            |s| s.on_complete_program = Some(std::path::PathBuf::from("/usr/local/bin/finish")),
            "on_complete_program",
        );
    }

    #[test]
    fn m226_use_incomplete_dir_immediate() {
        m226_delta_and_classify_check(|s| s.use_incomplete_dir = true, "use_incomplete_dir");
    }

    #[test]
    fn m226_incomplete_dir_immediate() {
        m226_delta_and_classify_check(
            |s| s.incomplete_dir = Some(std::path::PathBuf::from("/tmp/inc")),
            "incomplete_dir",
        );
    }

    #[test]
    fn m226_default_skip_hash_check_immediate() {
        m226_delta_and_classify_check(
            |s| s.default_skip_hash_check = true,
            "default_skip_hash_check",
        );
    }

    #[test]
    fn m226_incomplete_extension_enabled_immediate() {
        // Default is TRUE so we toggle false to observe diff.
        m226_delta_and_classify_check(
            |s| s.incomplete_extension_enabled = false,
            "incomplete_extension_enabled",
        );
    }

    #[test]
    fn m226_watched_folder_immediate() {
        m226_delta_and_classify_check(
            |s| s.watched_folder = Some(std::path::PathBuf::from("/tmp/watched")),
            "watched_folder",
        );
    }

    #[test]
    fn m226_delete_torrent_after_add_immediate() {
        m226_delta_and_classify_check(
            |s| s.delete_torrent_after_add = true,
            "delete_torrent_after_add",
        );
    }

    #[test]
    fn m226_move_completed_enabled_immediate() {
        m226_delta_and_classify_check(
            |s| s.move_completed_enabled = true,
            "move_completed_enabled",
        );
    }

    #[test]
    fn m226_move_completed_to_immediate() {
        m226_delta_and_classify_check(
            |s| s.move_completed_to = Some(std::path::PathBuf::from("/tmp/done")),
            "move_completed_to",
        );
    }

    #[test]
    fn m226_ip_filter_auto_refresh_immediate() {
        m226_delta_and_classify_check(
            |s| s.ip_filter_auto_refresh = true,
            "ip_filter_auto_refresh",
        );
    }

    #[test]
    fn m226_web_ui_https_enabled_immediate() {
        m226_delta_and_classify_check(|s| s.web_ui_https_enabled = true, "web_ui_https_enabled");
    }

    #[test]
    fn m226_network_interface_immediate() {
        m226_delta_and_classify_check(
            |s| s.network_interface = Some("eth0".into()),
            "network_interface",
        );
    }

    #[test]
    fn m226_default_add_paused_immediate() {
        m226_delta_and_classify_check(|s| s.default_add_paused = true, "default_add_paused");
    }

    #[test]
    fn m226_delta_clears_optional_path_incomplete_dir() {
        // F4 — outer Some + inner None means "clear to None". Without nested
        // Option this case is indistinguishable from "no change".
        use crate::types::SettingsDelta;
        let old = Settings {
            incomplete_dir: Some(std::path::PathBuf::from("/foo")),
            ..Settings::default()
        };
        let new = Settings {
            incomplete_dir: None,
            ..old.clone()
        };
        let d = SettingsDelta::from_diff(&old, &new);
        assert_eq!(d.incomplete_dir, Some(None), "must signal clear to None");
        assert!(!d.is_empty());
    }

    #[test]
    fn m226_delta_clears_optional_path_watched_folder() {
        // F4 — same pattern for watched_folder.
        use crate::types::SettingsDelta;
        let old = Settings {
            watched_folder: Some(std::path::PathBuf::from("/tmp/watch")),
            ..Settings::default()
        };
        let new = Settings {
            watched_folder: None,
            ..old.clone()
        };
        let d = SettingsDelta::from_diff(&old, &new);
        assert_eq!(d.watched_folder, Some(None));
        assert!(!d.is_empty());
    }

    #[test]
    fn m226_delta_is_empty_honours_new_fields() {
        // is_empty must return false when ANY M226 field is set.
        use crate::types::SettingsDelta;
        let mut d = SettingsDelta::default();
        assert!(d.is_empty());
        d.notify_on_complete = Some(true);
        assert!(!d.is_empty());
        d = SettingsDelta::default();
        d.watched_folder = Some(None);  // clear-to-None still counts
        assert!(!d.is_empty());
        d = SettingsDelta::default();
        d.default_add_paused = Some(true);
        assert!(!d.is_empty());
    }

    #[test]
    fn m226_no_fields_appear_in_restart_required() {
        // Negative coverage: toggling each of the 15 M226 fields one at a
        // time must NOT produce any classify_restart_required entries.
        type Mutation = fn(&mut Settings);
        let mutations: [Mutation; 15] = [
            |s| s.notify_on_complete = true,
            |s| s.notify_on_error = true,
            |s| s.on_complete_program = Some(std::path::PathBuf::from("/p")),
            |s| s.use_incomplete_dir = true,
            |s| s.incomplete_dir = Some(std::path::PathBuf::from("/i")),
            |s| s.default_skip_hash_check = true,
            |s| s.incomplete_extension_enabled = false,
            |s| s.watched_folder = Some(std::path::PathBuf::from("/w")),
            |s| s.delete_torrent_after_add = true,
            |s| s.move_completed_enabled = true,
            |s| s.move_completed_to = Some(std::path::PathBuf::from("/m")),
            |s| s.ip_filter_auto_refresh = true,
            |s| s.web_ui_https_enabled = true,
            |s| s.network_interface = Some("eth0".into()),
            |s| s.default_add_paused = true,
        ];
        let old = Settings::default();
        for (idx, m) in mutations.iter().enumerate() {
            let mut new = old.clone();
            m(&mut new);
            let rr = classify_restart_required(&old, &new);
            assert!(
                rr.is_empty(),
                "mutation #{idx}: M226 fields must not surface restart_required, got {rr:?}"
            );
        }
    }

    #[test]
    fn classify_immediate_seed_time_and_inactive_combined() {
        // Both seed-time limits flipped in one delta — both must surface
        // in `immediate`, none in `restart_required`.
        let old = Settings::default();
        let mut new = old.clone();
        new.seed_time_limit_secs = Some(7200);
        new.inactive_seed_time_limit_secs = Some(900);
        let imm = classify_immediate(&old, &new);
        let set: std::collections::HashSet<&str> = imm.iter().copied().collect();
        assert_eq!(
            set,
            ["max_seeding_time", "max_inactive_seeding_time"]
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_combined_seed_time_and_hashing_both_immediate() {
        // M225: hashing_threads graduated from restart_required to immediate
        // (D-eng-2 revised). With seed_time_limit also immediate, both fields
        // must surface in immediate, none in restart_required.
        let old = Settings::default();
        let mut new = old.clone();
        new.seed_time_limit_secs = Some(1200);
        new.hashing_threads = old.hashing_threads.saturating_add(2);
        let imm = classify_immediate(&old, &new);
        let set: std::collections::HashSet<&str> = imm.iter().copied().collect();
        assert_eq!(
            set,
            ["max_seeding_time", "hashing_threads"]
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    #[test]
    fn classify_combined_hashing_and_save_resume_both_immediate() {
        // M225: hashing_threads and save_resume_interval both graduated from
        // restart_required to immediate. Mixed change must land both in
        // immediate, none in restart_required.
        let old = Settings::default();
        let mut new = old.clone();
        new.hashing_threads = old.hashing_threads.saturating_add(3);
        new.save_resume_interval_secs = old.save_resume_interval_secs.saturating_add(120);
        let imm = classify_immediate(&old, &new);
        let set: std::collections::HashSet<&str> = imm.iter().copied().collect();
        assert_eq!(
            set,
            ["hashing_threads", "save_resume_interval"]
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
        );
        assert_eq!(classify_restart_required(&old, &new), Vec::<&str>::new());
    }

    // ── M226: AddTorrentParams.paused: Option<bool> resolution ──────────
    //
    // The constructor default `paused: None` means "honour the engine's
    // `default_add_paused`"; an explicit `.paused(v)` call wraps `Some(v)`
    // and wins over the engine setting. Tests exercise all 4 combinations
    // (3 here + 1 implicit default already covered by existing
    // `pause_resume_via_session` and `add_torrent_with_meta` tests).

    /// Re-bencode a single-piece v1 torrent so the bytes branch of
    /// `add_torrent` can ingest it. Helper avoids dragging
    /// `add_torrent_with_meta` into the M226 tests (that bypasses
    /// `AddTorrentParams` entirely).
    fn m226_make_torrent_bytes(data: &[u8], piece_length: u64) -> Vec<u8> {
        use serde::Serialize;

        #[derive(Serialize)]
        struct Info<'a> {
            length: u64,
            name: &'a str,
            #[serde(rename = "piece length")]
            piece_length: u64,
            #[serde(with = "serde_bytes")]
            pieces: &'a [u8],
        }
        #[derive(Serialize)]
        struct Torrent<'a> {
            info: Info<'a>,
        }

        let mut pieces = Vec::new();
        let mut offset = 0;
        while offset < data.len() {
            let end = (offset + piece_length as usize).min(data.len());
            let hash = irontide_core::sha1(&data[offset..end]);
            pieces.extend_from_slice(hash.as_bytes());
            offset = end;
        }

        irontide_bencode::to_bytes(&Torrent {
            info: Info {
                length: data.len() as u64,
                name: "m226-test",
                piece_length,
                pieces: &pieces,
            },
        })
        .unwrap()
    }

    /// M226 D1 acceptance: `default_add_paused = true` + caller passes no
    /// explicit `.paused(...)` → torrent must land paused.
    #[tokio::test]
    async fn add_torrent_with_default_add_paused_true_pauses_torrent() {
        let mut settings = test_settings();
        settings.default_add_paused = true;
        let session = SessionHandle::start(settings).await.unwrap();

        let data = vec![0xAB; 16384];
        let bytes = m226_make_torrent_bytes(&data, 16384);
        let info_hash = session
            .add_torrent(AddTorrentParams::bytes(bytes))
            .await
            .unwrap();

        // Pause is dispatched via `tokio::spawn(handle.pause())`; give the
        // dispatched task a tick to land before we read state.
        tokio::time::sleep(Duration::from_millis(100)).await;
        let stats = session.torrent_stats(info_hash).await.unwrap();
        assert_eq!(
            stats.state,
            TorrentState::Paused,
            "engine default_add_paused=true must pause the torrent when caller \
             passes AddTorrentParams::bytes() without an explicit .paused(...)"
        );

        session.shutdown().await.unwrap();
    }

    /// M226 D1 acceptance: explicit `.paused(false)` must beat
    /// `default_add_paused = true` — the engine setting is the fallback,
    /// the per-call override is authoritative.
    #[tokio::test]
    async fn add_torrent_with_explicit_paused_false_resumes_despite_default() {
        let mut settings = test_settings();
        settings.default_add_paused = true;
        let session = SessionHandle::start(settings).await.unwrap();

        let data = vec![0xCD; 16384];
        let bytes = m226_make_torrent_bytes(&data, 16384);
        let info_hash = session
            .add_torrent(AddTorrentParams::bytes(bytes).paused(false))
            .await
            .unwrap();

        // Negative assertion: nothing should run a paused dispatch path —
        // a brief sleep guards against a phantom spawned pause.
        tokio::time::sleep(Duration::from_millis(100)).await;
        let stats = session.torrent_stats(info_hash).await.unwrap();
        assert_ne!(
            stats.state,
            TorrentState::Paused,
            "explicit .paused(false) must override default_add_paused=true; \
             got state={:?}",
            stats.state
        );

        session.shutdown().await.unwrap();
    }

    /// M226 D1 acceptance: explicit `.paused(true)` must beat
    /// `default_add_paused = false` — mirror image of the previous test
    /// to cover the other direction of "explicit wins over default".
    #[tokio::test]
    async fn add_torrent_with_explicit_paused_true_pauses_despite_default_false() {
        let mut settings = test_settings();
        settings.default_add_paused = false;
        let session = SessionHandle::start(settings).await.unwrap();

        let data = vec![0xEF; 16384];
        let bytes = m226_make_torrent_bytes(&data, 16384);
        let info_hash = session
            .add_torrent(AddTorrentParams::bytes(bytes).paused(true))
            .await
            .unwrap();

        tokio::time::sleep(Duration::from_millis(100)).await;
        let stats = session.torrent_stats(info_hash).await.unwrap();
        assert_eq!(
            stats.state,
            TorrentState::Paused,
            "explicit .paused(true) must pause even when \
             default_add_paused=false"
        );

        session.shutdown().await.unwrap();
    }
}