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
//! Unified settings pack for session configuration.
//!
//! Replaces the old `SessionConfig` with a single strongly-typed struct that
//! consolidates all configurable knobs. Supports presets, validation, and
//! serde serialization (bencode + JSON).

use std::net::IpAddr;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use irontide_core::StorageMode;
use irontide_wire::mse::EncryptionMode;

use crate::alert::AlertCategory;
use crate::choker::{ChokingAlgorithm, SeedChokingAlgorithm};
use crate::proxy::ProxyConfig;
use crate::rate_limiter::MixedModeAlgorithm;

/// M171: Action taken when a torrent's seed ratio reaches its configured limit.
///
/// Wire format is qBt's `snake_case` string (`"pause"` / `"remove"` /
/// `"enable_super_seeding"`). Pause keeps the torrent in the session in a
/// user-stopped state, Remove deletes the torrent record (files remain),
/// and `EnableSuperSeeding` flips the torrent into BEP 16 super-seed mode
/// without stopping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MaxRatioAction {
    /// Pause the torrent — keep it in the session but stop all activity.
    #[default]
    Pause,
    /// Remove the torrent record. Files on disk are left untouched.
    Remove,
    /// Enable BEP 16 super seeding on the torrent rather than stopping it.
    EnableSuperSeeding,
}

// ── Serde default helpers ────────────────────────────────────────────

fn default_true() -> bool {
    true
}
fn default_listen_port() -> u16 {
    42020
}
fn default_download_dir() -> PathBuf {
    PathBuf::from(".")
}
fn default_max_torrents() -> usize {
    100
}
fn default_encryption() -> EncryptionMode {
    EncryptionMode::Disabled
}
fn default_auto_upload_slots_min() -> usize {
    2
}
fn default_auto_upload_slots_max() -> usize {
    20
}
fn default_active_downloads() -> i32 {
    3
}
fn default_active_seeds() -> i32 {
    5
}
fn default_active_limit() -> i32 {
    500
}
fn default_active_checking() -> i32 {
    3
}
fn default_inactive_rate() -> u64 {
    2048
}
fn default_auto_manage_interval() -> u64 {
    30
}
fn default_auto_manage_startup() -> u64 {
    60
}
fn default_queue_rate_ewma_alpha() -> f64 {
    0.3
}
fn default_seed_queue_min_active_secs() -> u64 {
    1800
}
fn default_alert_mask() -> AlertCategory {
    AlertCategory::ALL
}
fn default_alert_channel_size() -> usize {
    1024
}
fn default_smart_ban_max_failures() -> u32 {
    3
}
fn default_disk_io_threads() -> usize {
    let cores = std::thread::available_parallelism().map_or(4, std::num::NonZero::get);
    (cores / 2).clamp(4, 16)
}
fn default_max_blocking_threads() -> usize {
    std::thread::available_parallelism().map_or(4, std::num::NonZero::get)
}
fn default_storage_mode() -> StorageMode {
    StorageMode::Auto
}
fn default_disk_cache_size() -> usize {
    16 * 1024 * 1024
}
fn default_disk_write_cache_ratio() -> f32 {
    0.5
}
fn default_buffer_pool_capacity() -> usize {
    64 * 1024 * 1024
}
fn default_enable_mlock() -> bool {
    cfg!(unix)
}
fn default_io_uring_sq_depth() -> u32 {
    256
}
fn default_io_uring_batch_threshold() -> usize {
    4
}
fn default_disk_channel_capacity() -> usize {
    512
}
fn default_hashing_threads() -> usize {
    let cores = std::thread::available_parallelism().map_or(4, std::num::NonZero::get);
    (cores / 4).clamp(2, 8)
}
fn default_max_request_queue_depth() -> usize {
    250
}
fn default_initial_queue_depth() -> usize {
    128
}
fn default_request_queue_time() -> f64 {
    3.0
}
fn default_block_request_timeout() -> u32 {
    60
}
fn default_max_concurrent_streams() -> usize {
    8
}
fn default_dht_qps() -> usize {
    50
}
fn default_dht_timeout() -> u64 {
    5
}
fn default_upnp_lease() -> u32 {
    3600
}
fn default_natpmp_lifetime() -> u32 {
    7200
}
fn default_utp_max_conns() -> usize {
    256
}
fn default_dht_max_items() -> usize {
    700
}
fn default_dht_item_lifetime() -> u64 {
    7200
}
fn default_dht_sample_interval() -> u64 {
    0
}
fn default_suggest_mode() -> bool {
    true
}
fn default_max_suggest_pieces() -> usize {
    16
}
fn default_predictive_piece_announce_ms() -> u64 {
    0
}
fn default_ssl_listen_port() -> u16 {
    0 // 0 = disabled
}
fn default_seed_choking_algorithm() -> SeedChokingAlgorithm {
    SeedChokingAlgorithm::FastestUpload
}
fn default_choking_algorithm() -> ChokingAlgorithm {
    ChokingAlgorithm::FixedSlots
}
fn default_mixed_mode() -> MixedModeAlgorithm {
    MixedModeAlgorithm::PeerProportional
}
fn default_steal_threshold_ratio() -> f64 {
    10.0
}
fn default_use_block_stealing() -> bool {
    true
}
fn default_peer_connect_timeout() -> u64 {
    10 // M139: match rqbit — longer timeout produces more natural connect failures for cycling
}
fn default_peer_dscp() -> u8 {
    0x08 // CS1 (scavenger/low-priority)
}
fn default_max_peers_per_torrent() -> usize {
    128
}
// v0.187.3: eviction-policy tunables.
fn default_pass0_grace_secs() -> u64 {
    60 // Per OV2/12A: full minute of post-handshake slow-start before Pass 0 fires.
}
fn default_proactive_evictions_per_minute_limit() -> u32 {
    30 // Sliding-window cap that prevents the 130→20-50 churn observed in dogfood.
}
fn default_eviction_ban_duration_secs() -> u64 {
    600 // 10 min (was 1800/30 min). Long enough to break churn loops, short enough
    // that a legitimately slow peer can rejoin after warming up.
}
fn default_eviction_ban_set_cap() -> usize {
    1024 // FIFO cap on the banned-peer set (raised from the legacy 256).
}
fn default_stats_report_interval() -> u64 {
    1000
}
fn default_strict_end_game() -> bool {
    true
}
fn default_max_web_seeds() -> usize {
    4
}
fn default_web_seed_retry_base_secs() -> u64 {
    10
}
fn default_web_seed_retry_factor() -> u64 {
    6
}
fn default_web_seed_retry_cap_secs() -> u64 {
    3600
}
fn default_web_seed_max_failures() -> u32 {
    10
}
fn default_initial_picker_threshold() -> u32 {
    4
}
fn default_whole_pieces_threshold() -> u32 {
    20
}
fn default_snub_timeout_secs() -> u32 {
    15
}
fn default_readahead_pieces() -> u32 {
    8
}
fn default_max_metadata_size() -> u64 {
    4 * 1024 * 1024 // 4 MiB — libtorrent default
}
fn default_max_message_size() -> usize {
    16 * 1024 * 1024 // 16 MiB — matches wire codec constant
}
fn default_max_piece_length() -> u64 {
    32 * 1024 * 1024 // 32 MiB — largest reasonable piece size
}
fn default_max_outstanding_requests() -> usize {
    500
}
fn default_max_in_flight_pieces() -> usize {
    512
}
fn default_fixed_pipeline_depth() -> usize {
    128
}
fn default_i2p_hostname() -> String {
    "127.0.0.1".into()
}
fn default_i2p_port() -> u16 {
    7656
}
fn default_i2p_tunnel_quantity() -> u8 {
    3
}
fn default_i2p_tunnel_length() -> u8 {
    3
}
fn default_runtime_worker_threads() -> usize {
    std::thread::available_parallelism().map_or(4, |n| n.get().min(8))
}
fn default_lock_warn_threshold_ms() -> u64 {
    50
}
fn default_steal_stale_piece_secs() -> u64 {
    2
}
fn default_steal_threshold_endgame() -> f64 {
    3.0
}
fn default_peer_read_timeout_secs() -> u64 {
    10
}
fn default_peer_write_timeout_secs() -> u64 {
    10
}
fn default_data_contribution_timeout() -> u64 {
    0 // M139: disabled by default — rqbit doesn't evict for no data
}
fn default_choke_rotation_max_evictions() -> u32 {
    0 // M139: disabled by default — rqbit doesn't proactively rotate choked peers
}
fn default_max_concurrent_connects() -> u16 {
    128 // M147: ConnectPool — gates connection attempts, released on handshake
}
fn default_connect_soft_timeout() -> u64 {
    3 // M147: seconds without TCP SYN-ACK before soft reap disconnects
}
fn default_dispatch_backlog_cap() -> usize {
    8 // M182: dispatch_tx reader-side spill cap (constant pre-perf-harness)
}
fn default_event_backlog_cap() -> usize {
    32 // M182: event_tx reader-side spill cap (constant pre-perf-harness)
}
fn default_web_seed_progress_throttle_ms() -> u64 {
    250 // M178: per-URL minimum interval for PeerEvent::WebSeedProgress (0 = disabled)
}
fn default_save_resume_interval() -> u64 {
    300 // M161: 5 minutes between periodic resume file saves
}
fn default_max_upload_slots_global() -> i32 {
    -1
}
fn default_max_upload_slots_per_torrent() -> i32 {
    4
}
fn default_max_connections_global() -> i32 {
    -1
}
fn default_max_uploads_per_torrent() -> i32 {
    -1
}

// ── Settings ─────────────────────────────────────────────────────────

/// Unified session settings (replaces `SessionConfig`).
///
/// All 56 configurable fields in a single strongly-typed struct.
/// Supports presets via factory functions and runtime mutation via
/// `SessionHandle::apply_settings()`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Settings {
    // ── General ──
    /// TCP listen port for incoming peer connections (default: 42020).
    #[serde(default = "default_listen_port")]
    pub listen_port: u16,
    /// Randomize the listen port each time the session starts. Default: false.
    #[serde(default)]
    pub randomize_port_on_startup: bool,
    /// Default download directory for new torrents (default: ".").
    #[serde(default = "default_download_dir")]
    pub download_dir: PathBuf,
    /// Maximum number of concurrent torrents (default: 100).
    #[serde(default = "default_max_torrents")]
    pub max_torrents: usize,
    /// Directory for fast-resume data files. If `None`, resume data is not persisted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume_data_dir: Option<PathBuf>,
    /// Interval in seconds between periodic resume file saves (0 = disabled).
    /// Default: 300 (5 minutes).
    #[serde(default = "default_save_resume_interval")]
    pub save_resume_interval_secs: u64,

    // ── Protocol features ──
    /// Enable Kademlia DHT peer discovery (BEP 5). Default: true.
    #[serde(default = "default_true")]
    pub enable_dht: bool,
    /// Enable Peer Exchange (BEP 11). Default: true.
    #[serde(default = "default_true")]
    pub enable_pex: bool,
    /// Enable Local Service Discovery via multicast (BEP 14). Default: true.
    #[serde(default = "default_true")]
    pub enable_lsd: bool,
    /// Enable BEP 6 Fast Extension (`AllowedFast`, `HaveAll`, `HaveNone`, Reject,
    /// `SuggestPiece`). Default: true.
    #[serde(default = "default_true")]
    pub enable_fast_extension: bool,
    /// Enable uTP (BEP 29) micro transport protocol. When enabled, outbound
    /// connections try uTP first with a 5-second timeout before falling back
    /// to TCP. Default: true.
    #[serde(default = "default_true")]
    pub enable_utp: bool,
    /// Enable `UPnP` IGD port mapping (last resort after PCP and NAT-PMP).
    /// Default: true.
    #[serde(default = "default_true")]
    pub enable_upnp: bool,
    /// Enable NAT-PMP (RFC 6886) and PCP (RFC 6887) port mapping.
    /// PCP is tried first, then NAT-PMP as fallback. Default: true.
    #[serde(default = "default_true")]
    pub enable_natpmp: bool,
    /// Enable IPv6 dual-stack support (BEP 7, 24). Binds listeners on both
    /// IPv4 and IPv6, starts a second DHT instance, and processes IPv6 peers
    /// in PEX and tracker responses. Default: true.
    #[serde(default = "default_true")]
    pub enable_ipv6: bool,
    /// Enable HTTP/web seeding (BEP 19 `GetRight`, BEP 17 Hoffman). Torrents
    /// with `url-list` or `httpseeds` download pieces from HTTP servers
    /// alongside peer-to-peer transfers. Default: true.
    #[serde(default = "default_true")]
    pub enable_web_seed: bool,
    /// Enable BEP 55 holepunch extension for NAT traversal. Advertises
    /// `ut_holepunch` in the extension handshake and can act as initiator,
    /// relay, or target for holepunch connections. Default: true.
    #[serde(default = "default_true")]
    pub enable_holepunch: bool,
    /// Enable BEP 40 canonical peer priority for connection eviction.
    /// When at capacity, incoming peers with higher deterministic priority
    /// can displace lower-priority ones. Default: true.
    #[serde(default = "default_true")]
    pub enable_bep40_eviction: bool,
    /// Enable diagnostic counters (dispatch timing, backpressure high-water,
    /// peer unchoke/choke/lifetime telemetry). Default: false — enable for
    /// benchmarking or troubleshooting via `--diagnostics` or config.
    #[serde(default)]
    pub enable_diagnostic_counters: bool,
    /// Connection encryption mode (MSE/PE). Default: Disabled.
    #[serde(default = "default_encryption")]
    pub encryption_mode: EncryptionMode,
    /// Suppress identifying information (client version in BEP 10 handshake)
    /// and disable DHT, LSD, `UPnP`, and NAT-PMP. Default: false.
    #[serde(default)]
    pub anonymous_mode: bool,
    /// Manually configured external IP for BEP 40 peer priority.
    /// If not set, discovered automatically via NAT traversal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_ip: Option<IpAddr>,

    // ── Seeding ──
    /// Stop seeding when this upload/download ratio is reached. `None` = unlimited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed_ratio_limit: Option<f64>,
    /// M171: Stop seeding after this many cumulative seeding seconds.
    /// `None` = no limit. Mirrors qBt's "Maximum seeding time" preference,
    /// which is exposed in minutes on the wire but stored here in seconds
    /// to match the other duration-typed fields.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed_time_limit_secs: Option<u64>,
    /// M171: Stop seeding after this many seconds of inactivity while in the
    /// Seeding state (no outgoing Piece data). `None` = no limit. Mirrors
    /// qBt's "Maximum inactive seeding time" preference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inactive_seed_time_limit_secs: Option<u64>,
    /// M171: What to do when `seed_ratio_limit` is reached.
    /// Mirrors qBt's `max_ratio_act` wire enum. Default: `Pause`.
    #[serde(default)]
    pub max_ratio_action: MaxRatioAction,
    /// M171: Create a subfolder named after the torrent when adding a
    /// multi-file torrent. Mirrors qBt's `create_subfolder_enabled`.
    /// Default: `true` (qBt factory default).
    #[serde(default = "default_true")]
    pub create_subfolder: bool,
    /// M171: Automatically manage torrent resources via the queueing
    /// subsystem (start/stop/recheck order). Mirrors qBt's
    /// `auto_tmm_enabled`. Default: `false`.
    #[serde(default)]
    pub auto_manage_torrents: bool,
    /// M171: Enable the download/upload queueing subsystem. When `false`,
    /// no queueing is applied and torrents run concurrently up to per-torrent
    /// limits. Mirrors qBt's `queueing_enabled`. Default: `false`.
    #[serde(default)]
    pub queueing_enabled: bool,
    /// Enable BEP 16 super seeding for new torrents. Reveals pieces one-per-peer
    /// to maximize piece diversity across the swarm. Default: false.
    #[serde(default)]
    pub default_super_seeding: bool,
    /// Default share mode for new torrents. When true, torrents relay pieces
    /// in memory without writing to disk. Requires fast extension (BEP 6).
    #[serde(default)]
    pub default_share_mode: bool,
    /// Advertise upload-only status via extension handshake when a torrent
    /// transitions to seeding (BEP 21). Default: true.
    #[serde(default = "default_true")]
    pub upload_only_announce: bool,
    // ── Rate limiting ──
    /// Global upload rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub upload_rate_limit: u64,
    /// Global download rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub download_rate_limit: u64,
    /// TCP upload rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub tcp_upload_rate_limit: u64,
    /// TCP download rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub tcp_download_rate_limit: u64,
    /// uTP upload rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub utp_upload_rate_limit: u64,
    /// uTP download rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub utp_download_rate_limit: u64,
    /// Automatically adjust the number of upload slots based on bandwidth. Default: true.
    #[serde(default = "default_true")]
    pub auto_upload_slots: bool,
    /// Minimum number of automatic upload slots (default: 2).
    #[serde(default = "default_auto_upload_slots_min")]
    pub auto_upload_slots_min: usize,
    /// Maximum number of automatic upload slots (default: 20).
    #[serde(default = "default_auto_upload_slots_max")]
    pub auto_upload_slots_max: usize,
    /// Maximum upload slots across all torrents (-1 = unlimited). Default: -1.
    #[serde(default = "default_max_upload_slots_global")]
    pub max_upload_slots_global: i32,
    /// Maximum upload slots per torrent. Default: 4.
    #[serde(default = "default_max_upload_slots_per_torrent")]
    pub max_upload_slots_per_torrent: i32,
    /// Maximum peer connections across all torrents (-1 = unlimited). Default: -1.
    #[serde(default = "default_max_connections_global")]
    pub max_connections_global: i32,
    /// Maximum unchoked upload slots per torrent (-1 = unlimited). Default: -1.
    /// M224: qBt wire `max_uploads_per_torrent`. `-1` is unlimited; `n >= 1`
    /// caps the choker's unchoke set; `0` is explicitly rejected by
    /// [`Settings::validate`] (choking every peer is almost certainly a
    /// wire-format mistake, not user intent).
    #[serde(default = "default_max_uploads_per_torrent")]
    pub max_uploads_per_torrent: i32,
    /// Alternative download rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub alt_download_rate_limit: u64,
    /// Alternative upload rate limit in bytes/sec (0 = unlimited).
    #[serde(default)]
    pub alt_upload_rate_limit: u64,
    /// Whether alternative speed limits are currently active. Default: false.
    #[serde(default)]
    pub alt_speed_enabled: bool,
    /// Whether the alternative speed schedule is enabled. Default: false.
    #[serde(default)]
    pub alt_speed_schedule_enabled: bool,
    /// Schedule start time in minutes-of-day (0-1439). Default: 0.
    #[serde(default)]
    pub alt_speed_schedule_from: u16,
    /// Schedule end time in minutes-of-day (0-1439). Default: 0.
    #[serde(default)]
    pub alt_speed_schedule_to: u16,
    /// Schedule active days as a bitmask (bit 0 = Mon .. bit 6 = Sun). Default: 0.
    #[serde(default)]
    pub alt_speed_schedule_days: u8,
    /// Include protocol overhead in rate limit calculations. Default: true.
    #[serde(default = "default_true")]
    pub rate_limit_includes_overhead: bool,
    /// Apply rate limits to uTP connections. Default: true.
    #[serde(default = "default_true")]
    pub rate_limit_utp: bool,
    /// Apply rate limits to LAN connections. Default: false.
    #[serde(default)]
    pub rate_limit_lan: bool,
    /// Mixed-mode TCP/uTP bandwidth allocation algorithm.
    #[serde(default = "default_mixed_mode")]
    pub mixed_mode_algorithm: MixedModeAlgorithm,

    // ── Queue management ──
    /// Maximum concurrent auto-managed downloading torrents (-1 = unlimited, default: 3).
    #[serde(default = "default_active_downloads")]
    pub active_downloads: i32,
    /// Maximum concurrent auto-managed seeding torrents (-1 = unlimited, default: 5).
    #[serde(default = "default_active_seeds")]
    pub active_seeds: i32,
    /// Hard cap on all active auto-managed torrents (-1 = unlimited, default: 500).
    #[serde(default = "default_active_limit")]
    pub active_limit: i32,
    /// Maximum concurrent hash-check operations (default: 1).
    #[serde(default = "default_active_checking")]
    pub active_checking: i32,
    /// Exempt inactive torrents from download/seed limits. A torrent is inactive
    /// if its rate is below `inactive_down_rate` / `inactive_up_rate`. Default: true.
    #[serde(default = "default_true")]
    pub dont_count_slow_torrents: bool,
    /// Download rate threshold (bytes/sec) below which a torrent is considered
    /// inactive for queue management purposes (default: 2048).
    #[serde(default = "default_inactive_rate")]
    pub inactive_down_rate: u64,
    /// Upload rate threshold (bytes/sec) below which a torrent is considered
    /// inactive for queue management purposes (default: 2048).
    #[serde(default = "default_inactive_rate")]
    pub inactive_up_rate: u64,
    /// Interval in seconds between queue evaluations (default: 30).
    #[serde(default = "default_auto_manage_interval")]
    pub auto_manage_interval: u64,
    /// Grace period in seconds where a torrent is considered active regardless
    /// of speed after being started (default: 60).
    #[serde(default = "default_auto_manage_startup")]
    pub auto_manage_startup: u64,
    /// Allocate seeding slots before download slots. Default: false.
    #[serde(default)]
    pub auto_manage_prefer_seeds: bool,
    /// EWMA smoothing factor for queue rate classification (0.0–1.0).
    /// 0.0 = pure history (never adapts), 1.0 = no smoothing (raw rate).
    /// Default: 0.3.
    #[serde(default = "default_queue_rate_ewma_alpha")]
    pub queue_rate_ewma_alpha: f64,
    /// Anti-flap grace period for seeding torrents, in seconds.
    /// Seeding torrents are exempt from queue-pause for this duration after
    /// starting (default: 1800 = 30 minutes, matching libtorrent).
    #[serde(default = "default_seed_queue_min_active_secs")]
    pub seed_queue_min_active_secs: u64,

    // ── Alerts ──
    /// Bitmask of alert categories to receive (default: ALL).
    #[serde(default = "default_alert_mask")]
    pub alert_mask: AlertCategory,
    /// Capacity of the alert broadcast channel (default: 1024).
    #[serde(default = "default_alert_channel_size")]
    pub alert_channel_size: usize,

    // ── Smart banning ──
    /// Number of hash-failure involvements before a peer is auto-banned.
    /// Lower values ban faster but risk false positives (default: 3).
    #[serde(default = "default_smart_ban_max_failures")]
    pub smart_ban_max_failures: u32,
    /// Enable parole mode: re-download a failed piece from a single uninvolved
    /// peer to definitively attribute fault before striking. Default: true.
    #[serde(default = "default_true")]
    pub smart_ban_parole: bool,

    // ── Disk I/O ──
    /// Number of concurrent disk I/O threads (default: 4).
    #[serde(default = "default_disk_io_threads")]
    pub disk_io_threads: usize,
    /// Maximum number of concurrent blocking I/O operations dispatched via
    /// `block_in_place`. Defaults to the number of available CPU cores.
    #[serde(default = "default_max_blocking_threads")]
    pub max_blocking_threads: usize,
    /// Storage allocation mode: Auto, `FullPreallocate`, or `SparseFile` (default: Auto).
    #[serde(default = "default_storage_mode")]
    pub storage_mode: StorageMode,
    /// Override pre-allocation strategy (None/Sparse/Full). When `None` (default),
    /// derived from `storage_mode`: Full → `PreallocateMode::Full`, else → `PreallocateMode::None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preallocate_mode: Option<irontide_storage::PreallocateMode>,
    /// Total ARC disk cache size in bytes (default: 16 MiB, minimum: 1 MiB).
    #[serde(default = "default_disk_cache_size")]
    pub disk_cache_size: usize,
    /// Fraction of disk cache reserved for write buffering (0.0–1.0, default: 0.5).
    #[serde(default = "default_disk_write_cache_ratio")]
    pub disk_write_cache_ratio: f32,
    /// Capacity of the async disk I/O command channel (default: 512).
    #[serde(default = "default_disk_channel_capacity")]
    pub disk_channel_capacity: usize,
    /// Unified buffer pool capacity in bytes (default: 64 MiB).
    /// Replaces `disk_cache_size` when set. Covers both write buffering and read cache.
    #[serde(default = "default_buffer_pool_capacity")]
    pub buffer_pool_capacity: usize,
    /// Lock cached piece data in physical memory (default: true on Unix).
    /// Prevents the OS from swapping out hot cache entries. Silently ignored
    /// if `RLIMIT_MEMLOCK` is exceeded.
    #[serde(default = "default_enable_mlock")]
    pub enable_mlock: bool,
    /// `io_uring` submission queue depth (number of SQEs). Only used when
    /// `storage_mode` is `IoUring`. Default: 256.
    #[serde(default = "default_io_uring_sq_depth")]
    pub io_uring_sq_depth: u32,
    /// Enable `O_DIRECT` for `io_uring` writes, bypassing the kernel page cache.
    /// Unaligned writes fall back to regular pwritev. Default: false.
    #[serde(default)]
    pub io_uring_direct_io: bool,
    /// Enable direct I/O for filesystem storage (bypasses kernel page cache).
    /// Linux/FreeBSD: `O_DIRECT`, macOS: `F_NOCACHE`. Windows: use `--iocp`
    /// with `--direct-io`. Default: false.
    #[serde(default)]
    pub filesystem_direct_io: bool,
    /// Minimum number of file segments to batch before using `io_uring`.
    /// Below this threshold, pwritev may be cheaper. Default: 4.
    #[serde(default = "default_io_uring_batch_threshold")]
    pub io_uring_batch_threshold: usize,
    /// IOCP concurrent thread count (0 = system default). Only used when
    /// `storage_mode` is `Iocp`. Default: 0.
    #[serde(default)]
    pub iocp_concurrent_threads: u32,
    /// Enable `FILE_FLAG_NO_BUFFERING` for IOCP I/O, bypassing the OS page cache.
    /// Requires sector-aligned writes. Default: false.
    #[serde(default)]
    pub iocp_direct_io: bool,
    // ── Hashing & piece picking ──
    /// Number of concurrent piece hash verification threads (default: 2).
    #[serde(default = "default_hashing_threads")]
    pub hashing_threads: usize,
    /// Maximum per-peer request queue depth (default: 250).
    #[serde(default = "default_max_request_queue_depth")]
    pub max_request_queue_depth: usize,
    /// Initial per-peer request queue depth (default: 128). Higher values let
    /// peers reach full throughput faster by skipping slow-start ramp-up.
    #[serde(default = "default_initial_queue_depth")]
    pub initial_queue_depth: usize,
    /// Request queue time multiplier in seconds (default: 3.0).
    ///
    /// **Deprecated**: This field is retained for backward compatibility with
    /// existing config files. The pipeline now uses a fixed-depth model where
    /// queue depth equals `initial_queue_depth` for the lifetime of the
    /// connection; this value is no longer used in depth computation.
    #[serde(default = "default_request_queue_time")]
    pub request_queue_time: f64,
    /// Block request timeout in seconds before the request is considered
    /// lost and re-issued (default: 60).
    #[serde(default = "default_block_request_timeout")]
    pub block_request_timeout_secs: u32,
    /// Maximum concurrent `FileStream` readers. Controls how many simultaneous
    /// file-streaming reads can proceed (default: 8).
    #[serde(default = "default_max_concurrent_streams")]
    pub max_concurrent_stream_reads: usize,
    /// Automatically switch to sequential piece picking when too many partial
    /// pieces accumulate. Uses hysteresis (1.6x activate / 1.3x deactivate).
    #[serde(default = "default_true")]
    pub auto_sequential: bool,
    /// In end-game mode, cancel duplicate requests when a piece completes.
    /// When false, both copies download — wastes bandwidth but finishes faster
    /// on unreliable peers. Default: true.
    #[serde(default = "default_strict_end_game")]
    pub strict_end_game: bool,
    /// Maximum concurrent web seed connections per torrent (default: 4).
    #[serde(default = "default_max_web_seeds")]
    pub max_web_seeds: usize,
    /// M186: Base delay (seconds) for web seed exponential backoff. Default: 10.
    #[serde(default = "default_web_seed_retry_base_secs")]
    pub web_seed_retry_base_secs: u64,
    /// M186: Multiplier for web seed exponential backoff. Default: 6.
    #[serde(default = "default_web_seed_retry_factor")]
    pub web_seed_retry_factor: u64,
    /// M186: Maximum backoff (seconds) for web seed retry. Default: 3600.
    #[serde(default = "default_web_seed_retry_cap_secs")]
    pub web_seed_retry_cap_secs: u64,
    /// M186: Consecutive failures before permanently banning a web seed. Default: 10.
    #[serde(default = "default_web_seed_max_failures")]
    pub web_seed_max_failures: u32,
    /// Completed piece count below which the picker uses random selection
    /// to promote piece diversity in the swarm. Default: 4.
    #[serde(default = "default_initial_picker_threshold")]
    pub initial_picker_threshold: u32,
    /// Seconds to download a piece — if a peer is faster, it gets exclusive
    /// assignment (no block splitting). Default: 20.
    #[serde(default = "default_whole_pieces_threshold")]
    pub whole_pieces_threshold: u32,
    /// Seconds without data from a peer before marking it as snubbed.
    /// Snubbed peers get queue depth clamped to 1. Default: 60.
    #[serde(default = "default_snub_timeout_secs")]
    pub snub_timeout_secs: u32,
    /// Number of pieces ahead of the streaming cursor to prioritize (default: 8).
    #[serde(default = "default_readahead_pieces")]
    pub readahead_pieces: u32,
    /// Escalate streaming piece requests that exceed the mean RTT. Default: true.
    #[serde(default = "default_true")]
    pub streaming_timeout_escalation: bool,
    /// Steal blocks from peers this many times slower than the requesting peer (default: 10.0).
    /// Set to 0.0 to disable stealing.
    #[serde(default = "default_steal_threshold_ratio")]
    pub steal_threshold_ratio: f64,
    /// Enable per-block stealing: fast peers can steal individual unrequested
    /// blocks from pieces reserved by slower peers (default: true).
    #[serde(default = "default_use_block_stealing")]
    pub use_block_stealing: bool,
    /// Seconds between steal-queue population scans. Every N seconds, all
    /// in-flight pieces are pushed into the steal queue so fast peers can
    /// steal blocks mid-download (not just at endgame). 0 = disabled.
    /// Default: 2.
    #[serde(default = "default_steal_stale_piece_secs")]
    pub steal_stale_piece_secs: u64,
    /// M149: Steal threshold multiplier when >90% complete (endgame).
    /// Pieces taking longer than `swarm_avg` * this value are stolen. Default: 3.0.
    #[serde(default = "default_steal_threshold_endgame")]
    pub steal_threshold_endgame: f64,
    /// Fixed per-peer pipeline depth (number of concurrent requests per peer).
    /// Replaces the old AIMD dynamic depth system. rqbit uses a fixed
    /// `Semaphore(128)` per peer — simpler and faster. This setting allows
    /// benchmarking different fixed depths. Default: 128.
    #[serde(default = "default_fixed_pipeline_depth")]
    pub fixed_pipeline_depth: usize,

    // ── Piece picker enhancements (M44) ──
    /// Prefer pieces adjacent to those already downloaded for improved sequential
    /// disk access patterns (4 MiB extent groups). Default: true.
    #[serde(default = "default_true")]
    pub piece_extent_affinity: bool,
    /// Enable BEP 6 `SuggestPiece`: suggest newly verified pieces to peers that
    /// Send `SuggestPiece` messages for cached pieces so peers can request what they
    /// don't have them, improving piece diversity in the swarm. Default: true.
    #[serde(default = "default_suggest_mode")]
    pub suggest_mode: bool,
    /// Maximum `SuggestPiece` messages per peer to avoid flooding (default: 10).
    #[serde(default = "default_max_suggest_pieces")]
    pub max_suggest_pieces: usize,
    /// Predictive piece announce delay in milliseconds. When > 0, a Have message
    /// is sent before hash verification completes, reducing piece availability
    /// latency at the cost of a possible false announce. Default: 0 (disabled).
    #[serde(default = "default_predictive_piece_announce_ms")]
    pub predictive_piece_announce_ms: u64,

    // ── Proxy ──
    /// Proxy configuration for peer and tracker connections. Default: no proxy.
    #[serde(default)]
    pub proxy: ProxyConfig,
    /// Force all connections through the configured proxy. Disables listen
    /// sockets, `UPnP`, NAT-PMP, DHT, and LSD. Default: false.
    #[serde(default)]
    pub force_proxy: bool,

    // ── IP Filtering ──
    /// Enable the IP filter (blocklist). Default: false.
    #[serde(default)]
    pub ip_filter_enabled: bool,
    /// Path to the IP filter file (e.g. `ipfilter.dat`). Default: empty.
    #[serde(default)]
    pub ip_filter_path: String,
    /// Automatically refresh the IP filter when the file changes. Default: false.
    #[serde(default)]
    pub ip_filter_auto_refresh: bool,

    /// Check tracker IP addresses against the IP filter. When false, trackers
    /// are exempt from IP filtering. Default: true.
    #[serde(default = "default_true")]
    pub apply_ip_filter_to_trackers: bool,

    // ── DHT tuning ──
    /// Maximum DHT queries per second to control network traffic (default: 50).
    #[serde(default = "default_dht_qps")]
    pub dht_queries_per_second: usize,
    /// Timeout in seconds for a single DHT query before it is abandoned (default: 5).
    #[serde(default = "default_dht_timeout")]
    pub dht_query_timeout_secs: u64,
    /// BEP 42: Enforce node ID verification in DHT routing table.
    /// Disabled by default: too many real DHT nodes lack BEP 42-compliant IDs.
    #[serde(default)]
    pub dht_enforce_node_id: bool,
    /// BEP 42: Restrict DHT routing table to one node per IP.
    #[serde(default = "default_true")]
    pub dht_restrict_routing_ips: bool,
    /// Maximum number of BEP 44 items stored in the DHT (immutable + mutable).
    #[serde(default = "default_dht_max_items")]
    pub dht_max_items: usize,
    /// Lifetime of BEP 44 DHT items in seconds before expiry (default: 7200 = 2 hours).
    #[serde(default = "default_dht_item_lifetime")]
    pub dht_item_lifetime_secs: u64,
    /// Interval in seconds for periodic `sample_infohashes` queries (BEP 51).
    /// 0 = disabled (default). Non-zero enables background DHT indexing.
    #[serde(default = "default_dht_sample_interval")]
    pub dht_sample_infohashes_interval: u64,
    /// BEP 43: Run DHT in read-only mode. Read-only nodes can query the DHT
    /// but do not store data or announce. Other nodes should not add us to
    /// their routing tables. Useful for resource-constrained clients.
    #[serde(default)]
    pub dht_read_only: bool,

    // ── NAT tuning ──
    /// `UPnP` lease duration in seconds (default: 3600).
    #[serde(default = "default_upnp_lease")]
    pub upnp_lease_duration: u32,
    /// NAT-PMP mapping lifetime in seconds (default: 7200).
    #[serde(default = "default_natpmp_lifetime")]
    pub natpmp_lifetime: u32,

    // ── uTP tuning ──
    /// Maximum concurrent uTP connections (default: 256).
    #[serde(default = "default_utp_max_conns")]
    pub utp_max_connections: usize,

    // ── I2P ──
    /// Enable I2P anonymous network support (requires SAM bridge).
    #[serde(default)]
    pub enable_i2p: bool,
    /// SAM bridge hostname (default: "127.0.0.1").
    #[serde(default = "default_i2p_hostname")]
    pub i2p_hostname: String,
    /// SAM bridge port (default: 7656).
    #[serde(default = "default_i2p_port")]
    pub i2p_port: u16,
    /// Number of inbound I2P tunnels (1-16, default: 3).
    #[serde(default = "default_i2p_tunnel_quantity")]
    pub i2p_inbound_quantity: u8,
    /// Number of outbound I2P tunnels (1-16, default: 3).
    #[serde(default = "default_i2p_tunnel_quantity")]
    pub i2p_outbound_quantity: u8,
    /// Number of hops in inbound I2P tunnels (0-7, default: 3).
    #[serde(default = "default_i2p_tunnel_length")]
    pub i2p_inbound_length: u8,
    /// Number of hops in outbound I2P tunnels (0-7, default: 3).
    #[serde(default = "default_i2p_tunnel_length")]
    pub i2p_outbound_length: u8,
    /// Allow mixing I2P and clearnet peers in the same torrent.
    /// When false (default), I2P-enabled torrents only connect to I2P peers.
    #[serde(default)]
    pub allow_i2p_mixed: bool,

    // ── SSL torrents (M42) ──
    /// SSL listen port for SSL torrent incoming connections.
    /// 0 = disabled (no SSL listener). When set, a TLS listener is bound
    /// on this port for torrents with `ssl-cert` in their info dict.
    #[serde(default = "default_ssl_listen_port")]
    pub ssl_listen_port: u16,
    /// Path to the PEM-encoded certificate file for SSL torrent connections.
    /// If not set, a self-signed certificate is auto-generated on first use
    /// and stored in `resume_data_dir` (or a temp directory).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssl_cert_path: Option<PathBuf>,
    /// Path to the PEM-encoded private key file for SSL torrent connections.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssl_key_path: Option<PathBuf>,

    // ── Choking algorithms (M43) ──
    /// Algorithm for ranking peers during seed-mode choking.
    #[serde(default = "default_seed_choking_algorithm")]
    pub seed_choking_algorithm: SeedChokingAlgorithm,
    /// Algorithm for determining the number of unchoke slots.
    #[serde(default = "default_choking_algorithm")]
    pub choking_algorithm: ChokingAlgorithm,

    // ── Peer connections ──
    /// Maximum peer connections per torrent (default: 128). When `0`, falls back
    /// to `HARD_PEER_CEILING` (4096) — there is no "unlimited" mode, see Bug 7
    /// fix in v0.187.3.
    #[serde(default = "default_max_peers_per_torrent")]
    pub max_peers_per_torrent: usize,

    /// v0.187.3 / OV2 / 12A: seconds after a peer goes Live before Pass 0
    /// (zero-throughput) eviction can fire against it. Default 60. Prevents
    /// the proactive-eviction loop from culling peers still in `BitTorrent`
    /// slow-start. 0 = disable grace (legacy v0.187.2 behaviour).
    #[serde(default = "default_pass0_grace_secs")]
    pub pass0_grace_secs: u64,

    /// v0.187.3 / 3A: sliding-window cap on proactive evictions in any
    /// rolling 60s window. Default 30. The churn from the dogfood report
    /// ("130 → 20-50 every few seconds") shows what 0 looks like; this is
    /// the upper bound on how aggressive the eviction loop can be.
    #[serde(default = "default_proactive_evictions_per_minute_limit")]
    pub proactive_evictions_per_minute_limit: u32,

    /// v0.187.3: how long a Pass 0 eviction victim is blocked from
    /// reconnection. Default 600 (10 min). Was effectively 1800 (30 min)
    /// pre-v0.187.3 — shorter ban duration lets slow peers warm up and
    /// rejoin without forcing the user to restart.
    #[serde(default = "default_eviction_ban_duration_secs")]
    pub eviction_ban_duration_secs: u64,

    /// v0.187.3 / OV4: FIFO cap on the banned-peer set. Default 1024 (was
    /// 256). With the previous cap, busy swarms thrashed the ban set —
    /// peers fell off the back faster than ban duration could elapse.
    #[serde(default = "default_eviction_ban_set_cap")]
    pub eviction_ban_set_cap: usize,

    /// M133: Seconds without any wire message before disconnecting a peer.
    /// Matches rqbit's 10s read timeout. 0 = disabled. Default: 10.
    #[serde(default = "default_peer_read_timeout_secs")]
    pub peer_read_timeout_secs: u64,
    /// M133: Seconds before a stalled outgoing write disconnects a peer.
    /// 0 = disabled. Default: 10.
    #[serde(default = "default_peer_write_timeout_secs")]
    pub peer_write_timeout_secs: u64,

    /// M137: Data contribution timeout — seconds without receiving a Piece
    /// message before disconnecting. Set to 0 to disable. Default: 60.
    #[serde(default = "default_data_contribution_timeout")]
    pub data_contribution_timeout_secs: u64,

    /// M138: Maximum peers to evict per choke rotation tick (0 = disabled).
    #[serde(default = "default_choke_rotation_max_evictions")]
    pub choke_rotation_max_evictions: u32,

    /// M138: Maximum concurrent outbound peer connections (throttles connect ramp).
    #[serde(default = "default_max_concurrent_connects")]
    pub max_concurrent_connects: u16,

    /// M147: Seconds without TCP SYN-ACK before soft reap disconnects a connecting
    /// peer. Peers that have received SYN-ACK get the full `peer_connect_timeout`.
    #[serde(default = "default_connect_soft_timeout")]
    pub connect_soft_timeout: u64,

    /// M182: dispatch-channel backlog cap. The reader's `BackpressureQueue`
    /// spills up to this many items if `dispatch_tx` is full; on overflow
    /// the peer is disconnected. Lowering this value forces overflow under
    /// less load — the would-have-caught harness uses `cap = 2` to
    /// reproduce the M182 backlog-too-small regression class.
    #[serde(default = "default_dispatch_backlog_cap")]
    pub dispatch_backlog_cap: usize,

    /// M182: event-channel backlog cap. Same role as
    /// [`Self::dispatch_backlog_cap`] for the `event_tx` queue carrying
    /// `PeerEvent::*` from reader to `TorrentActor`.
    #[serde(default = "default_event_backlog_cap")]
    pub event_backlog_cap: usize,

    /// M187 A/B: use actor-centralised dispatch (true) or per-peer CAS dispatch (false).
    #[serde(default = "default_true")]
    pub use_actor_dispatch: bool,

    /// M178: Minimum milliseconds between `PeerEvent::WebSeedProgress` emissions
    /// per URL. Coalesces stat updates from `WebSeedTask` so the actor channel
    /// stays bounded under fast piece-fetch loops. Cold-start (first event for
    /// a URL) and error events bypass the throttle. `0` disables coalescing.
    #[serde(default = "default_web_seed_progress_throttle_ms")]
    pub web_seed_progress_throttle_ms: u64,

    // ── Security ──
    /// Enable SSRF mitigation: restrict localhost tracker paths, block
    /// public-to-private redirects, and reject query strings on local web seeds.
    #[serde(default = "default_true")]
    pub ssrf_mitigation: bool,
    /// Allow internationalised (non-ASCII) domain names in tracker/web seed URLs.
    #[serde(default)]
    pub allow_idna: bool,
    /// Require HTTPS for HTTP tracker announces (UDP trackers are unaffected).
    #[serde(default = "default_true")]
    pub validate_https_trackers: bool,
    /// Maximum BEP 9 metadata size in bytes that will be accepted from peers.
    /// Protects against OOM from peers claiming enormous metadata. Default: 4 MiB.
    #[serde(default = "default_max_metadata_size")]
    pub max_metadata_size: u64,
    /// Maximum wire protocol message size in bytes. Messages exceeding this are
    /// rejected by the codec. Default: 16 MiB.
    #[serde(default = "default_max_message_size")]
    pub max_message_size: usize,
    /// Maximum accepted piece length when adding a torrent. Rejects torrents
    /// with piece sizes above this limit. Default: 32 MiB.
    #[serde(default = "default_max_piece_length")]
    pub max_piece_length: u64,
    /// Maximum outstanding incoming requests per peer. When a peer sends more
    /// Request messages than this without them being served, excess requests
    /// are dropped. Default: 500.
    #[serde(default = "default_max_outstanding_requests")]
    pub max_outstanding_requests: usize,
    /// Maximum number of pieces simultaneously in-flight (downloaded but not
    /// yet verified). Caps memory usage for in-progress pieces. When the cap
    /// is reached, the piece selector only returns blocks from already-in-flight
    /// pieces. Default: 512.
    #[serde(default = "default_max_in_flight_pieces")]
    pub max_in_flight_pieces: usize,
    /// Timeout in seconds for outbound TCP peer connections.
    /// Default 10. Set to 0 to use the OS default (~2 minutes on Linux).
    #[serde(default = "default_peer_connect_timeout")]
    pub peer_connect_timeout: u64,
    /// DSCP (Differentiated Services Code Point) value for peer traffic sockets.
    /// Applied to TCP listeners, outbound TCP connections, uTP sockets, and UDP tracker sockets.
    /// Default 0x08 (CS1/scavenger — low-priority background). Set to 0 to disable DSCP marking.
    #[serde(default = "default_peer_dscp")]
    pub peer_dscp: u8,

    // ── Session Stats (M50) ──
    /// Interval in milliseconds between `SessionStatsAlert` emissions.
    /// Default 1000 (1 second). Set to 0 to disable periodic stats alerts.
    #[serde(default = "default_stats_report_interval")]
    pub stats_report_interval: u64,

    // ── Runtime tuning (M95) ──
    /// Number of tokio worker threads. Default: min(available cores, 8).
    /// Set to 0 to use tokio's default (= `available_parallelism()`).
    #[serde(default = "default_runtime_worker_threads")]
    pub runtime_worker_threads: usize,
    /// Pin tokio worker threads to CPU cores for cache locality. Default: true.
    #[serde(default = "default_true")]
    pub pin_cores: bool,

    // ── Lock diagnostics (M120) ──
    /// Warning threshold in milliseconds for lock hold duration.
    /// When a hot-path lock is held longer than this, a tracing warning is
    /// emitted. Set to 0 to disable timing entirely (zero overhead).
    /// Default: 50.
    #[serde(default = "default_lock_warn_threshold_ms")]
    pub lock_warn_threshold_ms: u64,

    // ── DHT bootstrap (M56) ──
    /// Previously saved DHT routing table nodes for fast bootstrap.
    /// These are prepended to the bootstrap node list on startup so that
    /// peer discovery starts instantly instead of bootstrapping from scratch.
    /// Runtime-injected, not serialized.
    #[serde(skip)]
    pub dht_saved_nodes: Vec<String>,
    /// BEP 42-compliant DHT node ID from previous session.
    /// Reusing the same ID avoids routing table regeneration on every startup.
    /// Runtime-injected, not serialized.
    #[serde(skip)]
    pub dht_node_id: Option<irontide_core::Id20>,

    /// qBittorrent `WebUI` v2 compatibility layer (M168).
    /// Opt-in; disabled by default. Enables *arr integration via qBt's de-facto
    /// API protocol. See `QbtCompatSettings` for full field documentation.
    #[serde(default)]
    pub qbt_compat: QbtCompatSettings,

    /// M170: Path to the qBt-compat category registry TOML file. When
    /// `None`, the default `$XDG_CONFIG_HOME/irontide/categories.toml`
    /// resolution is used (matching the `config.toml` convention).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category_registry_path: Option<PathBuf>,

    /// M171: Path to the qBt-compat tag registry TOML file. When `None`,
    /// the default `$XDG_CONFIG_HOME/irontide/tags.toml` resolution is
    /// used (matching the `category_registry_path` convention).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag_registry_path: Option<PathBuf>,

    // ── M226: Notifications / paths / watched folder / network ──────────
    /// M226: Fire an OS desktop notification when a torrent finishes
    /// downloading. Wired through `NotificationSink` in `notification.rs`.
    /// Default: false.
    #[serde(default)]
    pub notify_on_complete: bool,
    /// M226: Fire an OS desktop notification when a torrent enters an error
    /// state. Default: false.
    #[serde(default)]
    pub notify_on_error: bool,
    /// M226: Path to a program to run on torrent completion (qBt parity
    /// field). STORED ONLY — subprocess spawning is deferred to a future
    /// engine milestone (child-reaper, env scrubbing, exec safety audit
    /// pending). Default: None.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_complete_program: Option<PathBuf>,
    /// M226: Whether in-progress downloads use a separate directory before
    /// being moved to `download_dir` on completion. STORED ONLY — storage
    /// layer wiring deferred. Default: false.
    #[serde(default)]
    pub use_incomplete_dir: bool,
    /// M226: Directory for in-progress downloads (paired with
    /// `use_incomplete_dir`). STORED ONLY — storage layer wiring deferred.
    /// Must be absolute when `Some`. Default: None.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub incomplete_dir: Option<PathBuf>,
    /// M226: Default value for `AddTorrentParams.skip_checking` when the
    /// caller does not specify. STORED ONLY — add-torrent flow wiring is
    /// deferred to M227's GUI "Skip hash check" toggle. Default: false.
    #[serde(default)]
    pub default_skip_hash_check: bool,
    /// M226: Append `.!ut` to filenames during download (qBt convention to
    /// signal partial files to file managers). STORED ONLY — storage layer
    /// wiring deferred. Default: true (qBt parity).
    #[serde(default = "default_true")]
    pub incomplete_extension_enabled: bool,
    /// M226: Path to a folder to watch for new `.torrent` files; on detection
    /// the file is auto-added to the session. Wired through `watched_folder.rs`.
    /// Must be absolute when `Some`. Default: None.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub watched_folder: Option<PathBuf>,
    /// M226: After successfully adding a `.torrent` file from `watched_folder`,
    /// delete the source file. When false, the file is renamed to
    /// `<name>.duplicate` to prevent infinite-rescan (see plan §G2). Default:
    /// false (dry-run safe).
    #[serde(default)]
    pub delete_torrent_after_add: bool,
    /// M226: Whether to move completed torrents to `move_completed_to`.
    /// STORED ONLY — on-completion move logic deferred to a future engine
    /// milestone. Default: false.
    #[serde(default)]
    pub move_completed_enabled: bool,
    /// M226: Destination for completed torrents (paired with
    /// `move_completed_enabled`). STORED ONLY — move logic deferred. Must be
    /// absolute when `Some`. Default: None.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub move_completed_to: Option<PathBuf>,
    /// M226: Enable `HTTPS` for the qBt v2 `WebUI` listener. STORED ONLY —
    /// rustls integration deferred to a Phase O follow-on or Phase P
    /// milestone. Default: false.
    #[serde(default)]
    pub web_ui_https_enabled: bool,
    /// M226: Bind peer listeners to a specific network interface (qBt
    /// `current_network_interface`). STORED ONLY — `SO_BINDTODEVICE` wiring
    /// deferred. Default: None (use 0.0.0.0 / [::]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network_interface: Option<String>,
    /// M226: When `AddTorrentParams.paused` is `None`, this default decides
    /// whether new torrents start paused. Surfaced through the qBt v2
    /// `preferences.rs` GET projection as `start_paused_enabled`. Default:
    /// false.
    #[serde(default)]
    pub default_add_paused: bool,
}

/// qBittorrent `WebUI` v2 compatibility layer configuration.
///
/// # Security note (M172a)
/// As of M172a passwords are stored in PHC-format argon2id hashes in
/// [`Self::password_hash`]. The legacy [`Self::password`] field is retained
/// as a one-shot upgrade path — on daemon startup, if `password_hash` is
/// empty and `password` is non-empty, the daemon hashes the plaintext,
/// writes it back to [`Self::password_hash`] (zeroing the plaintext), and
/// atomically rewrites the config file via
/// [`crate::migrate_qbt_credentials`]. Fresh installs ship with
/// `password = ""` and a pre-hashed `password_hash` so no migration WARN
/// ever fires on a clean daemon.
///
/// File permissions (`0o600`) are still enforced by
/// [`irontide-config`'s `save_config_atomic`] as defence-in-depth — the PHC
/// hash is not directly reversible, but password-cracking dictionaries
/// remain feasible for weak passwords.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default)]
pub struct QbtCompatSettings {
    /// Master enable flag. When `false`, all `/api/v2/*` routes return 404
    /// (not 403) — the route must appear non-existent. Default: `true`
    /// (v0.172.1 flip, inverted from v0.168.0's security-through-invisibility
    /// default). Set `enabled = false` in `config.toml` under `[qbt_compat]`
    /// to opt out — the argon2id hash + brute-force ban + CSRF middleware
    /// (M172a) remain the primary defences; 404-on-disabled is defence-in-
    /// depth, not primary security.
    pub enabled: bool,
    /// Username required for qBt v2 login. Default: `"admin"` (qBt factory
    /// default). Must be non-empty when `enabled`.
    pub username: String,
    /// Argon2id PHC-format password hash (M172a). Example:
    /// `"$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>"`. OWASP-recommended
    /// parameters (m=19456 KiB, t=2, p=1).
    ///
    /// Fresh installs ship a non-empty default pre-hashing the factory
    /// "adminadmin" password so no migration WARN ever fires. The daemon
    /// rejects a malformed hash at validate-time.
    pub password_hash: String,
    /// Legacy plaintext password — **deprecated, migration-only**. Populated
    /// on config files written before M172a; the daemon rehashes and
    /// zeroizes this on next startup, leaving it permanently empty
    /// afterwards. New configs must ship with `password = ""` and a
    /// non-empty `password_hash`. Default: `""`.
    #[serde(default)]
    pub password: String,
    /// Version string returned by `GET /api/v2/app/version`. Must match the
    /// regex `^v\d+\.\d+(\.\d+)?(-\w+)?$`. Default: `"v5.1.4"`.
    pub spoof_app_version: String,
    /// Version string returned by `GET /api/v2/app/webapiVersion`. Must match
    /// the regex `^\d+\.\d+(\.\d+)?$` (no leading `v`). Default: `"2.11.4"`.
    pub spoof_webapi_version: String,
    /// Session cookie TTL in seconds. Bounds: `[60, 604_800]` (1 minute to
    /// 1 week). Default: `86_400` (24 hours).
    pub session_ttl_secs: u64,
    /// Maximum concurrent sessions. Prevents unbounded growth on login
    /// storms. Must be > 0. Default: `1024`.
    pub max_sessions: usize,
    /// Optional override for the global argon2 verification semaphore size
    /// (M172a G2). `None` means use the computed default
    /// `num_cpus::get() * 2`, clamped to `[2, 16]`. Rejects `Some(0)`. Peak
    /// memory under flood is bounded by `permits * 19 MiB`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_concurrent_argon2_ops: Option<u32>,

    /// v0.187.3 / 2A: TCP port the Web UI listens on. Single source of truth
    /// for the listen port; the legacy `[api].port` field is deprecated and
    /// auto-migrates to this value on config load with a one-time warning.
    /// Default: `9080`. Validated `> 0` when `enabled` is true.
    #[serde(default = "default_qbt_port")]
    pub port: u16,

    /// v0.187.3 / 2A: bind address the Web UI listens on. Single source of
    /// truth; the legacy `[api].bind` field is deprecated and auto-migrates.
    /// Default: `"127.0.0.1"`. Use `"0.0.0.0"` to expose on all interfaces
    /// (behind a reverse proxy strongly recommended).
    #[serde(default = "default_qbt_bind_address")]
    pub bind_address: String,

    // M172a Lane B (CSRF + reverse-proxy). Fields appended at the end of the
    // struct to keep merge conflicts minimal with parallel Lane C.
    /// M172a Lane B: enable Origin/Referer CSRF checks on mutating requests
    /// (POST/PATCH/PUT/DELETE) against `/webui/*` and `/api/v2/*`. When both
    /// headers are absent the request is allowed (server-to-server case;
    /// matches qBt and is what `*arr` clients need). Default: `true`.
    #[serde(default = "default_csrf_protection_enabled")]
    pub csrf_protection_enabled: bool,
    /// M172a Lane B: enable Host-header validation against Origin/Referer.
    /// When `csrf_protection_enabled` is `true` but this flag is `false`, the
    /// middleware short-circuits to allow. Useful for reverse-proxy setups
    /// whose proxy strips/rewrites the Host header in a non-trivial way.
    /// Default: `true`.
    #[serde(default = "default_host_header_validation_enabled")]
    pub host_header_validation_enabled: bool,
    /// M172a Lane B: when true, the CSRF middleware resolves the real client
    /// IP via the XFF trust-hop algorithm and validates Host against
    /// `X-Forwarded-Host` + `X-Forwarded-Proto` *only when* the peer matches
    /// one of the CIDRs in [`Self::web_ui_reverse_proxies_list`]. Untrusted
    /// peers fall back to direct Host validation — defence-in-depth against
    /// an attacker spoofing XFH from outside the proxy layer. Default:
    /// `false`.
    #[serde(default)]
    pub web_ui_reverse_proxy_enabled: bool,
    /// M172a Lane B: list of CIDRs trusted to supply `X-Forwarded-For` and
    /// `X-Forwarded-Host` headers. Each entry must parse as
    /// [`ipnet::IpNet`] (validated in [`Settings::validate`]). Empty list
    /// is valid but degrades reverse-proxy mode to "trust nobody" — the
    /// middleware falls back to direct Host validation in that case.
    ///
    /// **Narrow is safer.** Prefer single-host CIDRs like `172.20.0.5/32`
    /// over block-wide `172.16.0.0/12`. A too-wide mask means any client
    /// inside a trusted subnet can spoof `X-Forwarded-Host` and defeat
    /// CSRF protection; a `/32` binds trust to the exact proxy IP.
    #[serde(default)]
    pub web_ui_reverse_proxies_list: Vec<String>,

    // ── M172a Lane C: brute-force ban ──────────────────────────────────
    /// Maximum number of failed `auth/login` attempts from a single source
    /// IP before the IP is banned. Must be `> 0` unless
    /// [`Self::bypass_local_auth`] is `true`. Default: `5`.
    ///
    /// The counter resets on a successful login and on ban expiry.
    #[serde(default = "default_max_failed_auth_count")]
    pub max_failed_auth_count: u32,
    /// Ban duration (seconds) after hitting [`Self::max_failed_auth_count`].
    /// Bounds: `[60, 86_400]` (1 minute to 1 day). Default: `3_600` (1 hour).
    #[serde(default = "default_ban_duration_secs")]
    pub ban_duration_secs: u64,
    /// When `true`, any request whose resolved client IP is loopback
    /// (`127.0.0.0/8`, `::1`) bypasses authentication entirely and
    /// receives a valid SID cookie. Default: `false`.
    ///
    /// Combined with [`Self::bypass_auth_subnet_whitelist`] these provide
    /// the qBt-parity "local auth off" and "whitelisted subnets" escape
    /// hatches that `*arr` clients rely on.
    #[serde(default)]
    pub bypass_local_auth: bool,
    /// CIDR strings whose resolved client IP bypasses authentication
    /// entirely. Each string must parse as an [`ipnet::IpNet`]. Default:
    /// `vec![]`.
    ///
    /// Interpreted at router construction time and re-parsed on
    /// `setPreferences` apply so runtime reconfiguration flows through the
    /// shared `QbtState::bypass_auth_subnet_whitelist` `RwLock`.
    #[serde(default)]
    pub bypass_auth_subnet_whitelist: Vec<String>,
    /// Optional override for the brute-force-ban registry's LRU capacity.
    /// `None` means use the internal default of `10_000`. Rejects values
    /// `< 100`. Default: `None`.
    ///
    /// The registry retains its initial capacity until daemon restart —
    /// runtime changes only affect NEW entries admitted afterwards (see
    /// `FIXME` in the `classify_immediate` handler).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub brute_force_registry_capacity: Option<usize>,
}

fn default_csrf_protection_enabled() -> bool {
    true
}

fn default_host_header_validation_enabled() -> bool {
    true
}

// v0.187.3 / 2A: Web UI bind + port defaults. Match what previously lived
// on `[api]`.
fn default_qbt_port() -> u16 {
    9080
}

fn default_qbt_bind_address() -> String {
    "127.0.0.1".to_owned()
}

/// Default for [`QbtCompatSettings::max_failed_auth_count`].
#[must_use]
pub const fn default_max_failed_auth_count() -> u32 {
    5
}

/// Default for [`QbtCompatSettings::ban_duration_secs`].
#[must_use]
pub const fn default_ban_duration_secs() -> u64 {
    3_600
}

/// Argon2id PHC hash of the default "adminadmin" password (M172a A3).
///
/// Pre-computed once using the OWASP-recommended parameters with a
/// deterministic salt so round-tripping the default config across installs
/// is stable. The salt literal below is not a secret — it's supposed to be
/// recognisably the shipped default so operators know to rotate it.
///
/// The hash is regenerated by the [`tests::default_hash_roundtrips_admin_admin`]
/// test, which will fail with a suggested replacement value if parameters
/// or salt change.
pub const DEFAULT_ADMINADMIN_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$u3doPIM7ab7NlbMfhMFm6A$ctIAjFfl70eUfUsThdGcXICr0lcD6bEUilRujvnXLPg";

impl Default for QbtCompatSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            username: "admin".into(),
            password_hash: DEFAULT_ADMINADMIN_HASH.into(),
            password: String::new(),
            spoof_app_version: "v5.1.4".into(),
            spoof_webapi_version: "2.11.4".into(),
            session_ttl_secs: 86_400,
            max_sessions: 1024,
            max_concurrent_argon2_ops: None,
            // v0.187.3 / 2A: Web UI listen socket — single source of truth.
            port: default_qbt_port(),
            bind_address: default_qbt_bind_address(),
            // M172a Lane B defaults — CSRF on, host validation on, no proxy.
            csrf_protection_enabled: true,
            host_header_validation_enabled: true,
            web_ui_reverse_proxy_enabled: false,
            web_ui_reverse_proxies_list: Vec::new(),
            // M172a Lane C: brute-force ban defaults.
            max_failed_auth_count: default_max_failed_auth_count(),
            ban_duration_secs: default_ban_duration_secs(),
            bypass_local_auth: false,
            bypass_auth_subnet_whitelist: Vec::new(),
            brute_force_registry_capacity: None,
        }
    }
}

/// Outcome of a legacy-plaintext migration pass (M172a A3 / C2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QbtCredentialMigration {
    /// `password_hash` already present or nothing to migrate — no change.
    NoOp,
    /// Plaintext was hashed and written back into `password_hash`; the
    /// in-memory `password` was zeroed. The in-memory settings are mutated
    /// in place; callers should persist the mutation.
    Upgraded,
}

/// Hash `plaintext` with OWASP-recommended argon2id parameters and return the
/// PHC-format encoded string (M172a).
///
/// Pure CPU work — callers on async stacks should wrap in
/// `tokio::task::spawn_blocking` for anything other than a one-shot startup
/// migration. Login-time verification has its own concurrency limiter.
///
/// # Errors
///
/// Returns an error when the `argon2` crate's own hashing fails (empty
/// plaintext, OS entropy failure, internal parameter error).
pub fn hash_qbt_password(plaintext: &str) -> Result<String, QbtMigrationError> {
    use argon2::password_hash::{PasswordHasher, SaltString};
    use argon2::{Algorithm, Argon2, Params, Version};

    // `rand_core::OsRng` + its `getrandom` feature is our entropy source —
    // pulled in directly rather than via argon2's `rand` feature flag so the
    // hash path is decoupled from argon2 feature churn.
    let salt = SaltString::generate(&mut rand_core::OsRng);
    // OWASP cheat-sheet (argon2id): m=19_456 KiB, t=2, p=1. Output length
    // 32 bytes = 256 bits of key material.
    let params = Params::new(19_456, 2, 1, Some(32))
        .map_err(|e| QbtMigrationError::Hash(format!("argon2 params: {e}")))?;
    let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
    let hash = argon2
        .hash_password(plaintext.as_bytes(), &salt)
        .map_err(|e| QbtMigrationError::Hash(format!("argon2 hash: {e}")))?;
    Ok(hash.to_string())
}

/// Errors raised by [`migrate_qbt_credentials`].
#[derive(Debug, thiserror::Error)]
pub enum QbtMigrationError {
    /// argon2 hashing failure — returned by [`hash_qbt_password`].
    #[error("argon2 hash: {0}")]
    Hash(String),
}

/// One-shot legacy-plaintext → argon2id migration for
/// [`QbtCompatSettings`].
///
/// Semantics:
///
/// * `password_hash` non-empty → [`QbtCredentialMigration::NoOp`] (most
///   common path: fresh install, already-migrated install).
/// * `password_hash` empty **and** `password` non-empty → compute a fresh
///   PHC-format hash, assign it to `password_hash`, zero the plaintext via
///   [`zeroize::Zeroizing`] + `std::mem::take`, return
///   [`QbtCredentialMigration::Upgraded`].
/// * Both empty → [`QbtCredentialMigration::NoOp`]. Validation elsewhere
///   rejects an "enabled and both-empty" combo so we never authenticate an
///   unconfigured daemon.
///
/// This helper does *not* touch disk — callers pair it with
/// [`irontide_config::save_config_atomic`] (or a hand-rolled rewrite) to
/// persist the rewritten `Settings`. On migration failure the plaintext is
/// left untouched in memory so the daemon can still authenticate during
/// this boot; the migration will retry on the next startup.
///
/// # Errors
///
/// Propagates [`QbtMigrationError::Hash`] if argon2 hashing itself fails.
/// On `Err` the input is left unmodified so the caller's session-startup
/// path can continue with the plaintext still in memory.
pub fn migrate_qbt_credentials(
    qbt: &mut QbtCompatSettings,
) -> Result<QbtCredentialMigration, QbtMigrationError> {
    if !qbt.password_hash.is_empty() {
        return Ok(QbtCredentialMigration::NoOp);
    }
    if qbt.password.is_empty() {
        return Ok(QbtCredentialMigration::NoOp);
    }

    let hash = hash_qbt_password(&qbt.password)?;
    qbt.password_hash = hash;
    // C7: substantive zeroize — the Settings struct has a longer in-memory
    // lifetime than the request path, so scrubbing the plaintext here
    // actually removes a residual copy rather than theatre.
    let _drain = zeroize::Zeroizing::new(std::mem::take(&mut qbt.password));
    Ok(QbtCredentialMigration::Upgraded)
}

/// Validate an app-version string (e.g. `v5.1.4` or `v4.6.4-rc1`).
fn is_valid_app_version(s: &str) -> bool {
    let Some(rest) = s.strip_prefix('v') else {
        return false;
    };
    // Split optional "-suffix" (pre-release tag like rc1, beta2) from the numeric core.
    let (core, suffix_ok) = match rest.split_once('-') {
        Some((core, suffix)) => (
            core,
            !suffix.is_empty() && suffix.chars().all(|c| c.is_ascii_alphanumeric()),
        ),
        None => (rest, true),
    };
    if !suffix_ok {
        return false;
    }
    is_valid_dotted_numeric(core)
}

/// Validate a webapi-version string (e.g. `2.11.4`).
fn is_valid_webapi_version(s: &str) -> bool {
    is_valid_dotted_numeric(s)
}

/// Accepts two or three non-empty dot-separated numeric segments.
fn is_valid_dotted_numeric(s: &str) -> bool {
    let parts: Vec<&str> = s.split('.').collect();
    if !(2..=3).contains(&parts.len()) {
        return false;
    }
    parts
        .iter()
        .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            // General
            listen_port: 42020,
            randomize_port_on_startup: false,
            download_dir: PathBuf::from("."),
            max_torrents: 100,
            resume_data_dir: None,
            save_resume_interval_secs: 300,
            // Protocol features
            enable_dht: true,
            enable_pex: true,
            enable_lsd: true,
            enable_fast_extension: true,
            enable_utp: true,
            enable_upnp: true,
            enable_natpmp: true,
            enable_ipv6: true,
            enable_web_seed: true,
            enable_holepunch: true,
            enable_bep40_eviction: true,
            enable_diagnostic_counters: false,
            encryption_mode: EncryptionMode::Disabled,
            anonymous_mode: false,
            external_ip: None,
            // Seeding
            seed_ratio_limit: None,
            seed_time_limit_secs: None,
            inactive_seed_time_limit_secs: None,
            max_ratio_action: MaxRatioAction::Pause,
            create_subfolder: true,
            auto_manage_torrents: false,
            queueing_enabled: false,
            default_super_seeding: false,
            default_share_mode: false,
            upload_only_announce: true,
            // Rate limiting
            upload_rate_limit: 0,
            download_rate_limit: 0,
            tcp_upload_rate_limit: 0,
            tcp_download_rate_limit: 0,
            utp_upload_rate_limit: 0,
            utp_download_rate_limit: 0,
            auto_upload_slots: true,
            auto_upload_slots_min: 2,
            auto_upload_slots_max: 20,
            max_upload_slots_global: -1,
            max_upload_slots_per_torrent: 4,
            max_connections_global: -1,
            max_uploads_per_torrent: -1,
            alt_download_rate_limit: 0,
            alt_upload_rate_limit: 0,
            alt_speed_enabled: false,
            alt_speed_schedule_enabled: false,
            alt_speed_schedule_from: 0,
            alt_speed_schedule_to: 0,
            alt_speed_schedule_days: 0,
            rate_limit_includes_overhead: true,
            rate_limit_utp: true,
            rate_limit_lan: false,
            mixed_mode_algorithm: MixedModeAlgorithm::PeerProportional,
            // Queue management
            active_downloads: 3,
            active_seeds: 5,
            active_limit: 500,
            active_checking: 3,
            dont_count_slow_torrents: true,
            inactive_down_rate: 2048,
            inactive_up_rate: 2048,
            auto_manage_interval: 30,
            auto_manage_startup: 60,
            auto_manage_prefer_seeds: false,
            queue_rate_ewma_alpha: 0.3,
            seed_queue_min_active_secs: 1800,
            // Alerts
            alert_mask: AlertCategory::ALL,
            alert_channel_size: 1024,
            // Smart banning
            smart_ban_max_failures: 3,
            smart_ban_parole: true,
            // Disk I/O
            disk_io_threads: default_disk_io_threads(),
            max_blocking_threads: default_max_blocking_threads(),
            storage_mode: StorageMode::Auto,
            preallocate_mode: None,
            disk_cache_size: 16 * 1024 * 1024,
            disk_write_cache_ratio: 0.5,
            disk_channel_capacity: 512,
            buffer_pool_capacity: 64 * 1024 * 1024,
            enable_mlock: cfg!(unix),
            io_uring_sq_depth: 256,
            io_uring_direct_io: false,
            filesystem_direct_io: false,
            io_uring_batch_threshold: 4,
            iocp_concurrent_threads: 0,
            iocp_direct_io: false,
            // Hashing & piece picking
            hashing_threads: default_hashing_threads(),
            max_request_queue_depth: 250,
            initial_queue_depth: 128,
            request_queue_time: 3.0,
            block_request_timeout_secs: 60,
            max_concurrent_stream_reads: 8,
            auto_sequential: true,
            steal_threshold_ratio: 10.0,
            use_block_stealing: true,
            steal_stale_piece_secs: 2,
            steal_threshold_endgame: 3.0,
            fixed_pipeline_depth: 128,
            strict_end_game: true,
            max_web_seeds: 4,
            web_seed_retry_base_secs: 10,
            web_seed_retry_factor: 6,
            web_seed_retry_cap_secs: 3600,
            web_seed_max_failures: 10,
            initial_picker_threshold: 4,
            whole_pieces_threshold: 20,
            snub_timeout_secs: 15,
            readahead_pieces: 8,
            streaming_timeout_escalation: true,
            // Piece picker enhancements (M44)
            piece_extent_affinity: true,
            suggest_mode: true,
            max_suggest_pieces: 16,
            predictive_piece_announce_ms: 0,
            // Proxy
            proxy: ProxyConfig::default(),
            force_proxy: false,
            // IP Filtering
            ip_filter_enabled: false,
            ip_filter_path: String::new(),
            ip_filter_auto_refresh: false,
            apply_ip_filter_to_trackers: true,
            // DHT tuning
            dht_queries_per_second: 50,
            dht_query_timeout_secs: 5,
            dht_enforce_node_id: false,
            dht_restrict_routing_ips: true,
            dht_max_items: 700,
            dht_item_lifetime_secs: 7200,
            dht_sample_infohashes_interval: 0,
            dht_read_only: false,
            // NAT tuning
            upnp_lease_duration: 3600,
            natpmp_lifetime: 7200,
            // uTP tuning
            utp_max_connections: 256,
            // I2P
            enable_i2p: false,
            i2p_hostname: "127.0.0.1".into(),
            i2p_port: 7656,
            i2p_inbound_quantity: 3,
            i2p_outbound_quantity: 3,
            i2p_inbound_length: 3,
            i2p_outbound_length: 3,
            allow_i2p_mixed: false,
            // SSL torrents
            ssl_listen_port: 0,
            ssl_cert_path: None,
            ssl_key_path: None,
            // Choking algorithms
            seed_choking_algorithm: SeedChokingAlgorithm::FastestUpload,
            choking_algorithm: ChokingAlgorithm::FixedSlots,
            // Peer connections
            max_peers_per_torrent: 128,
            // v0.187.3 eviction policy (see field doc-comments)
            pass0_grace_secs: 60,
            proactive_evictions_per_minute_limit: 30,
            eviction_ban_duration_secs: 600,
            eviction_ban_set_cap: 1024,
            peer_read_timeout_secs: 10,
            peer_write_timeout_secs: 10,
            data_contribution_timeout_secs: 0,
            choke_rotation_max_evictions: 0,
            max_concurrent_connects: 128,
            connect_soft_timeout: 3,
            dispatch_backlog_cap: 8,
            event_backlog_cap: 32,
            use_actor_dispatch: true,
            web_seed_progress_throttle_ms: 250,
            // Security
            ssrf_mitigation: true,
            allow_idna: false,
            validate_https_trackers: true,
            max_metadata_size: 4 * 1024 * 1024,
            max_message_size: 16 * 1024 * 1024,
            max_piece_length: 32 * 1024 * 1024,
            max_outstanding_requests: 500,
            max_in_flight_pieces: 512,
            peer_connect_timeout: 10,
            peer_dscp: 0x08,
            // Session Stats (M50)
            stats_report_interval: 1000,
            // Runtime tuning (M95)
            runtime_worker_threads: default_runtime_worker_threads(),
            pin_cores: true,
            // Lock diagnostics (M120)
            lock_warn_threshold_ms: 50,
            // DHT bootstrap (M56)
            dht_saved_nodes: Vec::new(),
            dht_node_id: None,
            // qBt v2 compatibility (M168)
            qbt_compat: QbtCompatSettings::default(),
            // M170: default to None → resolved via XDG to
            // `$XDG_CONFIG_HOME/irontide/categories.toml` at registry load time.
            category_registry_path: None,
            // M171: default to None → resolved via XDG to
            // `$XDG_CONFIG_HOME/irontide/tags.toml` at registry load time.
            tag_registry_path: None,
            // M226: notifications + paths + watched folder + network
            notify_on_complete: false,
            notify_on_error: false,
            on_complete_program: None,
            use_incomplete_dir: false,
            incomplete_dir: None,
            default_skip_hash_check: false,
            incomplete_extension_enabled: true,
            watched_folder: None,
            delete_torrent_after_add: false,
            move_completed_enabled: false,
            move_completed_to: None,
            web_ui_https_enabled: false,
            network_interface: None,
            default_add_paused: false,
        }
    }
}

impl Settings {
    /// Preset for constrained/embedded environments.
    #[must_use]
    pub fn min_memory() -> Self {
        Self {
            disk_cache_size: 8 * 1024 * 1024,
            buffer_pool_capacity: 16 * 1024 * 1024,
            max_torrents: 20,
            max_peers_per_torrent: 30,
            active_downloads: 1,
            active_seeds: 2,
            active_limit: 10,
            alert_channel_size: 256,
            utp_max_connections: 64,
            max_request_queue_depth: 50,
            initial_queue_depth: 16,
            max_concurrent_stream_reads: 2,
            hashing_threads: 1,
            disk_io_threads: 1,
            dht_max_items: 100,
            max_in_flight_pieces: 32,
            fixed_pipeline_depth: 32,
            ..Self::default()
        }
    }

    /// Preset for desktop/server environments with ample resources.
    #[must_use]
    pub fn high_performance() -> Self {
        Self {
            disk_cache_size: 256 * 1024 * 1024,
            buffer_pool_capacity: 256 * 1024 * 1024,
            max_torrents: 2000,
            max_peers_per_torrent: 200,
            active_downloads: 30,
            active_seeds: 100,
            active_limit: 2000,
            alert_channel_size: 4096,
            utp_max_connections: 1024,
            max_request_queue_depth: 1000,
            initial_queue_depth: 256,
            max_concurrent_stream_reads: 32,
            hashing_threads: 4,
            disk_io_threads: 8,
            auto_upload_slots_max: 100,
            suggest_mode: true,
            steal_threshold_ratio: 5.0,
            steal_threshold_endgame: 2.0,
            use_block_stealing: true,
            max_in_flight_pieces: 512,
            ..Self::default()
        }
    }

    /// Validate settings. Returns error on the first invalid combination found.
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails.
    pub fn validate(&self) -> crate::Result<()> {
        use crate::proxy::ProxyType;

        if self.force_proxy && self.proxy.proxy_type == ProxyType::None {
            return Err(crate::Error::InvalidSettings(
                "force_proxy is enabled but no proxy type is configured".into(),
            ));
        }

        if self.active_downloads > 0
            && self.active_limit > 0
            && self.active_downloads > self.active_limit
        {
            return Err(crate::Error::InvalidSettings(
                "active_downloads exceeds active_limit".into(),
            ));
        }

        if self.active_seeds > 0 && self.active_limit > 0 && self.active_seeds > self.active_limit {
            return Err(crate::Error::InvalidSettings(
                "active_seeds exceeds active_limit".into(),
            ));
        }

        if !(0.0..=1.0).contains(&self.disk_write_cache_ratio) {
            return Err(crate::Error::InvalidSettings(
                "disk_write_cache_ratio must be between 0.0 and 1.0".into(),
            ));
        }

        if self.disk_cache_size < 1024 * 1024 {
            return Err(crate::Error::InvalidSettings(
                "disk_cache_size must be at least 1 MiB".into(),
            ));
        }

        if self.hashing_threads == 0 {
            return Err(crate::Error::InvalidSettings(
                "hashing_threads must be at least 1".into(),
            ));
        }

        // M226: paired-field validation + path-shape validation.
        if self.use_incomplete_dir && self.incomplete_dir.is_none() {
            return Err(crate::Error::InvalidSettings(
                "incomplete_dir must be set when use_incomplete_dir=true".into(),
            ));
        }
        if self.move_completed_enabled && self.move_completed_to.is_none() {
            return Err(crate::Error::InvalidSettings(
                "move_completed_to must be set when move_completed_enabled=true".into(),
            ));
        }
        // M226 F11: every Option<PathBuf> path-field must be absolute when Some
        // so silent breakage at runtime is replaced with a config-load error.
        for (name, opt) in [
            ("watched_folder", self.watched_folder.as_ref()),
            ("incomplete_dir", self.incomplete_dir.as_ref()),
            ("move_completed_to", self.move_completed_to.as_ref()),
        ] {
            if let Some(p) = opt
                && !p.is_absolute()
            {
                return Err(crate::Error::InvalidSettings(format!(
                    "{name} must be an absolute path, got {}",
                    p.display()
                )));
            }
        }
        // M226 H6: reject obviously-dangerous watched_folder paths. When
        // delete_torrent_after_add=true a typo here could shred system files.
        if let Some(p) = self.watched_folder.as_ref() {
            const DENY: &[&str] = &[
                "/", "/etc", "/usr", "/bin", "/sbin", "/lib", "/lib64", "/boot", "/sys",
                "/proc", "/dev", "/run", "/var/lib", "/var/log",
            ];
            let s = p.to_string_lossy();
            if DENY.iter().any(|d| s == *d) {
                return Err(crate::Error::InvalidSettings(format!(
                    "watched_folder rejected: {} is a system path (would risk shredding system files if delete_torrent_after_add=true)",
                    p.display()
                )));
            }
            if let Some(home) = std::env::var_os("HOME") {
                let home_path = PathBuf::from(home);
                if p == &home_path {
                    return Err(crate::Error::InvalidSettings(format!(
                        "watched_folder cannot be $HOME ({}) — too broad to be a torrent dropbox; pick a dedicated subdirectory",
                        p.display()
                    )));
                }
            }
        }

        // M224: max_uploads_per_torrent uses `-1` sentinel for unlimited
        // (matches max_connections_global precedent). `0` is rejected — qBt's
        // wire format accepts `0` on some GET paths to mean unlimited, but
        // qBt's setPreferences accepts `-1`; we mirror the `-1` convention
        // for input and reject `0` as a likely wire-format mistake.
        if self.max_uploads_per_torrent == 0 || self.max_uploads_per_torrent < -1 {
            return Err(crate::Error::InvalidSettings(
                "max_uploads_per_torrent must be -1 (unlimited) or >= 1".into(),
            ));
        }

        if self.disk_io_threads == 0 {
            return Err(crate::Error::InvalidSettings(
                "disk_io_threads must be at least 1".into(),
            ));
        }

        if self.max_blocking_threads == 0 {
            return Err(crate::Error::InvalidSettings(
                "max_blocking_threads must be at least 1".into(),
            ));
        }

        if self.default_share_mode && !self.enable_fast_extension {
            return Err(crate::Error::InvalidSettings(
                "share_mode requires enable_fast_extension for RejectRequest messages".into(),
            ));
        }

        // SSL cert/key must both be set or both absent
        if self.ssl_cert_path.is_some() != self.ssl_key_path.is_some() {
            return Err(crate::Error::InvalidSettings(
                "ssl_cert_path and ssl_key_path must both be set or both absent".into(),
            ));
        }

        if self.enable_i2p {
            if self.i2p_inbound_quantity == 0 || self.i2p_inbound_quantity > 16 {
                return Err(crate::Error::InvalidSettings(
                    "i2p_inbound_quantity must be 1-16".into(),
                ));
            }
            if self.i2p_outbound_quantity == 0 || self.i2p_outbound_quantity > 16 {
                return Err(crate::Error::InvalidSettings(
                    "i2p_outbound_quantity must be 1-16".into(),
                ));
            }
            if self.i2p_inbound_length > 7 {
                return Err(crate::Error::InvalidSettings(
                    "i2p_inbound_length must be 0-7".into(),
                ));
            }
            if self.i2p_outbound_length > 7 {
                return Err(crate::Error::InvalidSettings(
                    "i2p_outbound_length must be 0-7".into(),
                ));
            }
        }

        if self.runtime_worker_threads > 256 {
            return Err(crate::Error::InvalidSettings(
                "runtime_worker_threads must be at most 256".into(),
            ));
        }

        // qBt v2 compatibility settings (M168, extended M172a) — only validated
        // when enabled, so projects with qbt_compat disabled can leave bogus
        // defaults in place.
        if self.qbt_compat.enabled {
            if self.qbt_compat.username.is_empty() {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.username must not be empty when enabled".into(),
                ));
            }
            // M172a: either the PHC hash is present, or the legacy plaintext
            // is set to a non-trivial value (for the upcoming migration).
            // Forbidding both-empty prevents an "anyone can log in" misconfig.
            if self.qbt_compat.password_hash.is_empty() {
                if self.qbt_compat.password.len() < 8 {
                    return Err(crate::Error::InvalidSettings(
                        "qbt_compat: either password_hash must be set OR \
                         password must be at least 8 characters (legacy upgrade path)"
                            .into(),
                    ));
                }
            } else if !self.qbt_compat.password_hash.starts_with("$argon2id$") {
                // M172a: reject unknown-scheme hashes early so an operator
                // copy-pasting a bcrypt or plaintext into `password_hash`
                // doesn't silently authenticate every request.
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.password_hash must be an argon2id PHC string \
                     starting with `$argon2id$`"
                        .into(),
                ));
            }
            if let Some(0) = self.qbt_compat.max_concurrent_argon2_ops {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.max_concurrent_argon2_ops must be > 0 when set".into(),
                ));
            }
            if !is_valid_app_version(&self.qbt_compat.spoof_app_version) {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.spoof_app_version must match vN.N[.N][-suffix] (e.g. v5.1.4)"
                        .into(),
                ));
            }
            if !is_valid_webapi_version(&self.qbt_compat.spoof_webapi_version) {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.spoof_webapi_version must match N.N[.N] (e.g. 2.11.4)".into(),
                ));
            }
            if !(60..=604_800).contains(&self.qbt_compat.session_ttl_secs) {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.session_ttl_secs must be in [60, 604800]".into(),
                ));
            }
            if self.qbt_compat.max_sessions == 0 {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.max_sessions must be at least 1".into(),
                ));
            }
            // M172a Lane B: every CIDR in the reverse-proxy list must parse as
            // an `ipnet::IpNet`. An empty list is valid (middleware falls back
            // to direct-Host validation). The parse failure mode names the
            // offending entry so operators can fix the config without a diff.
            for entry in &self.qbt_compat.web_ui_reverse_proxies_list {
                if entry.parse::<ipnet::IpNet>().is_err() {
                    return Err(crate::Error::InvalidSettings(format!(
                        "qbt_compat.web_ui_reverse_proxies_list: invalid CIDR '{entry}'"
                    )));
                }
            }

            // M172a Lane C: brute-force ban validation.
            // max_failed_auth_count must be > 0 unless the operator has
            // explicitly enabled bypass_local_auth (in which case loopback
            // requests skip the check entirely and the counter is inert for
            // the only caller class that could trip it).
            if self.qbt_compat.max_failed_auth_count == 0 && !self.qbt_compat.bypass_local_auth {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.max_failed_auth_count must be > 0 when bypass_local_auth is false"
                        .into(),
                ));
            }
            if !(60..=86_400).contains(&self.qbt_compat.ban_duration_secs) {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.ban_duration_secs must be in [60, 86400]".into(),
                ));
            }
            for cidr in &self.qbt_compat.bypass_auth_subnet_whitelist {
                if cidr.parse::<ipnet::IpNet>().is_err() {
                    return Err(crate::Error::InvalidSettings(format!(
                        "qbt_compat.bypass_auth_subnet_whitelist: invalid CIDR `{cidr}`"
                    )));
                }
            }
            if let Some(cap) = self.qbt_compat.brute_force_registry_capacity
                && cap < 100
            {
                return Err(crate::Error::InvalidSettings(
                    "qbt_compat.brute_force_registry_capacity must be at least 100".into(),
                ));
            }
        }

        Ok(())
    }
}

// ── Sub-config conversions ───────────────────────────────────────────

impl From<&Settings> for crate::disk::DiskConfig {
    fn from(s: &Settings) -> Self {
        Self {
            io_threads: s.disk_io_threads,
            storage_mode: s.storage_mode,
            cache_size: s.disk_cache_size,
            write_cache_ratio: s.disk_write_cache_ratio,
            channel_capacity: s.disk_channel_capacity,
            buffer_pool_capacity: s.buffer_pool_capacity,
            enable_mlock: s.enable_mlock,
            lock_warn_threshold_ms: s.lock_warn_threshold_ms,
            io_uring_sq_depth: s.io_uring_sq_depth,
            io_uring_direct_io: s.io_uring_direct_io,
            filesystem_direct_io: s.filesystem_direct_io,
            io_uring_batch_threshold: s.io_uring_batch_threshold,
            iocp_concurrent_threads: s.iocp_concurrent_threads,
            iocp_direct_io: s.iocp_direct_io,
        }
    }
}

impl From<&Settings> for crate::ban::BanConfig {
    fn from(s: &Settings) -> Self {
        Self {
            max_failures: s.smart_ban_max_failures,
            use_parole: s.smart_ban_parole,
        }
    }
}

impl Settings {
    pub(crate) fn to_dht_config(&self) -> irontide_dht::DhtConfig {
        let default = irontide_dht::DhtConfig::default();
        let mut bootstrap = self.dht_saved_nodes.clone();
        bootstrap.extend(default.bootstrap_nodes.iter().cloned());
        irontide_dht::DhtConfig {
            bootstrap_nodes: bootstrap,
            own_id: self.dht_node_id,
            queries_per_second: self.dht_queries_per_second,
            query_timeout: std::time::Duration::from_secs(self.dht_query_timeout_secs),
            enforce_node_id: self.dht_enforce_node_id,
            restrict_routing_ips: self.dht_restrict_routing_ips,
            dht_max_items: self.dht_max_items,
            dht_item_lifetime_secs: self.dht_item_lifetime_secs,
            state_dir: self.resume_data_dir.clone(),
            read_only_mode: self.dht_read_only,
            ..default
        }
    }

    pub(crate) fn to_dht_config_v6(&self) -> irontide_dht::DhtConfig {
        let default = irontide_dht::DhtConfig::default_v6();
        let mut bootstrap = self.dht_saved_nodes.clone();
        bootstrap.extend(default.bootstrap_nodes.iter().cloned());
        irontide_dht::DhtConfig {
            bootstrap_nodes: bootstrap,
            queries_per_second: self.dht_queries_per_second,
            query_timeout: std::time::Duration::from_secs(self.dht_query_timeout_secs),
            enforce_node_id: self.dht_enforce_node_id,
            restrict_routing_ips: self.dht_restrict_routing_ips,
            dht_max_items: self.dht_max_items,
            dht_item_lifetime_secs: self.dht_item_lifetime_secs,
            state_dir: self.resume_data_dir.clone(),
            read_only_mode: self.dht_read_only,
            ..default
        }
    }

    pub(crate) fn to_nat_config(&self) -> irontide_nat::NatConfig {
        irontide_nat::NatConfig {
            enable_upnp: self.enable_upnp,
            enable_natpmp: self.enable_natpmp,
            upnp_lease_duration: self.upnp_lease_duration,
            natpmp_lifetime: self.natpmp_lifetime,
        }
    }

    pub(crate) fn to_utp_config(&self, port: u16) -> irontide_utp::UtpConfig {
        irontide_utp::UtpConfig {
            bind_addr: std::net::SocketAddr::from(([0, 0, 0, 0], port)),
            max_connections: self.utp_max_connections,
            dscp: self.peer_dscp,
        }
    }

    pub(crate) fn to_utp_config_v6(&self, port: u16) -> irontide_utp::UtpConfig {
        irontide_utp::UtpConfig {
            bind_addr: std::net::SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, port)),
            max_connections: self.utp_max_connections,
            dscp: self.peer_dscp,
        }
    }

    /// Build a `SamTunnelConfig` from the I2P-related settings.
    pub(crate) fn to_sam_tunnel_config(&self) -> crate::i2p::SamTunnelConfig {
        crate::i2p::SamTunnelConfig {
            inbound_quantity: self.i2p_inbound_quantity,
            outbound_quantity: self.i2p_outbound_quantity,
            inbound_length: self.i2p_inbound_length,
            outbound_length: self.i2p_outbound_length,
        }
    }
}

// ── PartialEq (manual — f32/f64 fields need special handling) ────────


// ── Tests ────────────────────────────────────────────────────────────

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

    #[test]
    fn default_settings_values() {
        let s = Settings::default();
        assert_eq!(s.listen_port, 42020);
        assert_eq!(s.download_dir, PathBuf::from("."));
        assert_eq!(s.max_torrents, 100);
        assert!(s.resume_data_dir.is_none());
        assert_eq!(s.save_resume_interval_secs, 300);
        assert!(s.enable_dht);
        assert!(s.enable_pex);
        assert!(s.enable_lsd);
        assert!(s.enable_fast_extension);
        assert!(s.enable_utp);
        assert!(s.enable_upnp);
        assert!(s.enable_natpmp);
        assert!(s.enable_ipv6);
        assert!(s.enable_web_seed);
        assert_eq!(s.encryption_mode, EncryptionMode::Disabled);
        assert!(!s.anonymous_mode);
        assert!(s.seed_ratio_limit.is_none());
        assert!(!s.default_super_seeding);
        assert!(!s.default_share_mode);
        assert!(s.upload_only_announce);
        assert_eq!(s.upload_rate_limit, 0);
        assert_eq!(s.download_rate_limit, 0);
        assert!(s.auto_upload_slots);
        assert_eq!(s.active_downloads, 3);
        assert_eq!(s.active_seeds, 5);
        assert_eq!(s.active_limit, 500);
        assert_eq!(s.active_checking, 3);
        assert!(s.dont_count_slow_torrents);
        assert_eq!(s.alert_mask, AlertCategory::ALL);
        assert_eq!(s.alert_channel_size, 1024);
        assert_eq!(s.smart_ban_max_failures, 3);
        assert!(s.smart_ban_parole);
        assert_eq!(s.disk_io_threads, default_disk_io_threads());
        assert_eq!(s.max_blocking_threads, default_max_blocking_threads());
        assert_eq!(s.storage_mode, StorageMode::Auto);
        assert_eq!(s.disk_cache_size, 16 * 1024 * 1024);
        assert!((s.disk_write_cache_ratio - 0.5).abs() < f32::EPSILON);
        assert_eq!(s.disk_channel_capacity, 512);
        assert_eq!(s.hashing_threads, default_hashing_threads());
        assert_eq!(s.max_request_queue_depth, 250);
        assert_eq!(s.initial_queue_depth, 128);
        assert!((s.request_queue_time - 3.0).abs() < f64::EPSILON);
        assert_eq!(s.block_request_timeout_secs, 60);
        assert_eq!(s.max_concurrent_stream_reads, 8);
        assert!(!s.force_proxy);
        assert!(s.apply_ip_filter_to_trackers);
        assert_eq!(s.dht_queries_per_second, 50);
        assert_eq!(s.dht_query_timeout_secs, 5);
        assert!(!s.dht_enforce_node_id);
        assert!(s.dht_restrict_routing_ips);
        assert_eq!(s.upnp_lease_duration, 3600);
        assert_eq!(s.natpmp_lifetime, 7200);
        assert_eq!(s.utp_max_connections, 256);
        assert_eq!(s.mixed_mode_algorithm, MixedModeAlgorithm::PeerProportional);
        assert!(s.auto_sequential);
        assert!(s.strict_end_game);
        assert_eq!(s.max_web_seeds, 4);
        assert_eq!(s.initial_picker_threshold, 4);
        assert_eq!(s.whole_pieces_threshold, 20);
        assert_eq!(s.snub_timeout_secs, 15);
        assert_eq!(s.readahead_pieces, 8);
        assert!(s.streaming_timeout_escalation);
        assert_eq!(s.max_peers_per_torrent, 128);
        assert_eq!(s.runtime_worker_threads, default_runtime_worker_threads());
        assert!(s.pin_cores);
    }

    #[test]
    fn min_memory_preset() {
        let s = Settings::min_memory();
        assert_eq!(s.disk_cache_size, 8 * 1024 * 1024);
        assert_eq!(s.max_torrents, 20);
        assert_eq!(s.max_peers_per_torrent, 30);
        assert_eq!(s.active_downloads, 1);
        assert_eq!(s.active_seeds, 2);
        assert_eq!(s.active_limit, 10);
        assert_eq!(s.alert_channel_size, 256);
        assert_eq!(s.utp_max_connections, 64);
        assert_eq!(s.max_request_queue_depth, 50);
        assert_eq!(s.initial_queue_depth, 16);
        assert_eq!(s.max_concurrent_stream_reads, 2);
        assert_eq!(s.hashing_threads, 1);
        assert_eq!(s.disk_io_threads, 1);
    }

    #[test]
    fn high_performance_preset() {
        let s = Settings::high_performance();
        assert_eq!(s.disk_cache_size, 256 * 1024 * 1024);
        assert_eq!(s.max_torrents, 2000);
        assert_eq!(s.max_peers_per_torrent, 200);
        assert_eq!(s.active_downloads, 30);
        assert_eq!(s.active_seeds, 100);
        assert_eq!(s.active_limit, 2000);
        assert_eq!(s.alert_channel_size, 4096);
        assert_eq!(s.utp_max_connections, 1024);
        assert_eq!(s.max_request_queue_depth, 1000);
        assert_eq!(s.initial_queue_depth, 256);
        assert_eq!(s.max_concurrent_stream_reads, 32);
        assert_eq!(s.hashing_threads, 4);
        assert_eq!(s.disk_io_threads, 8);
        assert_eq!(s.auto_upload_slots_max, 100);
    }

    #[test]
    fn json_round_trip() {
        let original = Settings::default();
        let json = serde_json::to_string(&original).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn json_round_trip_presets() {
        // Verify all presets survive JSON serialization
        for original in [Settings::min_memory(), Settings::high_performance()] {
            let json = serde_json::to_string(&original).unwrap();
            let decoded: Settings = serde_json::from_str(&json).unwrap();
            assert_eq!(original, decoded);
        }
    }

    #[test]
    fn json_missing_fields_use_defaults() {
        // An empty JSON object should deserialize to defaults (via serde(default))
        let decoded: Settings = serde_json::from_str("{}").unwrap();
        assert_eq!(decoded, Settings::default());
    }

    // M171 D1a — seed-time limit Settings fields
    #[test]
    fn seed_time_limits_default_none() {
        let s = Settings::default();
        assert!(s.seed_time_limit_secs.is_none());
        assert!(s.inactive_seed_time_limit_secs.is_none());
    }

    #[test]
    fn seed_time_limits_round_trip_json() {
        let s = Settings {
            seed_time_limit_secs: Some(3600),
            inactive_seed_time_limit_secs: Some(1800),
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.seed_time_limit_secs, Some(3600));
        assert_eq!(decoded.inactive_seed_time_limit_secs, Some(1800));
    }

    #[test]
    fn seed_time_limits_skipped_when_none() {
        // `skip_serializing_if` keeps the wire format small when no limit is set.
        let s = Settings::default();
        let json = serde_json::to_string(&s).unwrap();
        assert!(
            !json.contains("seed_time_limit_secs"),
            "None should not be serialised: {json}"
        );
        assert!(
            !json.contains("inactive_seed_time_limit_secs"),
            "None should not be serialised: {json}"
        );
    }

    #[test]
    fn seed_time_limits_flow_to_torrent_config() {
        let s = Settings {
            seed_time_limit_secs: Some(7200),
            inactive_seed_time_limit_secs: Some(900),
            ..Settings::default()
        };
        let tc = crate::types::TorrentConfig::from(&s);
        assert_eq!(tc.seed_time_limit_secs, Some(7200));
        assert_eq!(tc.inactive_seed_time_limit_secs, Some(900));
    }

    // M171 D1 — max_ratio_action + create_subfolder + auto_manage_torrents + queueing_enabled
    #[test]
    fn m171_settings_defaults_pause_true_false_false() {
        let s = Settings::default();
        assert_eq!(s.max_ratio_action, MaxRatioAction::Pause);
        assert!(
            s.create_subfolder,
            "create_subfolder defaults true (qBt factory default)"
        );
        assert!(!s.auto_manage_torrents);
        assert!(!s.queueing_enabled);
    }

    #[test]
    fn m171_settings_round_trip_preserves_all_four() {
        let s = Settings {
            max_ratio_action: MaxRatioAction::EnableSuperSeeding,
            create_subfolder: false,
            auto_manage_torrents: true,
            queueing_enabled: true,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, s);
    }

    #[test]
    fn max_ratio_action_wire_snake_case() {
        // Critical for qBt compat: the wire format must be snake_case.
        let pause = serde_json::to_string(&MaxRatioAction::Pause).unwrap();
        let remove = serde_json::to_string(&MaxRatioAction::Remove).unwrap();
        let super_seed = serde_json::to_string(&MaxRatioAction::EnableSuperSeeding).unwrap();
        assert_eq!(pause, "\"pause\"");
        assert_eq!(remove, "\"remove\"");
        assert_eq!(super_seed, "\"enable_super_seeding\"");
    }

    #[test]
    fn max_ratio_action_wire_snake_case_round_trip() {
        // Deserialisation from snake_case works too.
        let pause: MaxRatioAction = serde_json::from_str("\"pause\"").unwrap();
        let remove: MaxRatioAction = serde_json::from_str("\"remove\"").unwrap();
        let super_seed: MaxRatioAction = serde_json::from_str("\"enable_super_seeding\"").unwrap();
        assert_eq!(pause, MaxRatioAction::Pause);
        assert_eq!(remove, MaxRatioAction::Remove);
        assert_eq!(super_seed, MaxRatioAction::EnableSuperSeeding);
    }

    #[test]
    fn validation_force_proxy_no_proxy() {
        let s = Settings {
            force_proxy: true,
            ..Settings::default()
        };
        // proxy_type defaults to None
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("force_proxy"));
    }

    #[test]
    fn validation_valid_defaults() {
        Settings::default().validate().unwrap();
        Settings::min_memory().validate().unwrap();
        Settings::high_performance().validate().unwrap();
    }

    #[test]
    fn disk_config_from_settings() {
        let s = Settings::default();
        let dc = crate::disk::DiskConfig::from(&s);
        assert_eq!(dc.io_threads, default_disk_io_threads());
        assert_eq!(dc.storage_mode, StorageMode::Auto);
        assert_eq!(dc.cache_size, 16 * 1024 * 1024);
        assert!((dc.write_cache_ratio - 0.5).abs() < f32::EPSILON);
        assert_eq!(dc.channel_capacity, 512);
    }

    #[test]
    fn torrent_config_from_settings() {
        let s = Settings::default();
        let tc = crate::types::TorrentConfig::from(&s);
        assert_eq!(tc.listen_port, 0); // random per-torrent
        assert_eq!(tc.max_peers, s.max_peers_per_torrent);
        assert_eq!(tc.download_dir, s.download_dir);
        assert_eq!(tc.enable_dht, s.enable_dht);
        assert_eq!(tc.enable_pex, s.enable_pex);
        assert_eq!(tc.encryption_mode, s.encryption_mode);
        assert_eq!(tc.enable_utp, s.enable_utp);
        assert_eq!(tc.enable_web_seed, s.enable_web_seed);
        assert_eq!(tc.hashing_threads, s.hashing_threads);
        assert_eq!(
            tc.max_concurrent_stream_reads,
            s.max_concurrent_stream_reads
        );
        assert_eq!(tc.anonymous_mode, s.anonymous_mode);
        assert_eq!(tc.enable_i2p, s.enable_i2p);
        assert_eq!(tc.allow_i2p_mixed, s.allow_i2p_mixed);
        // Previously hardcoded — now wired from Settings
        assert_eq!(tc.strict_end_game, s.strict_end_game);
        assert_eq!(tc.upload_rate_limit, s.upload_rate_limit);
        assert_eq!(tc.download_rate_limit, s.download_rate_limit);
        assert_eq!(tc.max_web_seeds, s.max_web_seeds);
        assert_eq!(tc.initial_picker_threshold, s.initial_picker_threshold);
        assert_eq!(tc.whole_pieces_threshold, s.whole_pieces_threshold);
        assert_eq!(tc.snub_timeout_secs, s.snub_timeout_secs);
        assert_eq!(tc.readahead_pieces, s.readahead_pieces);
        assert_eq!(
            tc.streaming_timeout_escalation,
            s.streaming_timeout_escalation
        );
        // New fields
        assert_eq!(tc.storage_mode, s.storage_mode);
        assert_eq!(tc.block_request_timeout_secs, s.block_request_timeout_secs);
        assert_eq!(tc.enable_lsd, s.enable_lsd);
        assert_eq!(tc.force_proxy, s.force_proxy);
        // M132: steal-queue population interval
        assert_eq!(tc.steal_stale_piece_secs, 2);
        assert_eq!(tc.steal_stale_piece_secs, s.steal_stale_piece_secs);
    }

    #[test]
    fn torrent_config_from_nondefault_settings() {
        // Verify non-default values flow through (catches re-hardcoding regressions)
        let mut s = Settings {
            strict_end_game: false,
            upload_rate_limit: 1_000_000,
            download_rate_limit: 2_000_000,
            max_web_seeds: 8,
            initial_picker_threshold: 10,
            whole_pieces_threshold: 50,
            snub_timeout_secs: 120,
            readahead_pieces: 16,
            streaming_timeout_escalation: false,
            storage_mode: StorageMode::Full,
            block_request_timeout_secs: 30,
            enable_lsd: false,
            force_proxy: true,
            ..Settings::default()
        };
        s.proxy.proxy_type = crate::proxy::ProxyType::Socks5;

        let tc = crate::types::TorrentConfig::from(&s);
        assert!(!tc.strict_end_game);
        assert_eq!(tc.upload_rate_limit, 1_000_000);
        assert_eq!(tc.download_rate_limit, 2_000_000);
        assert_eq!(tc.max_web_seeds, 8);
        assert_eq!(tc.initial_picker_threshold, 10);
        assert_eq!(tc.whole_pieces_threshold, 50);
        assert_eq!(tc.snub_timeout_secs, 120);
        assert_eq!(tc.readahead_pieces, 16);
        assert!(!tc.streaming_timeout_escalation);
        assert_eq!(tc.storage_mode, StorageMode::Full);
        assert_eq!(tc.block_request_timeout_secs, 30);
        assert!(!tc.enable_lsd);
        assert!(tc.force_proxy);
    }

    #[test]
    fn external_ip_default_and_json() {
        let s = Settings::default();
        assert!(s.external_ip.is_none());

        // JSON with external_ip set
        let json = r#"{"external_ip": "203.0.113.5"}"#;
        let decoded: Settings = serde_json::from_str(json).unwrap();
        assert_eq!(
            decoded.external_ip,
            Some(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
                203, 0, 113, 5
            )))
        );

        // Round-trip preserves external_ip
        let encoded = serde_json::to_string(&decoded).unwrap();
        let roundtrip: Settings = serde_json::from_str(&encoded).unwrap();
        assert_eq!(roundtrip.external_ip, decoded.external_ip);
    }

    #[test]
    fn validation_zero_threads() {
        let s = Settings {
            hashing_threads: 0,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("hashing_threads"));

        let s = Settings {
            disk_io_threads: 0,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("disk_io_threads"));

        let s = Settings {
            max_blocking_threads: 0,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("max_blocking_threads"));
    }

    #[test]
    fn share_mode_requires_fast_extension() {
        let mut s = Settings {
            default_share_mode: true,
            enable_fast_extension: false,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("share_mode"));

        // With fast extension enabled, share mode is valid
        s.enable_fast_extension = true;
        s.validate().unwrap();
    }

    #[test]
    fn share_mode_default_false() {
        let cfg = crate::types::TorrentConfig::default();
        assert!(!cfg.share_mode);
    }

    #[test]
    fn dht_storage_settings_defaults() {
        let s = Settings::default();
        assert_eq!(s.dht_max_items, 700);
        assert_eq!(s.dht_item_lifetime_secs, 7200);
    }

    #[test]
    fn dht_sample_interval_default_disabled() {
        let s = Settings::default();
        assert_eq!(s.dht_sample_infohashes_interval, 0);
    }

    #[test]
    fn dht_sample_interval_json_round_trip() {
        let json = r#"{"dht_sample_infohashes_interval": 300}"#;
        let decoded: Settings = serde_json::from_str(json).unwrap();
        assert_eq!(decoded.dht_sample_infohashes_interval, 300);

        let encoded = serde_json::to_string(&decoded).unwrap();
        let roundtrip: Settings = serde_json::from_str(&encoded).unwrap();
        assert_eq!(roundtrip.dht_sample_infohashes_interval, 300);
    }

    #[test]
    fn min_memory_restricts_dht_items() {
        let s = Settings::min_memory();
        assert_eq!(s.dht_max_items, 100);
    }

    #[test]
    fn dht_config_inherits_security_settings() {
        let s = Settings {
            dht_enforce_node_id: false,
            ..Settings::default()
        };
        let dht = s.to_dht_config();
        assert!(!dht.enforce_node_id);
        assert!(dht.restrict_routing_ips);

        let dht_v6 = s.to_dht_config_v6();
        assert!(!dht_v6.enforce_node_id);
        assert!(dht_v6.restrict_routing_ips);
    }

    #[test]
    fn enable_holepunch_default_true() {
        let s = Settings::default();
        assert!(s.enable_holepunch);
    }

    #[test]
    fn enable_holepunch_json_round_trip() {
        let json = r#"{"enable_holepunch": false}"#;
        let decoded: Settings = serde_json::from_str(json).unwrap();
        assert!(!decoded.enable_holepunch);

        let encoded = serde_json::to_string(&decoded).unwrap();
        let roundtrip: Settings = serde_json::from_str(&encoded).unwrap();
        assert!(!roundtrip.enable_holepunch);
    }

    #[test]
    fn i2p_settings_defaults() {
        let s = Settings::default();
        assert!(!s.enable_i2p);
        assert_eq!(s.i2p_hostname, "127.0.0.1");
        assert_eq!(s.i2p_port, 7656);
        assert_eq!(s.i2p_inbound_quantity, 3);
        assert_eq!(s.i2p_outbound_quantity, 3);
        assert_eq!(s.i2p_inbound_length, 3);
        assert_eq!(s.i2p_outbound_length, 3);
        assert!(!s.allow_i2p_mixed);
    }

    #[test]
    fn i2p_settings_json_roundtrip() {
        let s = Settings {
            enable_i2p: true,
            i2p_hostname: "10.0.0.1".into(),
            i2p_port: 7700,
            i2p_inbound_quantity: 5,
            i2p_outbound_quantity: 4,
            i2p_inbound_length: 2,
            i2p_outbound_length: 1,
            allow_i2p_mixed: true,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(s, decoded);
    }

    #[test]
    fn i2p_validation_quantity_zero() {
        let s = Settings {
            enable_i2p: true,
            i2p_inbound_quantity: 0,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("i2p_inbound_quantity"));
    }

    #[test]
    fn i2p_validation_quantity_too_high() {
        let s = Settings {
            enable_i2p: true,
            i2p_outbound_quantity: 17,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("i2p_outbound_quantity"));
    }

    #[test]
    fn i2p_validation_length_too_high() {
        let s = Settings {
            enable_i2p: true,
            i2p_inbound_length: 8,
            ..Settings::default()
        };
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("i2p_inbound_length"));
    }

    #[test]
    fn i2p_validation_passes_when_disabled() {
        // Invalid values should not trigger errors when I2P is disabled
        let mut s = Settings {
            enable_i2p: false,
            ..Settings::default()
        };
        s.i2p_inbound_quantity = 0; // would be invalid if enabled
        s.validate().unwrap(); // should pass
    }

    #[test]
    fn i2p_validation_valid_config() {
        let s = Settings {
            enable_i2p: true,
            i2p_inbound_quantity: 1,
            i2p_outbound_quantity: 16,
            i2p_inbound_length: 0,
            i2p_outbound_length: 7,
            ..Settings::default()
        };
        s.validate().unwrap();
    }

    #[test]
    fn ssl_settings_defaults() {
        let s = Settings::default();
        assert_eq!(s.ssl_listen_port, 0);
        assert!(s.ssl_cert_path.is_none());
        assert!(s.ssl_key_path.is_none());
    }

    #[test]
    fn ssl_settings_json_round_trip() {
        let s = Settings {
            ssl_listen_port: 4433,
            ssl_cert_path: Some(PathBuf::from("/etc/ssl/cert.pem")),
            ssl_key_path: Some(PathBuf::from("/etc/ssl/key.pem")),
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(s, decoded);
    }

    #[test]
    fn ssl_validation_cert_without_key() {
        let s = Settings {
            ssl_cert_path: Some(PathBuf::from("/tmp/cert.pem")),
            ..Settings::default()
        };
        // ssl_key_path is None
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("ssl_cert_path"));
    }

    #[test]
    fn ssl_validation_key_without_cert() {
        let s = Settings {
            ssl_key_path: Some(PathBuf::from("/tmp/key.pem")),
            ..Settings::default()
        };
        // ssl_cert_path is None
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("ssl_cert_path"));
    }

    #[test]
    fn ssl_validation_both_set_passes() {
        let s = Settings {
            ssl_cert_path: Some(PathBuf::from("/tmp/cert.pem")),
            ssl_key_path: Some(PathBuf::from("/tmp/key.pem")),
            ..Settings::default()
        };
        s.validate().unwrap();
    }

    #[test]
    fn ssl_validation_both_absent_passes() {
        let s = Settings::default();
        // Both are None by default
        s.validate().unwrap();
    }

    #[test]
    fn default_choking_algorithms() {
        let s = Settings::default();
        assert_eq!(
            s.seed_choking_algorithm,
            SeedChokingAlgorithm::FastestUpload
        );
        assert_eq!(s.choking_algorithm, ChokingAlgorithm::FixedSlots);
    }

    #[test]
    fn choking_algorithm_json_round_trip() {
        let s = Settings {
            seed_choking_algorithm: SeedChokingAlgorithm::AntiLeech,
            choking_algorithm: ChokingAlgorithm::RateBased,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(
            decoded.seed_choking_algorithm,
            SeedChokingAlgorithm::AntiLeech
        );
        assert_eq!(decoded.choking_algorithm, ChokingAlgorithm::RateBased);
    }

    #[test]
    fn m44_settings_defaults() {
        let s = Settings::default();
        assert!(s.piece_extent_affinity);
        assert!(s.suggest_mode);
        assert_eq!(s.max_suggest_pieces, 16);
        assert_eq!(s.predictive_piece_announce_ms, 0);
    }

    #[test]
    fn m44_high_performance_enables_suggest() {
        let s = Settings::high_performance();
        assert!(s.suggest_mode);
    }

    #[test]
    fn m44_json_round_trip() {
        let s = Settings {
            piece_extent_affinity: false,
            suggest_mode: true,
            max_suggest_pieces: 5,
            predictive_piece_announce_ms: 50,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(s, decoded);
    }

    #[test]
    fn security_settings_defaults() {
        let s = Settings::default();
        assert!(s.ssrf_mitigation);
        assert!(!s.allow_idna);
        assert!(s.validate_https_trackers);
    }

    #[test]
    fn security_settings_json_round_trip() {
        let s = Settings {
            ssrf_mitigation: false,
            allow_idna: true,
            validate_https_trackers: false,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(s, decoded);
    }

    #[test]
    fn security_settings_missing_use_defaults() {
        // An empty JSON object should deserialize security fields to defaults.
        let decoded: Settings = serde_json::from_str("{}").unwrap();
        assert!(decoded.ssrf_mitigation);
        assert!(!decoded.allow_idna);
        assert!(decoded.validate_https_trackers);
    }

    #[test]
    fn url_security_config_from_settings() {
        let s = Settings {
            ssrf_mitigation: false,
            allow_idna: true,
            validate_https_trackers: false,
            ..Settings::default()
        };
        let cfg = crate::url_guard::UrlSecurityConfig::from(&s);
        assert!(!cfg.ssrf_mitigation);
        assert!(cfg.allow_idna);
        assert!(!cfg.validate_https_trackers);
    }

    #[test]
    fn default_peer_dscp_value() {
        let s = Settings::default();
        assert_eq!(s.peer_dscp, 0x08);
    }

    #[test]
    fn peer_dscp_json_round_trip() {
        let s = Settings {
            peer_dscp: 0x2E, // EF
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.peer_dscp, 0x2E);
    }

    #[test]
    fn peer_dscp_zero_disables() {
        let s = Settings {
            peer_dscp: 0,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.peer_dscp, 0);
    }

    #[test]
    fn utp_config_includes_dscp() {
        let s = Settings {
            peer_dscp: 0x0A,
            ..Settings::default()
        };
        let utp = s.to_utp_config(6881);
        assert_eq!(utp.dscp, 0x0A);

        let utp_v6 = s.to_utp_config_v6(6881);
        assert_eq!(utp_v6.dscp, 0x0A);
    }

    #[test]
    fn default_stats_report_interval() {
        let s = Settings::default();
        assert_eq!(s.stats_report_interval, 1000);
    }

    #[test]
    fn stats_report_interval_json_round_trip() {
        let s = Settings {
            stats_report_interval: 5000,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.stats_report_interval, 5000);
    }

    #[test]
    fn stats_report_interval_zero_disables() {
        let s = Settings {
            stats_report_interval: 0,
            ..Settings::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        let decoded: Settings = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.stats_report_interval, 0);
    }

    #[test]
    fn settings_runtime_worker_threads_and_pin_cores() {
        // Defaults
        let s = Settings::default();
        assert_eq!(s.runtime_worker_threads, default_runtime_worker_threads());
        assert!(s.pin_cores);

        // 0 is valid (means auto-detect)
        let mut s = Settings {
            runtime_worker_threads: 0,
            ..Settings::default()
        };
        assert!(s.validate().is_ok());

        // 256 is valid (boundary)
        s.runtime_worker_threads = 256;
        assert!(s.validate().is_ok());

        // 257 is invalid
        s.runtime_worker_threads = 257;
        assert!(s.validate().is_err());
    }

    #[test]
    fn max_in_flight_512_default() {
        let s = Settings::default();
        assert_eq!(s.max_in_flight_pieces, 512);
        assert_eq!(s.fixed_pipeline_depth, 128);

        // Presets
        let mm = Settings::min_memory();
        assert_eq!(mm.max_in_flight_pieces, 32);
        assert_eq!(mm.fixed_pipeline_depth, 32);

        let hp = Settings::high_performance();
        assert_eq!(hp.max_in_flight_pieces, 512);
        assert_eq!(hp.fixed_pipeline_depth, 128); // inherits default
    }

    #[test]
    fn recalc_max_in_flight_formula() {
        // M104: The formula in torrent.rs: max(512, connected * 4), clamped to
        // num_pieces / 2, floored at 512. Validate the logic here.
        let base = 512_usize;

        // Few peers: floor dominates
        let connected = 10;
        let num_pieces = 2000_u32;
        let calculated = base.max(connected * 4);
        let result = calculated.min(num_pieces as usize / 2).max(base);
        assert_eq!(result, 512); // max(512, 40) = 512, min(512, 1000) = 512

        // Many peers: peer count drives it up
        let connected = 200;
        let calculated = base.max(connected * 4);
        let result = calculated.min(num_pieces as usize / 2).max(base);
        assert_eq!(result, 800); // max(512, 800) = 800, min(800, 1000) = 800

        // Small torrent: piece clamp wins
        let connected = 200;
        let num_pieces = 100_u32;
        let calculated = base.max(connected * 4);
        let result = calculated.min(num_pieces as usize / 2).max(base);
        assert_eq!(result, 512); // max(512, 800) = 800, min(800, 50) = 50, max(50, 512) = 512

        // Exact boundary: connected * 4 == base
        let connected = 129; // 129 * 4 = 516, just above 512
        let num_pieces = 10000_u32;
        let calculated = base.max(connected * 4);
        let result = calculated.min(num_pieces as usize / 2).max(base);
        assert_eq!(result, 516); // max(512, 516) = 516, min(516, 5000) = 516
    }

    // ── M168: qBt v2 compatibility settings tests ────────────────────

    #[test]
    fn settings_default_enables_qbt_compat_v0_172_1() {
        // v0.172.1: default flipped from false (M168 security-through-
        // invisibility) to true so *arr clients work out of the box. The
        // real defences (argon2id hash, brute-force ban, CSRF middleware)
        // all ship in M172a. Operators opt out via [qbt_compat] enabled = false.
        let s = Settings::default();
        assert!(s.qbt_compat.enabled);
        assert_eq!(s.qbt_compat.username, "admin");
        // M172a: plaintext `password` ships empty by default; `password_hash`
        // ships a pre-hashed "adminadmin" so fresh installs never run the
        // legacy-migration path.
        assert_eq!(s.qbt_compat.password, "");
        assert!(
            s.qbt_compat
                .password_hash
                .starts_with("$argon2id$v=19$m=19456,t=2,p=1$")
        );
        assert_eq!(s.qbt_compat.spoof_app_version, "v5.1.4");
        assert_eq!(s.qbt_compat.spoof_webapi_version, "2.11.4");
        assert_eq!(s.qbt_compat.session_ttl_secs, 86_400);
        assert_eq!(s.qbt_compat.max_sessions, 1024);
        assert!(s.qbt_compat.max_concurrent_argon2_ops.is_none());
    }

    #[test]
    fn validate_rejects_empty_username() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.username = String::new();
        let err = s.validate().expect_err("empty username must fail");
        let msg = format!("{err}");
        assert!(msg.contains("username"), "error was: {msg}");
    }

    #[test]
    fn validate_rejects_short_legacy_password_lt_8_when_hash_empty() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        // Simulate a pre-M172a config: hash is empty, plaintext is too short.
        s.qbt_compat.password_hash.clear();
        s.qbt_compat.password = "short".into();
        let err = s.validate().expect_err("short password must fail");
        let msg = format!("{err}");
        assert!(
            msg.contains("password") && msg.contains("hash"),
            "error was: {msg}"
        );
    }

    #[test]
    fn validate_rejects_bad_app_version_format() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.spoof_app_version = "garbage".into();
        let err = s.validate().expect_err("bad app version must fail");
        let msg = format!("{err}");
        assert!(msg.contains("spoof_app_version"), "error was: {msg}");
    }

    #[test]
    fn validate_rejects_bad_webapi_version_format() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.spoof_webapi_version = "v2.11".into(); // leading v is wrong for webapi
        let err = s.validate().expect_err("bad webapi version must fail");
        let msg = format!("{err}");
        assert!(msg.contains("spoof_webapi_version"), "error was: {msg}");
    }

    #[test]
    fn validate_rejects_ttl_out_of_bounds() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.session_ttl_secs = 10; // below 60
        let err = s.validate().expect_err("ttl too small must fail");
        assert!(format!("{err}").contains("session_ttl_secs"));

        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.session_ttl_secs = 604_801; // above 604800
        let err = s.validate().expect_err("ttl too large must fail");
        assert!(format!("{err}").contains("session_ttl_secs"));
    }

    // ── M172a Lane A: argon2 PHC + migration ──────────────────────────

    #[test]
    fn default_hash_roundtrips_admin_admin() {
        use argon2::Argon2;
        use argon2::password_hash::{PasswordHash, PasswordVerifier};

        // If this test fails because someone changed the default salt or
        // Argon2 parameters, regenerate `DEFAULT_ADMINADMIN_HASH` with:
        //
        //   cargo run --example regen_qbt_default_hash
        //
        // and paste the output back into the constant. The asymmetry matters:
        // production verification uses the same crate + params, so this test
        // is the canary for a bad paste. We do not regenerate the hash here
        // (non-deterministic salt would break cross-install round-tripping).
        let hash = PasswordHash::new(DEFAULT_ADMINADMIN_HASH)
            .expect("DEFAULT_ADMINADMIN_HASH must be a valid PHC string");
        Argon2::default()
            .verify_password(b"adminadmin", &hash)
            .expect("default hash must verify the 'adminadmin' plaintext");
    }

    #[test]
    fn validate_rejects_password_hash_not_starting_with_argon2id() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        // bcrypt-style hash — wrong scheme.
        s.qbt_compat.password_hash =
            "$2b$12$KIXQ5.pHJN3iLz9H6CfQEe2/6rFv1h4jdXWv.0eoGzJ6w7L4Yj7vi".into();
        let err = s.validate().expect_err("non-argon2id hash must fail");
        let msg = format!("{err}");
        assert!(msg.contains("argon2id"), "error was: {msg}");
    }

    #[test]
    fn validate_rejects_zero_max_concurrent_argon2_ops() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.max_concurrent_argon2_ops = Some(0);
        let err = s.validate().expect_err("zero argon2 semaphore must fail");
        assert!(format!("{err}").contains("max_concurrent_argon2_ops"));
    }

    #[test]
    fn default_settings_ship_pre_hashed_no_migration_needed() {
        let s = Settings::default();
        assert!(s.qbt_compat.password_hash.starts_with("$argon2id$"));
        assert!(s.qbt_compat.password.is_empty());
    }

    #[test]
    fn hash_qbt_password_roundtrips() {
        let h = hash_qbt_password("correct horse battery staple")
            .expect("hash must succeed for a simple plaintext");
        assert!(h.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
        // Every call produces a fresh salt → different PHC output.
        let h2 =
            hash_qbt_password("correct horse battery staple").expect("second hash must succeed");
        assert_ne!(h, h2, "argon2 must use a fresh salt per call");
    }

    #[test]
    fn migrate_qbt_credentials_noop_when_hash_present() {
        let mut qbt = QbtCompatSettings {
            password_hash: DEFAULT_ADMINADMIN_HASH.into(),
            password: String::new(),
            ..Default::default()
        };
        let outcome = migrate_qbt_credentials(&mut qbt).expect("noop");
        assert_eq!(outcome, QbtCredentialMigration::NoOp);
        assert_eq!(qbt.password_hash, DEFAULT_ADMINADMIN_HASH);
        assert!(qbt.password.is_empty());
    }

    #[test]
    fn migrate_qbt_credentials_upgrades_legacy_plaintext() {
        use argon2::Argon2;
        use argon2::password_hash::{PasswordHash, PasswordVerifier};

        let mut qbt = QbtCompatSettings {
            password_hash: String::new(),
            password: "legacy-plaintext-pw".into(),
            ..Default::default()
        };
        let outcome = migrate_qbt_credentials(&mut qbt).expect("upgrade");
        assert_eq!(outcome, QbtCredentialMigration::Upgraded);
        assert!(qbt.password_hash.starts_with("$argon2id$"));
        assert!(
            qbt.password.is_empty(),
            "plaintext must be zeroed after migration"
        );

        let parsed =
            PasswordHash::new(&qbt.password_hash).expect("migration wrote a valid PHC string");
        Argon2::default()
            .verify_password(b"legacy-plaintext-pw", &parsed)
            .expect("migrated hash must verify the original plaintext");
    }

    #[test]
    fn migrate_qbt_credentials_noop_when_both_empty() {
        let mut qbt = QbtCompatSettings {
            password_hash: String::new(),
            password: String::new(),
            ..Default::default()
        };
        let outcome = migrate_qbt_credentials(&mut qbt).expect("noop on empty");
        assert_eq!(outcome, QbtCredentialMigration::NoOp);
    }

    // ── M172a Lane C: brute-force ban settings ────────────────────────

    #[test]
    fn brute_force_defaults_are_5_attempts_and_one_hour_ban() {
        let s = Settings::default();
        assert_eq!(s.qbt_compat.max_failed_auth_count, 5);
        assert_eq!(s.qbt_compat.ban_duration_secs, 3_600);
        assert!(!s.qbt_compat.bypass_local_auth);
        assert!(s.qbt_compat.bypass_auth_subnet_whitelist.is_empty());
        assert!(s.qbt_compat.brute_force_registry_capacity.is_none());
    }

    #[test]
    fn validate_rejects_zero_max_failed_auth_count_without_bypass() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.max_failed_auth_count = 0;
        s.qbt_compat.bypass_local_auth = false;
        let err = s
            .validate()
            .expect_err("zero attempts without bypass must fail");
        assert!(format!("{err}").contains("max_failed_auth_count"));
    }

    #[test]
    fn validate_accepts_zero_max_failed_auth_count_when_bypass_local() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.max_failed_auth_count = 0;
        s.qbt_compat.bypass_local_auth = true;
        s.validate().expect("bypass_local_auth disarms the check");
    }

    #[test]
    fn validate_rejects_ban_duration_out_of_bounds() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.ban_duration_secs = 59;
        let err = s.validate().expect_err("too short ban must fail");
        assert!(format!("{err}").contains("ban_duration_secs"));

        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.ban_duration_secs = 86_401;
        let err = s.validate().expect_err("too long ban must fail");
        assert!(format!("{err}").contains("ban_duration_secs"));
    }

    #[test]
    fn validate_rejects_malformed_bypass_whitelist_cidr() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.bypass_auth_subnet_whitelist = vec!["not-a-cidr".into()];
        let err = s.validate().expect_err("bad cidr must fail");
        let msg = format!("{err}");
        assert!(msg.contains("bypass_auth_subnet_whitelist"));
        assert!(msg.contains("not-a-cidr"));
    }

    #[test]
    fn validate_accepts_valid_bypass_whitelist_cidrs() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.bypass_auth_subnet_whitelist = vec![
            "10.0.0.0/8".into(),
            "192.168.1.0/24".into(),
            "::1/128".into(),
        ];
        s.validate().expect("valid cidrs pass");
    }

    #[test]
    fn validate_rejects_registry_capacity_below_floor() {
        let mut s = Settings::default();
        s.qbt_compat.enabled = true;
        s.qbt_compat.brute_force_registry_capacity = Some(99);
        let err = s
            .validate()
            .expect_err("capacity < 100 must fail sanity floor");
        assert!(format!("{err}").contains("brute_force_registry_capacity"));
    }

    // ── M224: max_uploads_per_torrent validate + serde-default ──────────

    #[test]
    fn validate_rejects_zero_max_uploads_per_torrent() {
        let s = Settings {
            max_uploads_per_torrent: 0,
            ..Settings::default()
        };
        let err = s
            .validate()
            .expect_err("max_uploads_per_torrent = 0 must fail");
        let msg = format!("{err}");
        assert!(
            msg.contains("max_uploads_per_torrent"),
            "error was: {msg}"
        );
    }

    #[test]
    fn validate_rejects_negative_below_minus_one_max_uploads_per_torrent() {
        let s = Settings {
            max_uploads_per_torrent: -2,
            ..Settings::default()
        };
        let err = s
            .validate()
            .expect_err("max_uploads_per_torrent < -1 must fail");
        let msg = format!("{err}");
        assert!(
            msg.contains("max_uploads_per_torrent"),
            "error was: {msg}"
        );
    }

    #[test]
    fn validate_accepts_minus_one_max_uploads_per_torrent() {
        let s = Settings::default();
        assert_eq!(s.max_uploads_per_torrent, -1);
        s.validate().expect("default -1 must validate");
    }

    #[test]
    fn validate_accepts_positive_max_uploads_per_torrent() {
        let s = Settings {
            max_uploads_per_torrent: 4,
            ..Settings::default()
        };
        s.validate().expect("n >= 1 must validate");
    }

    #[test]
    fn max_uploads_per_torrent_default_deserialize_without_field() {
        // R6 guard: existing Settings JSON files without the new field must
        // deserialize cleanly to -1 (the default-fn sentinel), not 0 (which
        // would then fail validate() and break every existing config).
        let s = Settings::default();
        let mut value = serde_json::to_value(&s).expect("serialise");
        let obj = value.as_object_mut().expect("Settings is a JSON object");
        assert!(
            obj.remove("max_uploads_per_torrent").is_some(),
            "field should have been present in serialised default"
        );
        let decoded: Settings = serde_json::from_value(value).expect("deserialise without field");
        assert_eq!(decoded.max_uploads_per_torrent, -1);
        decoded.validate().expect("default-via-serde must validate");
    }

    #[test]
    fn brute_force_settings_json_round_trip() {
        let mut s = Settings::default();
        s.qbt_compat.max_failed_auth_count = 7;
        s.qbt_compat.ban_duration_secs = 1_800;
        s.qbt_compat.bypass_local_auth = true;
        s.qbt_compat.bypass_auth_subnet_whitelist = vec!["10.0.0.0/8".into()];
        s.qbt_compat.brute_force_registry_capacity = Some(5_000);

        let json = serde_json::to_string(&s).expect("serialise");
        let decoded: Settings = serde_json::from_str(&json).expect("deserialise");
        assert_eq!(decoded.qbt_compat.max_failed_auth_count, 7);
        assert_eq!(decoded.qbt_compat.ban_duration_secs, 1_800);
        assert!(decoded.qbt_compat.bypass_local_auth);
        assert_eq!(
            decoded.qbt_compat.bypass_auth_subnet_whitelist,
            vec!["10.0.0.0/8".to_string()]
        );
        assert_eq!(
            decoded.qbt_compat.brute_force_registry_capacity,
            Some(5_000)
        );
    }

    // ── M226: Notifications / paths / watched folder / network — defaults ────

    #[test]
    fn settings_default_notify_on_complete_is_false() {
        assert!(!Settings::default().notify_on_complete);
    }

    #[test]
    fn settings_default_notify_on_error_is_false() {
        assert!(!Settings::default().notify_on_error);
    }

    #[test]
    fn settings_default_on_complete_program_is_none() {
        assert!(Settings::default().on_complete_program.is_none());
    }

    #[test]
    fn settings_default_use_incomplete_dir_is_false() {
        assert!(!Settings::default().use_incomplete_dir);
    }

    #[test]
    fn settings_default_incomplete_dir_is_none() {
        assert!(Settings::default().incomplete_dir.is_none());
    }

    #[test]
    fn settings_default_default_skip_hash_check_is_false() {
        assert!(!Settings::default().default_skip_hash_check);
    }

    #[test]
    fn settings_default_incomplete_extension_enabled_is_true() {
        assert!(Settings::default().incomplete_extension_enabled);
    }

    #[test]
    fn settings_default_watched_folder_is_none() {
        assert!(Settings::default().watched_folder.is_none());
    }

    #[test]
    fn settings_default_delete_torrent_after_add_is_false() {
        assert!(!Settings::default().delete_torrent_after_add);
    }

    #[test]
    fn settings_default_move_completed_enabled_is_false() {
        assert!(!Settings::default().move_completed_enabled);
    }

    #[test]
    fn settings_default_move_completed_to_is_none() {
        assert!(Settings::default().move_completed_to.is_none());
    }

    #[test]
    fn settings_default_web_ui_https_enabled_is_false() {
        assert!(!Settings::default().web_ui_https_enabled);
    }

    #[test]
    fn settings_default_network_interface_is_none() {
        assert!(Settings::default().network_interface.is_none());
    }

    #[test]
    fn settings_default_default_add_paused_is_false() {
        assert!(!Settings::default().default_add_paused);
    }

    // ── M226: validation rules ────

    #[test]
    fn validate_rejects_use_incomplete_dir_without_incomplete_dir() {
        let s = Settings {
            use_incomplete_dir: true,
            incomplete_dir: None,
            ..Settings::default()
        };
        let err = s.validate().expect_err("must require incomplete_dir");
        assert!(format!("{err}").contains("incomplete_dir"));
    }

    #[test]
    fn validate_accepts_use_incomplete_dir_with_incomplete_dir() {
        let s = Settings {
            use_incomplete_dir: true,
            incomplete_dir: Some(PathBuf::from("/tmp/irontide-incomplete")),
            ..Settings::default()
        };
        s.validate().expect("paired fields valid");
    }

    #[test]
    fn validate_rejects_move_completed_without_move_completed_to() {
        let s = Settings {
            move_completed_enabled: true,
            move_completed_to: None,
            ..Settings::default()
        };
        let err = s.validate().expect_err("must require move_completed_to");
        assert!(format!("{err}").contains("move_completed_to"));
    }

    #[test]
    fn validate_rejects_relative_watched_folder() {
        let s = Settings {
            watched_folder: Some(PathBuf::from("relative/path")),
            ..Settings::default()
        };
        let err = s.validate().expect_err("relative path must fail");
        assert!(format!("{err}").contains("absolute"));
    }

    #[test]
    fn validate_rejects_relative_incomplete_dir() {
        let s = Settings {
            incomplete_dir: Some(PathBuf::from("inc")),
            ..Settings::default()
        };
        let err = s.validate().expect_err("relative path must fail");
        assert!(format!("{err}").contains("absolute"));
    }

    #[test]
    fn validate_rejects_relative_move_completed_to() {
        let s = Settings {
            move_completed_to: Some(PathBuf::from("done")),
            ..Settings::default()
        };
        let err = s.validate().expect_err("relative path must fail");
        assert!(format!("{err}").contains("absolute"));
    }

    #[test]
    fn validate_rejects_system_path_as_watched_folder() {
        for sys in ["/", "/etc", "/usr", "/bin", "/sys", "/proc"] {
            let s = Settings {
                watched_folder: Some(PathBuf::from(sys)),
                ..Settings::default()
            };
            let err = s
                .validate()
                .expect_err("system path must be rejected");
            assert!(
                format!("{err}").contains("system path"),
                "{sys}: error must mention 'system path', got: {err}"
            );
        }
    }

    #[test]
    fn validate_accepts_safe_watched_folder() {
        let s = Settings {
            watched_folder: Some(PathBuf::from("/tmp/irontide-watched")),
            ..Settings::default()
        };
        s.validate().expect("safe path must validate");
    }
}