irontide-session 0.165.0

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
//! 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;

// ── 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 {
    1
}
fn default_inactive_rate() -> u64 {
    2048
}
fn default_auto_manage_interval() -> u64 {
    30
}
fn default_auto_manage_startup() -> u64 {
    60
}
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(|n| n.get())
        .unwrap_or(4);
    (cores / 2).clamp(4, 16)
}
fn default_max_blocking_threads() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
}
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(|n| n.get())
        .unwrap_or(4);
    (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_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
}
fn default_stats_report_interval() -> u64 {
    1000
}
fn default_strict_end_game() -> bool {
    true
}
fn default_max_web_seeds() -> usize {
    4
}
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(|n| n.get().min(8))
        .unwrap_or(4)
}
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_min_pipeline_depth() -> u32 {
    16
}
fn default_max_pipeline_depth() -> u32 {
    512
}
fn default_target_buffer_secs() -> f64 {
    2.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_save_resume_interval() -> u64 {
    300 // M161: 5 minutes between periodic resume file saves
}

// ── 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, Serialize, Deserialize)]
pub struct Settings {
    // ── General ──
    /// TCP listen port for incoming peer connections (default: 42020).
    #[serde(default = "default_listen_port")]
    pub listen_port: u16,
    /// 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,
    /// 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>,
    /// 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,
    /// 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,

    // ── 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,
    /// 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,
    /// M149: Minimum per-peer pipeline depth (requests in flight). Default: 16.
    #[serde(default = "default_min_pipeline_depth")]
    pub min_pipeline_depth: u32,
    /// M149: Maximum per-peer pipeline depth (requests in flight). Default: 512.
    #[serde(default = "default_max_pipeline_depth")]
    pub max_pipeline_depth: u32,
    /// M149: Seconds of data to buffer in the pipeline per peer. Used to compute
    /// dynamic depth: depth = (download_rate / block_size) * target_buffer_secs.
    #[serde(default = "default_target_buffer_secs")]
    pub target_buffer_secs: 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
    /// don't have them, improving piece diversity in the swarm. Default: false.
    #[serde(default)]
    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,
    /// 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).
    #[serde(default = "default_max_peers_per_torrent")]
    pub max_peers_per_torrent: 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,

    // ── 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>,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            // General
            listen_port: 42020,
            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,
            encryption_mode: EncryptionMode::Disabled,
            anonymous_mode: false,
            external_ip: None,
            // Seeding
            seed_ratio_limit: None,
            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,
            mixed_mode_algorithm: MixedModeAlgorithm::PeerProportional,
            // Queue management
            active_downloads: 3,
            active_seeds: 5,
            active_limit: 500,
            active_checking: 1,
            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,
            // 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,
            min_pipeline_depth: 16,
            max_pipeline_depth: 512,
            target_buffer_secs: 2.0,
            fixed_pipeline_depth: 128,
            strict_end_game: true,
            max_web_seeds: 4,
            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: false,
            max_suggest_pieces: 16,
            predictive_piece_announce_ms: 0,
            // Proxy
            proxy: ProxyConfig::default(),
            force_proxy: 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,
            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,
            // 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,
        }
    }
}

impl Settings {
    /// Preset for constrained/embedded environments.
    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.
    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,
            min_pipeline_depth: 16,
            max_pipeline_depth: 512,
            target_buffer_secs: 2.0,
            use_block_stealing: true,
            max_in_flight_pieces: 512,
            ..Self::default()
        }
    }

    /// Validate settings. Returns error on the first invalid combination found.
    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(),
            ));
        }

        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(),
            ));
        }

        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) ────────

impl PartialEq for Settings {
    fn eq(&self, other: &Self) -> bool {
        self.listen_port == other.listen_port
            && self.download_dir == other.download_dir
            && self.max_torrents == other.max_torrents
            && self.resume_data_dir == other.resume_data_dir
            && self.save_resume_interval_secs == other.save_resume_interval_secs
            && self.enable_dht == other.enable_dht
            && self.enable_pex == other.enable_pex
            && self.enable_lsd == other.enable_lsd
            && self.enable_fast_extension == other.enable_fast_extension
            && self.enable_utp == other.enable_utp
            && self.enable_upnp == other.enable_upnp
            && self.enable_natpmp == other.enable_natpmp
            && self.enable_ipv6 == other.enable_ipv6
            && self.enable_web_seed == other.enable_web_seed
            && self.enable_holepunch == other.enable_holepunch
            && self.enable_bep40_eviction == other.enable_bep40_eviction
            && self.encryption_mode == other.encryption_mode
            && self.anonymous_mode == other.anonymous_mode
            && self.external_ip == other.external_ip
            && self.seed_ratio_limit == other.seed_ratio_limit
            && self.default_super_seeding == other.default_super_seeding
            && self.default_share_mode == other.default_share_mode
            && self.upload_only_announce == other.upload_only_announce
            && self.upload_rate_limit == other.upload_rate_limit
            && self.download_rate_limit == other.download_rate_limit
            && self.tcp_upload_rate_limit == other.tcp_upload_rate_limit
            && self.tcp_download_rate_limit == other.tcp_download_rate_limit
            && self.utp_upload_rate_limit == other.utp_upload_rate_limit
            && self.utp_download_rate_limit == other.utp_download_rate_limit
            && self.auto_upload_slots == other.auto_upload_slots
            && self.auto_upload_slots_min == other.auto_upload_slots_min
            && self.auto_upload_slots_max == other.auto_upload_slots_max
            && self.mixed_mode_algorithm == other.mixed_mode_algorithm
            && self.active_downloads == other.active_downloads
            && self.active_seeds == other.active_seeds
            && self.active_limit == other.active_limit
            && self.active_checking == other.active_checking
            && self.dont_count_slow_torrents == other.dont_count_slow_torrents
            && self.inactive_down_rate == other.inactive_down_rate
            && self.inactive_up_rate == other.inactive_up_rate
            && self.auto_manage_interval == other.auto_manage_interval
            && self.auto_manage_startup == other.auto_manage_startup
            && self.auto_manage_prefer_seeds == other.auto_manage_prefer_seeds
            && self.alert_mask == other.alert_mask
            && self.alert_channel_size == other.alert_channel_size
            && self.smart_ban_max_failures == other.smart_ban_max_failures
            && self.smart_ban_parole == other.smart_ban_parole
            && self.disk_io_threads == other.disk_io_threads
            && self.max_blocking_threads == other.max_blocking_threads
            && self.storage_mode == other.storage_mode
            && self.disk_cache_size == other.disk_cache_size
            && self.disk_write_cache_ratio.to_bits() == other.disk_write_cache_ratio.to_bits()
            && self.disk_channel_capacity == other.disk_channel_capacity
            && self.buffer_pool_capacity == other.buffer_pool_capacity
            && self.enable_mlock == other.enable_mlock
            && self.hashing_threads == other.hashing_threads
            && self.max_request_queue_depth == other.max_request_queue_depth
            && self.initial_queue_depth == other.initial_queue_depth
            && self.request_queue_time.to_bits() == other.request_queue_time.to_bits()
            && self.block_request_timeout_secs == other.block_request_timeout_secs
            && self.max_concurrent_stream_reads == other.max_concurrent_stream_reads
            && self.auto_sequential == other.auto_sequential
            && self.steal_threshold_ratio.to_bits() == other.steal_threshold_ratio.to_bits()
            && self.use_block_stealing == other.use_block_stealing
            && self.steal_stale_piece_secs == other.steal_stale_piece_secs
            && self.steal_threshold_endgame.to_bits() == other.steal_threshold_endgame.to_bits()
            && self.min_pipeline_depth == other.min_pipeline_depth
            && self.max_pipeline_depth == other.max_pipeline_depth
            && self.target_buffer_secs.to_bits() == other.target_buffer_secs.to_bits()
            && self.fixed_pipeline_depth == other.fixed_pipeline_depth
            && self.strict_end_game == other.strict_end_game
            && self.max_web_seeds == other.max_web_seeds
            && self.initial_picker_threshold == other.initial_picker_threshold
            && self.whole_pieces_threshold == other.whole_pieces_threshold
            && self.snub_timeout_secs == other.snub_timeout_secs
            && self.readahead_pieces == other.readahead_pieces
            && self.streaming_timeout_escalation == other.streaming_timeout_escalation
            && self.piece_extent_affinity == other.piece_extent_affinity
            && self.suggest_mode == other.suggest_mode
            && self.max_suggest_pieces == other.max_suggest_pieces
            && self.predictive_piece_announce_ms == other.predictive_piece_announce_ms
            && self.force_proxy == other.force_proxy
            && self.apply_ip_filter_to_trackers == other.apply_ip_filter_to_trackers
            && self.dht_queries_per_second == other.dht_queries_per_second
            && self.dht_query_timeout_secs == other.dht_query_timeout_secs
            && self.dht_enforce_node_id == other.dht_enforce_node_id
            && self.dht_restrict_routing_ips == other.dht_restrict_routing_ips
            && self.dht_max_items == other.dht_max_items
            && self.dht_item_lifetime_secs == other.dht_item_lifetime_secs
            && self.dht_sample_infohashes_interval == other.dht_sample_infohashes_interval
            && self.dht_read_only == other.dht_read_only
            && self.upnp_lease_duration == other.upnp_lease_duration
            && self.natpmp_lifetime == other.natpmp_lifetime
            && self.utp_max_connections == other.utp_max_connections
            && self.enable_i2p == other.enable_i2p
            && self.i2p_hostname == other.i2p_hostname
            && self.i2p_port == other.i2p_port
            && self.i2p_inbound_quantity == other.i2p_inbound_quantity
            && self.i2p_outbound_quantity == other.i2p_outbound_quantity
            && self.i2p_inbound_length == other.i2p_inbound_length
            && self.i2p_outbound_length == other.i2p_outbound_length
            && self.allow_i2p_mixed == other.allow_i2p_mixed
            && self.ssl_listen_port == other.ssl_listen_port
            && self.ssl_cert_path == other.ssl_cert_path
            && self.ssl_key_path == other.ssl_key_path
            && self.seed_choking_algorithm == other.seed_choking_algorithm
            && self.choking_algorithm == other.choking_algorithm
            && self.max_peers_per_torrent == other.max_peers_per_torrent
            && self.peer_read_timeout_secs == other.peer_read_timeout_secs
            && self.peer_write_timeout_secs == other.peer_write_timeout_secs
            && self.data_contribution_timeout_secs == other.data_contribution_timeout_secs
            && self.choke_rotation_max_evictions == other.choke_rotation_max_evictions
            && self.max_concurrent_connects == other.max_concurrent_connects
            && self.connect_soft_timeout == other.connect_soft_timeout
            && self.ssrf_mitigation == other.ssrf_mitigation
            && self.allow_idna == other.allow_idna
            && self.validate_https_trackers == other.validate_https_trackers
            && self.max_metadata_size == other.max_metadata_size
            && self.max_message_size == other.max_message_size
            && self.max_piece_length == other.max_piece_length
            && self.max_outstanding_requests == other.max_outstanding_requests
            && self.max_in_flight_pieces == other.max_in_flight_pieces
            && self.peer_connect_timeout == other.peer_connect_timeout
            && self.peer_dscp == other.peer_dscp
            && self.stats_report_interval == other.stats_report_interval
            && self.runtime_worker_threads == other.runtime_worker_threads
            && self.pin_cores == other.pin_cores
            && self.dht_saved_nodes == other.dht_saved_nodes
            && self.dht_node_id == other.dht_node_id
    }
}

// ── 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, 1);
        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());
    }

    #[test]
    fn validation_force_proxy_no_proxy() {
        let mut s = Settings::default();
        s.force_proxy = true;
        // 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::default();
        s.strict_end_game = false;
        s.upload_rate_limit = 1_000_000;
        s.download_rate_limit = 2_000_000;
        s.max_web_seeds = 8;
        s.initial_picker_threshold = 10;
        s.whole_pieces_threshold = 50;
        s.snub_timeout_secs = 120;
        s.readahead_pieces = 16;
        s.streaming_timeout_escalation = false;
        s.storage_mode = StorageMode::Full;
        s.block_request_timeout_secs = 30;
        s.enable_lsd = false;
        s.force_proxy = true;
        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 mut s = Settings::default();
        s.hashing_threads = 0;
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("hashing_threads"));

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

        let mut s = Settings::default();
        s.max_blocking_threads = 0;
        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();
        s.default_share_mode = true;
        s.enable_fast_extension = false;
        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 mut s = Settings::default();
        s.dht_enforce_node_id = false;
        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 mut s = Settings::default();
        s.enable_i2p = true;
        s.i2p_hostname = "10.0.0.1".into();
        s.i2p_port = 7700;
        s.i2p_inbound_quantity = 5;
        s.i2p_outbound_quantity = 4;
        s.i2p_inbound_length = 2;
        s.i2p_outbound_length = 1;
        s.allow_i2p_mixed = true;
        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 mut s = Settings::default();
        s.enable_i2p = true;
        s.i2p_inbound_quantity = 0;
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("i2p_inbound_quantity"));
    }

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

    #[test]
    fn i2p_validation_length_too_high() {
        let mut s = Settings::default();
        s.enable_i2p = true;
        s.i2p_inbound_length = 8;
        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::default();
        s.enable_i2p = false;
        s.i2p_inbound_quantity = 0; // would be invalid if enabled
        s.validate().unwrap(); // should pass
    }

    #[test]
    fn i2p_validation_valid_config() {
        let mut s = Settings::default();
        s.enable_i2p = true;
        s.i2p_inbound_quantity = 1;
        s.i2p_outbound_quantity = 16;
        s.i2p_inbound_length = 0;
        s.i2p_outbound_length = 7;
        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 mut s = Settings::default();
        s.ssl_listen_port = 4433;
        s.ssl_cert_path = Some(PathBuf::from("/etc/ssl/cert.pem"));
        s.ssl_key_path = Some(PathBuf::from("/etc/ssl/key.pem"));
        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 mut s = Settings::default();
        s.ssl_cert_path = Some(PathBuf::from("/tmp/cert.pem"));
        // 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 mut s = Settings::default();
        s.ssl_key_path = Some(PathBuf::from("/tmp/key.pem"));
        // 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 mut s = Settings::default();
        s.ssl_cert_path = Some(PathBuf::from("/tmp/cert.pem"));
        s.ssl_key_path = Some(PathBuf::from("/tmp/key.pem"));
        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 mut s = Settings::default();
        s.seed_choking_algorithm = SeedChokingAlgorithm::AntiLeech;
        s.choking_algorithm = ChokingAlgorithm::RateBased;
        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 mut s = Settings::default();
        s.piece_extent_affinity = false;
        s.suggest_mode = true;
        s.max_suggest_pieces = 5;
        s.predictive_piece_announce_ms = 50;
        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 mut s = Settings::default();
        s.ssrf_mitigation = false;
        s.allow_idna = true;
        s.validate_https_trackers = false;
        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 mut s = Settings::default();
        s.ssrf_mitigation = false;
        s.allow_idna = true;
        s.validate_https_trackers = false;
        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 mut s = Settings::default();
        s.peer_dscp = 0x2E; // EF
        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 mut s = Settings::default();
        s.peer_dscp = 0;
        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 mut s = Settings::default();
        s.peer_dscp = 0x0A;
        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 mut s = Settings::default();
        s.stats_report_interval = 5000;
        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 mut s = Settings::default();
        s.stats_report_interval = 0;
        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::default();
        s.runtime_worker_threads = 0;
        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
    }
}