irontide-session 1.0.1

BitTorrent session management: peers, torrents, and piece selection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;

use bitflags::bitflags;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tokio::sync::oneshot;

use irontide_storage::Bitfield;
use irontide_wire::ExtHandshake;

use crate::choker::{ChokingAlgorithm, SeedChokingAlgorithm};

/// Configurable parameters for a torrent session.
#[derive(Debug, Clone)]
pub struct TorrentConfig {
    /// TCP listen port for incoming peer connections.
    pub listen_port: u16,
    /// Maximum number of peer connections per torrent.
    pub max_peers: usize,
    /// Number of outstanding piece requests to maintain per peer.
    pub target_request_queue: usize,
    /// Directory where downloaded files are stored.
    pub download_dir: PathBuf,
    /// Enable DHT for peer discovery.
    pub enable_dht: bool,
    /// Enable Peer Exchange (BEP 11) for peer discovery.
    pub enable_pex: bool,
    /// Enable Fast Extension (BEP 6) for reject/suggest/allowed-fast messages.
    pub enable_fast: bool,
    /// Stop seeding after reaching this upload/download ratio (None = unlimited).
    pub seed_ratio_limit: Option<f64>,
    /// M171: Stop seeding after this many cumulative seeding seconds
    /// (None = no limit). Mirrors qBt's "Maximum seeding time" preference.
    pub seed_time_limit_secs: Option<u64>,
    /// M171: Stop seeding after this many seconds of inactivity while in
    /// the Seeding state (None = no limit). Mirrors qBt's "Maximum inactive
    /// seeding time" preference.
    pub inactive_seed_time_limit_secs: Option<u64>,
    /// In end game mode, cancel duplicate requests when a piece completes.
    pub strict_end_game: bool,
    /// Upload rate limit in bytes/sec (0 = unlimited).
    pub upload_rate_limit: u64,
    /// Download rate limit in bytes/sec (0 = unlimited).
    pub download_rate_limit: u64,
    /// M224: Maximum unchoked upload slots per torrent (`-1` = unlimited).
    /// Mirrors `Settings.max_uploads_per_torrent`; caps the choker's regular
    /// unchoke set when `n >= 1`. `-1` falls back to the historical default
    /// of 4 regular slots.
    pub max_uploads_per_torrent: i32,
    /// Connection encryption mode (MSE/PE).
    pub encryption_mode: irontide_wire::mse::EncryptionMode,
    /// Enable uTP (micro Transport Protocol) for peer connections.
    pub enable_utp: bool,
    /// Enable HTTP/web seeding (BEP 19, BEP 17).
    pub enable_web_seed: bool,
    /// Enable BEP 55 holepunch extension for NAT traversal.
    pub enable_holepunch: bool,
    /// Enable BEP 40 canonical peer priority for connection eviction.
    pub enable_bep40_eviction: bool,
    /// Maximum concurrent web seed connections.
    pub max_web_seeds: usize,
    /// M186: Base delay (seconds) for web seed exponential backoff.
    pub web_seed_retry_base_secs: u64,
    /// M186: Multiplier for web seed exponential backoff.
    pub web_seed_retry_factor: u64,
    /// M186: Maximum backoff (seconds) for web seed retry.
    pub web_seed_retry_cap_secs: u64,
    /// M186: Consecutive failures before permanently banning a web seed.
    pub web_seed_max_failures: u32,
    /// BEP 16: super seeding mode — reveal pieces one-per-peer for maximum diversity.
    pub super_seeding: bool,
    /// BEP 21: advertise upload-only status via extension handshake when seeding.
    pub upload_only_announce: bool,
    /// Number of concurrent piece verifications during torrent checking.
    pub hashing_threads: usize,
    /// Enable sequential (in-order) piece downloading.
    pub sequential_download: bool,
    /// Completed piece count below which the picker uses random selection to promote diversity.
    pub initial_picker_threshold: u32,
    /// Seconds below which a fast peer downloads a whole piece; if under this, picker grants
    /// exclusive assignment (no block splitting).
    pub whole_pieces_threshold: u32,
    /// Seconds without data from a peer before marking it as snubbed.
    pub snub_timeout_secs: u32,
    /// Number of pieces ahead of the streaming cursor to prioritize.
    pub readahead_pieces: u32,
    /// When true, escalate streaming piece requests that exceed the mean RTT.
    pub streaming_timeout_escalation: bool,
    /// Maximum concurrent file stream readers per torrent.
    pub max_concurrent_stream_reads: usize,
    /// Proxy configuration for outbound peer connections.
    pub proxy: crate::proxy::ProxyConfig,
    /// Anonymous mode: suppress client identity in peer handshakes.
    pub anonymous_mode: bool,
    /// Share mode: relay pieces in memory without writing to disk.
    /// Requires `enable_fast` for `RejectRequest` when evicting pieces.
    pub share_mode: bool,
    /// Whether this torrent should use I2P for peer connections.
    pub enable_i2p: bool,
    /// Whether to allow mixing I2P and clearnet peers.
    pub allow_i2p_mixed: bool,
    /// SSL listen port for SSL torrent connections (0 = disabled).
    pub ssl_listen_port: u16,
    /// Algorithm for ranking peers during seed-mode choking.
    pub seed_choking_algorithm: SeedChokingAlgorithm,
    /// Algorithm for determining the number of unchoke slots.
    pub choking_algorithm: ChokingAlgorithm,
    /// Prefer grouping piece requests within the same 4 MiB disk extent.
    pub piece_extent_affinity: bool,
    /// Enable sending `SuggestPiece` messages for cached pieces.
    pub suggest_mode: bool,
    /// Maximum number of pieces to suggest per peer.
    pub max_suggest_pieces: usize,
    /// Delay (ms) before announcing Have for a piece still being written to disk (0 = disabled).
    pub predictive_piece_announce_ms: u64,
    /// Mixed-mode TCP/uTP bandwidth allocation algorithm.
    pub mixed_mode_algorithm: crate::rate_limiter::MixedModeAlgorithm,
    /// Enable automatic sequential mode switching on partial-piece explosion.
    pub auto_sequential: bool,
    /// Storage allocation mode for disk I/O.
    pub storage_mode: irontide_core::StorageMode,
    /// Override pre-allocation strategy. `None` = derive from `storage_mode`.
    pub preallocate_mode: Option<irontide_storage::PreallocateMode>,
    /// Block request timeout in seconds before re-issuing (0 = disabled).
    pub block_request_timeout_secs: u32,
    /// Enable Local Service Discovery (BEP 14) for this torrent.
    pub enable_lsd: bool,
    /// Force all connections through the configured proxy.
    pub force_proxy: bool,
    /// Steal blocks from peers this many times slower than the requesting peer (0.0 = disabled).
    pub steal_threshold_ratio: f64,
    /// M149: Steal threshold multiplier when >90% complete.
    pub steal_threshold_endgame: f64,
    /// M133: Seconds without any wire message before disconnecting a peer (0 = disabled).
    pub peer_read_timeout_secs: u64,
    /// M133: Seconds before a stalled outgoing write disconnects a peer (0 = disabled).
    pub peer_write_timeout_secs: u64,
    /// M137: Seconds without Piece data before disconnecting a peer (0 = disabled).
    pub data_contribution_timeout_secs: u64,
    /// v0.187.3 / OV2 / 12A: post-handshake grace before Pass 0 eviction
    /// (zero-throughput) can fire (0 = disable grace, legacy v0.187.2 behaviour).
    pub pass0_grace_secs: u64,
    /// v0.187.3 / 3A: sliding-window cap on proactive evictions per torrent
    /// in any rolling 60s window.
    pub proactive_evictions_per_minute_limit: u32,
    /// v0.187.3: how long Pass 0 victims stay banned from reconnection.
    pub eviction_ban_duration_secs: u64,
    /// v0.187.3 / OV4: FIFO cap on the banned-peer set.
    pub eviction_ban_set_cap: usize,
    /// M138: Maximum peers to evict per choke rotation tick (0 = disabled).
    pub choke_rotation_max_evictions: u32,
    /// M138: Maximum concurrent outbound peer connections.
    pub max_concurrent_connects: u16,
    /// M147: Seconds without TCP SYN-ACK before soft reap disconnects.
    pub connect_soft_timeout: u64,
    /// M182: dispatch-channel reader-side spill cap (default 8).
    pub dispatch_backlog_cap: usize,
    /// M182: event-channel reader-side spill cap (default 32).
    pub event_backlog_cap: usize,
    /// M187 A/B: use actor-centralised dispatch (true) or per-peer CAS dispatch (false).
    pub use_actor_dispatch: bool,
    /// v0.186.1: when `true`, snapshot publishes that overflow the
    /// dispatch channel disconnect the peer fatally (regression mode).
    /// M178: Per-URL minimum interval between `PeerEvent::WebSeedProgress`
    /// emissions. `0` disables the throttle (every chunk emits).
    pub web_seed_progress_throttle_ms: u64,
    /// URL security configuration for SSRF mitigation and IDNA checking.
    pub url_security: crate::url_guard::UrlSecurityConfig,
    /// Timeout in seconds for outbound TCP peer connections (0 = OS default).
    pub peer_connect_timeout: u64,
    /// DSCP (Differentiated Services Code Point) value for peer traffic sockets.
    pub peer_dscp: u8,
    /// Fixed per-peer request queue depth for the lifetime of the connection.
    pub initial_queue_depth: usize,
    /// Maximum per-peer request queue depth.
    pub max_request_queue_depth: usize,
    /// Deprecated — unused in the fixed-depth pipeline model. Retained for API
    /// compatibility; was formerly used to scale BDP-based queue depth.
    pub request_queue_time: f64,
    /// Maximum BEP 9 metadata size in bytes accepted from peers.
    pub max_metadata_size: u64,
    /// Maximum wire protocol message size in bytes for the codec.
    pub max_message_size: usize,
    /// Maximum accepted piece length when adding a torrent.
    pub max_piece_length: u64,
    /// Maximum outstanding incoming requests per peer.
    pub max_outstanding_requests: usize,
    /// Maximum number of pieces simultaneously in-flight (downloaded but not
    /// yet verified).
    pub max_in_flight_pieces: usize,
    /// M103: Enable block-level stealing for partially-downloaded pieces.
    pub use_block_stealing: bool,
    /// M132: Seconds between steal-queue population scans (0 = disabled).
    pub steal_stale_piece_secs: u64,
    /// M104: Fixed per-peer pipeline depth (concurrent requests per peer).
    pub fixed_pipeline_depth: usize,
    /// M120: Lock timing warning threshold in milliseconds (0 = disabled).
    pub lock_warn_threshold_ms: u64,
    /// M127: Enable direct I/O for filesystem storage (`O_DIRECT` / `F_NOCACHE`).
    pub filesystem_direct_io: bool,
    /// M170: Per-torrent category label (qBt-compat). `None` = uncategorised.
    /// Resolved at add-time from the category registry; stored here so the
    /// `TorrentActor` can surface it through `TorrentStats`.
    pub category: Option<String>,
    /// M171: Per-torrent tags (qBt-compat). Multi-valued, free-form. Stored
    /// here so that `TorrentStats.tags` and resume-data persistence both read
    /// from the same source of truth.
    pub tags: Vec<String>,
}

impl Default for TorrentConfig {
    fn default() -> Self {
        Self {
            listen_port: 6881,
            max_peers: 128,
            target_request_queue: 5,
            download_dir: PathBuf::from("."),
            enable_dht: true,
            enable_pex: true,
            enable_fast: false,
            seed_ratio_limit: None,
            seed_time_limit_secs: None,
            inactive_seed_time_limit_secs: None,
            strict_end_game: true,
            upload_rate_limit: 0,
            download_rate_limit: 0,
            max_uploads_per_torrent: -1,
            encryption_mode: irontide_wire::mse::EncryptionMode::Disabled,
            enable_utp: true,
            enable_web_seed: true,
            enable_holepunch: true,
            enable_bep40_eviction: true,
            max_web_seeds: 4,
            web_seed_retry_base_secs: 10,
            web_seed_retry_factor: 6,
            web_seed_retry_cap_secs: 3600,
            web_seed_max_failures: 10,
            super_seeding: false,
            upload_only_announce: true,
            hashing_threads: {
                let cores = std::thread::available_parallelism().map_or(4, std::num::NonZero::get);
                (cores / 4).clamp(2, 8)
            },
            sequential_download: false,
            initial_picker_threshold: 4,
            whole_pieces_threshold: 20,
            snub_timeout_secs: 15,
            readahead_pieces: 8,
            streaming_timeout_escalation: true,
            max_concurrent_stream_reads: 8,
            proxy: crate::proxy::ProxyConfig::default(),
            anonymous_mode: false,
            share_mode: false,
            enable_i2p: false,
            allow_i2p_mixed: false,
            ssl_listen_port: 0,
            seed_choking_algorithm: SeedChokingAlgorithm::FastestUpload,
            choking_algorithm: ChokingAlgorithm::FixedSlots,
            piece_extent_affinity: true,
            suggest_mode: false,
            max_suggest_pieces: 10,
            predictive_piece_announce_ms: 0,
            mixed_mode_algorithm: crate::rate_limiter::MixedModeAlgorithm::PeerProportional,
            auto_sequential: true,
            storage_mode: irontide_core::StorageMode::Auto,
            preallocate_mode: None,
            block_request_timeout_secs: 60,
            enable_lsd: true,
            force_proxy: false,
            steal_threshold_ratio: 10.0,
            steal_threshold_endgame: 3.0,
            peer_read_timeout_secs: 10,
            peer_write_timeout_secs: 10,
            data_contribution_timeout_secs: 0,
            // v0.187.3 eviction defaults — mirror settings.rs values.
            pass0_grace_secs: 60,
            proactive_evictions_per_minute_limit: 30,
            eviction_ban_duration_secs: 600,
            eviction_ban_set_cap: 1024,
            choke_rotation_max_evictions: 0,
            max_concurrent_connects: 128,
            connect_soft_timeout: 3,
            dispatch_backlog_cap: 8,
            event_backlog_cap: 32,
            use_actor_dispatch: true,
            web_seed_progress_throttle_ms: 250,
            url_security: crate::url_guard::UrlSecurityConfig::default(),
            peer_connect_timeout: 10,
            peer_dscp: 0x08,
            initial_queue_depth: 128,
            max_request_queue_depth: 250,
            request_queue_time: 3.0,
            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,
            use_block_stealing: true,
            steal_stale_piece_secs: 2,
            fixed_pipeline_depth: 128,
            lock_warn_threshold_ms: 50,
            filesystem_direct_io: false,
            category: None,
            tags: Vec::new(),
        }
    }
}

impl From<&crate::settings::Settings> for TorrentConfig {
    fn from(s: &crate::settings::Settings) -> Self {
        Self {
            listen_port: 0, // Each torrent gets a random port (matches make_torrent_config)
            max_peers: s.max_peers_per_torrent,
            target_request_queue: 5,
            download_dir: s.download_dir.clone(),
            enable_dht: s.enable_dht,
            enable_pex: s.enable_pex,
            enable_fast: s.enable_fast_extension,
            seed_ratio_limit: s.seed_ratio_limit,
            seed_time_limit_secs: s.seed_time_limit_secs,
            inactive_seed_time_limit_secs: s.inactive_seed_time_limit_secs,
            strict_end_game: s.strict_end_game,
            upload_rate_limit: s.upload_rate_limit,
            download_rate_limit: s.download_rate_limit,
            max_uploads_per_torrent: s.max_uploads_per_torrent,
            encryption_mode: s.encryption_mode,
            enable_utp: s.enable_utp,
            enable_web_seed: s.enable_web_seed,
            enable_holepunch: s.enable_holepunch,
            enable_bep40_eviction: s.enable_bep40_eviction,
            max_web_seeds: s.max_web_seeds,
            web_seed_retry_base_secs: s.web_seed_retry_base_secs,
            web_seed_retry_factor: s.web_seed_retry_factor,
            web_seed_retry_cap_secs: s.web_seed_retry_cap_secs,
            web_seed_max_failures: s.web_seed_max_failures,
            super_seeding: s.default_super_seeding,
            upload_only_announce: s.upload_only_announce,
            hashing_threads: s.hashing_threads,
            sequential_download: false,
            initial_picker_threshold: s.initial_picker_threshold,
            whole_pieces_threshold: s.whole_pieces_threshold,
            snub_timeout_secs: s.snub_timeout_secs,
            readahead_pieces: s.readahead_pieces,
            streaming_timeout_escalation: s.streaming_timeout_escalation,
            max_concurrent_stream_reads: s.max_concurrent_stream_reads,
            proxy: s.proxy.clone(),
            anonymous_mode: s.anonymous_mode,
            share_mode: s.default_share_mode,
            enable_i2p: s.enable_i2p,
            allow_i2p_mixed: s.allow_i2p_mixed,
            ssl_listen_port: s.ssl_listen_port,
            seed_choking_algorithm: s.seed_choking_algorithm,
            choking_algorithm: s.choking_algorithm,
            piece_extent_affinity: s.piece_extent_affinity,
            suggest_mode: s.suggest_mode,
            max_suggest_pieces: s.max_suggest_pieces,
            predictive_piece_announce_ms: s.predictive_piece_announce_ms,
            mixed_mode_algorithm: s.mixed_mode_algorithm,
            auto_sequential: s.auto_sequential,
            storage_mode: s.storage_mode,
            preallocate_mode: s.preallocate_mode,
            block_request_timeout_secs: s.block_request_timeout_secs,
            enable_lsd: s.enable_lsd,
            force_proxy: s.force_proxy,
            steal_threshold_ratio: s.steal_threshold_ratio,
            steal_threshold_endgame: s.steal_threshold_endgame,
            peer_read_timeout_secs: s.peer_read_timeout_secs,
            peer_write_timeout_secs: s.peer_write_timeout_secs,
            data_contribution_timeout_secs: s.data_contribution_timeout_secs,
            pass0_grace_secs: s.pass0_grace_secs,
            proactive_evictions_per_minute_limit: s.proactive_evictions_per_minute_limit,
            eviction_ban_duration_secs: s.eviction_ban_duration_secs,
            eviction_ban_set_cap: s.eviction_ban_set_cap,
            choke_rotation_max_evictions: s.choke_rotation_max_evictions,
            max_concurrent_connects: s.max_concurrent_connects,
            connect_soft_timeout: s.connect_soft_timeout,
            dispatch_backlog_cap: s.dispatch_backlog_cap,
            event_backlog_cap: s.event_backlog_cap,
            use_actor_dispatch: s.use_actor_dispatch,
            web_seed_progress_throttle_ms: s.web_seed_progress_throttle_ms,
            url_security: crate::url_guard::UrlSecurityConfig::from(s),
            peer_connect_timeout: s.peer_connect_timeout,
            peer_dscp: s.peer_dscp,
            initial_queue_depth: s.initial_queue_depth,
            max_request_queue_depth: s.max_request_queue_depth,
            request_queue_time: s.request_queue_time,
            max_metadata_size: s.max_metadata_size,
            max_message_size: s.max_message_size,
            max_piece_length: s.max_piece_length,
            max_outstanding_requests: s.max_outstanding_requests,
            max_in_flight_pieces: s.max_in_flight_pieces,
            use_block_stealing: s.use_block_stealing,
            steal_stale_piece_secs: s.steal_stale_piece_secs,
            fixed_pipeline_depth: s.fixed_pipeline_depth,
            lock_warn_threshold_ms: s.lock_warn_threshold_ms,
            filesystem_direct_io: s.filesystem_direct_io,
            // M170: category is not in Settings (it lives in the per-torrent
            // registry); the session actor overrides it on add if the caller
            // specified one.
            category: None,
            // M171: tags are per-torrent, not session-wide. Populated by the
            // session actor when adding via AddTorrentParams::with_tags().
            tags: Vec::new(),
        }
    }
}

/// Current state of a torrent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TorrentState {
    /// Waiting for peers to send torrent metadata via BEP 9.
    FetchingMetadata,
    /// Verifying existing data on disk against piece hashes.
    Checking,
    /// Actively downloading pieces from peers.
    Downloading,
    /// All pieces downloaded, awaiting transition to seeding.
    Complete,
    /// Upload-only: all pieces verified, serving to other peers.
    Seeding,
    /// Manually paused by the user. No peer connections maintained.
    Paused,
    /// Queued by auto-manage. Peers disconnected; queue evaluator will resume when a slot opens.
    Queued,
    /// Removed from the session. Terminal state.
    Stopped,
    /// Share mode: relay pieces in memory without writing to disk.
    Sharing,
}

/// Aggregate statistics for a torrent.
#[derive(Debug, Clone, Serialize)]
pub struct TorrentStats {
    // ── Original fields (unchanged) ──
    /// Current torrent state.
    pub state: TorrentState,
    /// Total bytes downloaded (payload only).
    pub downloaded: u64,
    /// Total bytes uploaded (payload only).
    pub uploaded: u64,
    /// Number of pieces that have been verified.
    pub pieces_have: u32,
    /// Total number of pieces in the torrent.
    pub pieces_total: u32,
    /// Number of currently connected peers.
    pub peers_connected: usize,
    /// Number of known peers (connected + available).
    pub peers_available: usize,
    /// Progress of piece checking (0.0–1.0), meaningful when state is `Checking`.
    pub checking_progress: f32,
    /// Number of connected peers broken down by discovery source.
    pub peers_by_source: HashMap<crate::peer_state::PeerSource, usize>,

    // ── Identity ──
    /// Info hashes (v1 SHA-1 and/or v2 SHA-256) for this torrent.
    pub info_hashes: irontide_core::InfoHashes,
    /// Display name from the torrent metadata.
    pub name: String,

    // ── State flags ──
    /// Whether metadata has been received (always true for .torrent adds).
    pub has_metadata: bool,
    /// Whether we have all pieces and are seeding.
    pub is_seeding: bool,
    /// Whether all wanted pieces are downloaded (may differ from `is_seeding` with file priorities).
    pub is_finished: bool,
    /// Whether the torrent is paused.
    pub is_paused: bool,
    /// Whether the torrent is queued by auto-manage.
    pub is_queued: bool,
    /// Whether the torrent is auto-managed by the session queuing system.
    pub auto_managed: bool,
    /// Whether sequential piece downloading is enabled.
    pub sequential_download: bool,
    /// Whether BEP 16 super seeding mode is active.
    pub super_seeding: bool,
    /// Whether the user explicitly toggled seed-only mode (M159).
    ///
    /// Distinct from `is_seeding` which reflects download completion.
    /// When `true`, the engine stops scheduling new block requests but
    /// continues to serve uploads to interested peers.
    #[serde(default)]
    pub user_seed_mode: bool,
    /// Whether the user force-started this torrent (bypassing queue limits).
    #[serde(default)]
    pub user_forced: bool,
    /// Per-torrent seed ratio limit override (`None` = use session default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed_ratio_override: Option<f64>,
    /// Whether we have accepted any incoming peer connections.
    pub has_incoming: bool,
    /// Whether resume data needs to be saved.
    pub need_save_resume: bool,
    /// Whether a storage move operation is in progress.
    pub moving_storage: bool,

    // ── Progress ──
    /// Download progress as a fraction (0.0–1.0).
    pub progress: f32,
    /// Download progress in parts per million (`0–1_000_000`).
    pub progress_ppm: u32,
    /// Total bytes of verified (downloaded and hash-checked) data.
    pub total_done: u64,
    /// Total size of the torrent in bytes.
    pub total: u64,
    /// Total bytes of wanted data that have been verified.
    pub total_wanted_done: u64,
    /// Total bytes of wanted data (respecting file priorities).
    pub total_wanted: u64,
    /// Block (sub-piece request) size in bytes.
    pub block_size: u32,

    // ── Transfer (session counters) ──
    /// Total bytes downloaded this session (including protocol overhead).
    pub total_download: u64,
    /// Total bytes uploaded this session (including protocol overhead).
    pub total_upload: u64,
    /// Total payload bytes downloaded this session.
    pub total_payload_download: u64,
    /// Total payload bytes uploaded this session.
    pub total_payload_upload: u64,
    /// Total bytes of data that failed hash check.
    pub total_failed_bytes: u64,
    /// Total bytes of redundant (duplicate) data received.
    pub total_redundant_bytes: u64,

    // ── Transfer (all-time, persisted) ──
    /// All-time total bytes downloaded (persisted across sessions via resume data).
    pub all_time_download: u64,
    /// All-time total bytes uploaded (persisted across sessions via resume data).
    pub all_time_upload: u64,

    // ── Rates ──
    /// Current download rate in bytes/sec (including protocol overhead).
    pub download_rate: u64,
    /// Current upload rate in bytes/sec (including protocol overhead).
    pub upload_rate: u64,
    /// Current payload download rate in bytes/sec.
    pub download_payload_rate: u64,
    /// Current payload upload rate in bytes/sec.
    pub upload_payload_rate: u64,

    // ── Connection details ──
    /// Number of peers connected (including half-open).
    pub num_peers: usize,
    /// Number of connected peers that are seeds.
    pub num_seeds: usize,
    /// Number of complete copies known from tracker scrape (-1 = unknown).
    pub num_complete: i32,
    /// Number of incomplete copies known from tracker scrape (-1 = unknown).
    pub num_incomplete: i32,
    /// Total number of seeds across all trackers.
    pub list_seeds: usize,
    /// Total number of peers across all trackers.
    pub list_peers: usize,
    /// Number of peers available to connect to (not yet connected).
    pub connect_candidates: usize,
    /// Number of active peer connections (TCP + uTP).
    pub num_connections: usize,
    /// Number of unchoked peers we are uploading to.
    pub num_uploads: usize,
    /// M133: Total unique peer connection attempts during this session.
    pub unique_peers_attempted: u64,
    /// M137: Peer pipeline lifecycle snapshot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pipeline: Option<crate::peer_states::PeerPipelineSnapshot>,
    /// M138: Total peers evicted by proactive choke rotation.
    pub choke_rotations: u64,
    /// M149: Total number of piece-level steals performed.
    pub piece_steals: u64,
    /// M190: Total holepunch rendezvous requests relayed to other peers.
    #[serde(default)]
    pub holepunch_relayed: u64,
    /// M187: Pieces queued for dispatch in `PieceTracker` (0 when no tracker).
    #[serde(default)]
    pub dispatch_pieces_queued: u32,
    /// M187: Pieces currently in-flight in `PieceTracker` (0 when no tracker).
    #[serde(default)]
    pub dispatch_pieces_inflight: u32,

    // ── Limits ──
    /// Maximum number of connections for this torrent.
    pub connections_limit: usize,
    /// Maximum number of unchoke slots for this torrent.
    pub uploads_limit: usize,

    // ── Distributed copies ──
    /// Number of full distributed copies available in the swarm.
    pub distributed_full_copies: u32,
    /// Fractional part of distributed copies (0–999).
    pub distributed_fraction: u32,
    /// Distributed copies as a float (full + fraction/1000).
    pub distributed_copies: f32,

    // ── Tracker ──
    /// URL of the tracker we most recently announced to.
    pub current_tracker: String,
    /// Whether we are currently announcing to any tracker.
    pub announcing_to_trackers: bool,
    /// Whether we are currently announcing to LSD (Local Service Discovery).
    pub announcing_to_lsd: bool,
    /// Whether we are currently announcing to DHT.
    pub announcing_to_dht: bool,

    // ── Timestamps (POSIX seconds) ──
    /// Time when the torrent was added to the session.
    pub added_time: i64,
    /// Time when the torrent completed downloading (0 = not completed).
    pub completed_time: i64,
    /// Last time a complete copy was seen in the swarm (0 = never).
    pub last_seen_complete: i64,
    /// Time of last upload activity (0 = never).
    pub last_upload: i64,
    /// Time of last download activity (0 = never).
    pub last_download: i64,

    // ── Durations (cumulative seconds) ──
    /// Total seconds the torrent has been active (downloading or seeding).
    pub active_duration: i64,
    /// Total seconds the torrent has been in finished state.
    pub finished_duration: i64,
    /// Total seconds the torrent has been seeding.
    pub seeding_duration: i64,

    // ── Storage ──
    /// Current save path for the torrent data.
    pub save_path: String,

    // ── Queue ──
    /// Position in the session queue (-1 = not queued).
    pub queue_position: i32,

    // ── Error ──
    /// Human-readable error message (empty = no error).
    pub error: String,
    /// Index of the file that caused the error (-1 = not file-specific).
    pub error_file: i32,

    // ── M170: qBt v2 *arr-minimal surface ──
    /// User-assigned category label (qBt-compat). `None` = uncategorised.
    #[serde(default)]
    pub category: Option<String>,
    /// Torrent creator string (`created by` field of the .torrent). `None`
    /// for magnet-added torrents whose metadata has not yet resolved.
    #[serde(default)]
    pub created_by: Option<String>,
    /// UNIX timestamp (seconds) from the torrent's `creation date` field.
    /// `None` if absent from the .torrent or if metadata has not resolved.
    #[serde(default)]
    pub creation_date: Option<i64>,
    /// Piece length in bytes (from the info dict). `0` if metadata has not
    /// yet resolved for a magnet-added torrent.
    #[serde(default)]
    pub piece_size: u64,

    // ── M171: qBt v2 parity ──
    /// User-assigned tags (qBt-compat). Multi-valued. Empty = no tags.
    #[serde(default)]
    pub tags: Vec<String>,
}

impl Default for TorrentStats {
    fn default() -> Self {
        Self {
            // Original fields
            state: TorrentState::Paused,
            downloaded: 0,
            uploaded: 0,
            pieces_have: 0,
            pieces_total: 0,
            peers_connected: 0,
            peers_available: 0,
            checking_progress: 0.0,
            peers_by_source: HashMap::new(),

            // Identity
            info_hashes: irontide_core::InfoHashes::v1_only(irontide_core::Id20::from([0u8; 20])),
            name: String::new(),

            // State flags
            has_metadata: false,
            is_seeding: false,
            is_finished: false,
            is_paused: false,
            is_queued: false,
            auto_managed: false,
            sequential_download: false,
            super_seeding: false,
            user_seed_mode: false,
            user_forced: false,
            seed_ratio_override: None,
            has_incoming: false,
            need_save_resume: false,
            moving_storage: false,

            // Progress
            progress: 0.0,
            progress_ppm: 0,
            total_done: 0,
            total: 0,
            total_wanted_done: 0,
            total_wanted: 0,
            block_size: 16384,

            // Transfer (session counters)
            total_download: 0,
            total_upload: 0,
            total_payload_download: 0,
            total_payload_upload: 0,
            total_failed_bytes: 0,
            total_redundant_bytes: 0,

            // Transfer (all-time)
            all_time_download: 0,
            all_time_upload: 0,

            // Rates
            download_rate: 0,
            upload_rate: 0,
            download_payload_rate: 0,
            upload_payload_rate: 0,

            // Connection details
            num_peers: 0,
            num_seeds: 0,
            num_complete: -1,
            num_incomplete: -1,
            list_seeds: 0,
            list_peers: 0,
            connect_candidates: 0,
            num_connections: 0,
            num_uploads: 0,
            unique_peers_attempted: 0,
            pipeline: None,
            choke_rotations: 0,
            piece_steals: 0,
            holepunch_relayed: 0,
            dispatch_pieces_queued: 0,
            dispatch_pieces_inflight: 0,

            // Limits
            connections_limit: 0,
            uploads_limit: 0,

            // Distributed copies
            distributed_full_copies: 0,
            distributed_fraction: 0,
            distributed_copies: 0.0,

            // Tracker
            current_tracker: String::new(),
            announcing_to_trackers: false,
            announcing_to_lsd: false,
            announcing_to_dht: false,

            // Timestamps
            added_time: 0,
            completed_time: 0,
            last_seen_complete: 0,
            last_upload: 0,
            last_download: 0,

            // Durations
            active_duration: 0,
            finished_duration: 0,
            seeding_duration: 0,

            // Storage
            save_path: String::new(),

            // Queue
            queue_position: -1,

            // Error
            error: String::new(),
            error_file: -1,

            // M170
            category: None,
            created_by: None,
            creation_date: None,
            piece_size: 0,

            // M171
            tags: Vec::new(),
        }
    }
}

/// Lightweight summary of a torrent for the HTTP API.
///
/// A reduced view of [`TorrentStats`] with only the fields needed for list views.
/// Constructed via `From<&TorrentStats>`.
#[derive(Debug, Clone, Serialize)]
pub struct TorrentSummary {
    /// Hex-encoded v1 info hash (empty string for v2-only torrents).
    pub info_hash: String,
    /// Display name from the torrent metadata.
    pub name: String,
    /// Current torrent state.
    pub state: TorrentState,
    /// Download progress as a fraction (0.0–1.0).
    pub progress: f64,
    /// Current download rate in bytes/sec.
    pub download_rate: u64,
    /// Current upload rate in bytes/sec.
    pub upload_rate: u64,
    /// Total size of the torrent in bytes.
    pub total_size: u64,
    /// Number of connected peers.
    pub num_peers: usize,
    /// Number of connected seeders.
    pub num_seeds: usize,
    /// Total bytes uploaded across all sessions.
    pub all_time_upload: u64,
    /// Total bytes downloaded across all sessions.
    pub all_time_download: u64,
    /// Time when the torrent was added (POSIX seconds).
    pub added_time: i64,
    /// Whether the user has enabled seed-only mode for this torrent.
    pub user_seed_mode: bool,
    /// v0.187.3 / Bug 17: whether BEP 16 super-seeding is active. Surfaced
    /// in the state column so users can see when super-seed mode is on
    /// (previously displayed only "Seeding").
    pub super_seeding: bool,
    /// Whether the user force-started this torrent (bypassing queue limits).
    pub user_forced: bool,
    /// Progress of piece checking (0.0–1.0), meaningful when state is `Checking`.
    pub checking_progress: f32,
}

impl From<&TorrentStats> for TorrentSummary {
    fn from(s: &TorrentStats) -> Self {
        Self {
            info_hash: s.info_hashes.v1.map(|h| h.to_hex()).unwrap_or_default(),
            name: s.name.clone(),
            state: s.state,
            progress: f64::from(s.progress),
            download_rate: s.download_rate,
            upload_rate: s.upload_rate,
            total_size: s.total,
            num_peers: s.num_peers,
            num_seeds: s.num_seeds,
            all_time_upload: s.all_time_upload,
            all_time_download: s.all_time_download,
            added_time: s.added_time,
            user_seed_mode: s.user_seed_mode,
            super_seeding: s.super_seeding,
            user_forced: s.user_forced,
            checking_progress: s.checking_progress,
        }
    }
}

/// Lightweight record of a single block write completion,
/// carried in `PeerEvent::PieceBlocksBatch`.
#[derive(Debug, Clone)]
pub(crate) struct BlockEntry {
    pub index: u32,  // piece index
    pub begin: u32,  // byte offset within piece
    pub length: u32, // block size (usually 16384)
}

/// Events sent from a `PeerTask` back to the `TorrentActor`.
#[derive(Debug)]
#[allow(dead_code)] // consumed by peer/torrent modules (not yet implemented)
pub(crate) enum PeerEvent {
    Bitfield {
        peer_addr: SocketAddr,
        bitfield: Bitfield,
    },
    Have {
        peer_addr: SocketAddr,
        index: u32,
    },
    /// BEP 54: Peer no longer has a piece (`lt_donthave` extension).
    DontHave {
        peer_addr: SocketAddr,
        index: u32,
    },
    PieceData {
        peer_addr: SocketAddr,
        index: u32,
        begin: u32,
        data: Bytes,
    },
    /// Block completion from a peer task's direct disk write.
    /// Sent immediately on each block write for real-time `TorrentActor` visibility.
    PieceBlocksBatch {
        peer_addr: SocketAddr,
        blocks: Vec<BlockEntry>,
    },
    PeerChoking {
        peer_addr: SocketAddr,
        choking: bool,
    },
    PeerInterested {
        peer_addr: SocketAddr,
        interested: bool,
    },
    ExtHandshake {
        peer_addr: SocketAddr,
        handshake: ExtHandshake,
    },
    MetadataPiece {
        peer_addr: SocketAddr,
        piece: u32,
        data: Bytes,
        total_size: u64,
    },
    MetadataReject {
        peer_addr: SocketAddr,
        piece: u32,
    },
    PexPeers {
        new_peers: Vec<SocketAddr>,
    },
    TrackersReceived {
        tracker_urls: Vec<String>,
    },
    IncomingRequest {
        peer_addr: SocketAddr,
        index: u32,
        begin: u32,
        length: u32,
    },
    RejectRequest {
        peer_addr: SocketAddr,
        index: u32,
        begin: u32,
        length: u32,
    },
    AllowedFast {
        peer_addr: SocketAddr,
        index: u32,
    },
    SuggestPiece {
        peer_addr: SocketAddr,
        index: u32,
    },
    /// Peer successfully connected with a specific transport.
    TransportIdentified {
        peer_addr: SocketAddr,
        transport: crate::rate_limiter::PeerTransport,
    },
    /// M140: BT handshake completed successfully — peer is now truly live.
    /// Sent from `run_peer` after BT protocol handshake exchange validates
    /// `info_hash` and `peer_id`. Triggers `mark_live()` in the actor.
    HandshakeComplete {
        peer_addr: SocketAddr,
        /// M174: Whether MSE/PE negotiated RC4 encryption for this connection.
        is_encrypted: bool,
    },
    Disconnected {
        peer_addr: SocketAddr,
        reason: Option<String>,
    },
    WebSeedPieceData {
        url: String,
        index: u32,
        data: Bytes,
    },
    WebSeedError {
        url: String,
        piece: u32,
        message: String,
    },
    /// M178: Periodic per-URL progress update from `WebSeedTask`. Coalesced
    /// by the task's 250 ms throttle (configurable via
    /// `Settings::web_seed_progress_throttle_ms`); the actor accumulates
    /// `WebSeedStats` from these. `error == Some(_)` records a transition
    /// into the errored state; the field is reset to `None` on recovery
    /// emissions but the accumulated `last_error` on `WebSeedStats`
    /// persists per Issue 2.2.
    WebSeedProgress {
        url: String,
        bytes: u64,
        rate_bps: u64,
        error: Option<String>,
    },
    /// M186: Web seed completed backoff and is ready for new piece assignments.
    WebSeedRetryReady {
        url: String,
    },
    /// M186: Web seed permanently failed after max consecutive failures.
    WebSeedPermanentFailure {
        url: String,
    },
    /// BEP 52: Received hash response from peer.
    HashesReceived {
        peer_addr: SocketAddr,
        request: irontide_core::HashRequest,
        hashes: Vec<irontide_core::Id32>,
    },
    /// BEP 52: Peer rejected our hash request.
    HashRequestRejected {
        peer_addr: SocketAddr,
        request: irontide_core::HashRequest,
    },
    /// BEP 52: Peer sent a hash request to us.
    IncomingHashRequest {
        peer_addr: SocketAddr,
        request: irontide_core::HashRequest,
    },
    /// BEP 55: Received a Rendezvous request (we are the relay).
    HolepunchRendezvous {
        peer_addr: SocketAddr,
        target: SocketAddr,
    },
    /// BEP 55: Received a Connect message (we should initiate simultaneous connect).
    HolepunchConnect {
        peer_addr: SocketAddr,
        target: SocketAddr,
    },
    /// BEP 55: Received an Error message from the relay.
    HolepunchError {
        peer_addr: SocketAddr,
        target: SocketAddr,
        error_code: u32,
    },
    /// MSE handshake failed — peer is being retried with a different encryption mode.
    /// Carries the new command channel sender so the `TorrentActor` can
    /// update its `PeerState`.
    MseRetry {
        peer_addr: SocketAddr,
        cmd_tx: tokio::sync::mpsc::Sender<PeerCommand>,
    },
    /// Peer released a piece it was downloading (choke, error, disconnect).
    PieceReleased {
        peer_addr: SocketAddr,
        piece: u32,
    },
    /// M187: Requester asks the actor to acquire a piece via `PieceTracker`.
    /// Actor responds with the piece index via the oneshot, or `NoneAvailable`
    /// if the peer has no dispatchable pieces.
    AcquirePiece {
        peer_addr: SocketAddr,
        response_tx: tokio::sync::oneshot::Sender<crate::piece_reservation::AcquireResponse>,
    },
}

/// Commands sent from the `TorrentActor` to a `PeerTask`.
#[derive(Debug)]
#[allow(dead_code)] // consumed by peer/torrent modules (not yet implemented)
pub(crate) enum PeerCommand {
    Request {
        index: u32,
        begin: u32,
        length: u32,
    },
    Cancel {
        index: u32,
        begin: u32,
        length: u32,
    },
    SetChoking(bool),
    SetInterested(bool),
    Have(u32),
    RequestMetadata {
        piece: u32,
    },
    RejectRequest {
        index: u32,
        begin: u32,
        length: u32,
    },
    AllowedFast(u32),
    SendPiece {
        index: u32,
        begin: u32,
        data: Bytes,
    },
    /// Send an updated extension handshake (e.g. BEP 21 upload-only).
    SendExtHandshake(irontide_wire::ExtHandshake),
    /// BEP 6: Suggest a piece to the peer.
    SuggestPiece(u32),
    /// BEP 52: Send a hash request to the peer.
    SendHashRequest(irontide_core::HashRequest),
    /// BEP 52: Send hashes in response to a peer's request.
    SendHashes {
        request: irontide_core::HashRequest,
        hashes: Vec<irontide_core::Id32>,
    },
    /// BEP 52: Reject a peer's hash request.
    SendHashReject(irontide_core::HashRequest),
    /// BEP 11: Send a PEX message to this peer.
    SendPex {
        message: crate::pex::PexMessage,
    },
    /// BEP 55: Send a holepunch message to this peer.
    SendHolepunch(irontide_wire::HolepunchMessage),
    /// Update the piece count after BEP 9 metadata assembly.
    UpdateNumPieces(u32),
    /// M159: Tell the peer task to stop dispatching block requests.
    ///
    /// Translated to `DispatchCommand::Stop` by the reader loop. The requester
    /// transitions back to the idle state waiting for a fresh `StartRequesting`.
    /// Uploads are unaffected.
    StopRequesting,
    /// M75: Actor sends reservation state to peer task for integrated dispatch.
    /// Sent after metadata download (magnet) or at peer connection (non-magnet).
    StartRequesting {
        piece_notify: std::sync::Arc<tokio::sync::Notify>,
        disk_handle: Option<crate::disk::DiskHandle>,
        write_error_tx: tokio::sync::mpsc::Sender<crate::disk::DiskWriteError>,
        lengths: irontide_core::Lengths,
    },
    Shutdown,
}

/// Helper trait combining [`AsyncRead`] + [`AsyncWrite`] for trait-object erasure.
///
/// Rust doesn't allow `dyn AsyncRead + AsyncWrite` directly, so this trait
/// combines both into a single trait that can be used as a trait object.
pub(crate) trait AsyncReadWrite:
    tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send
{
}

impl<T> AsyncReadWrite for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}

/// Boxed async stream (`AsyncRead` + `AsyncWrite` + Unpin + Send) with a Debug impl.
///
/// Used for incoming SSL peer connections where the concrete TLS type is erased.
pub(crate) struct BoxedAsyncStream(pub Box<dyn AsyncReadWrite>);

impl std::fmt::Debug for BoxedAsyncStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("BoxedAsyncStream(..)")
    }
}

/// Commands sent from a `TorrentHandle` to the `TorrentActor`.
#[derive(Debug)]
#[allow(dead_code)] // consumed by torrent module (not yet implemented)
pub(crate) enum TorrentCommand {
    AddPeers {
        peers: Vec<SocketAddr>,
        source: crate::peer_state::PeerSource,
    },
    Stats {
        reply: oneshot::Sender<TorrentStats>,
    },
    Pause,
    Queue,
    Resume,
    /// Resume the torrent bypassing queue limits (force-start).
    ForceResume,
    Shutdown,
    /// M170: update the category label recorded on this torrent. `None`
    /// clears the label (uncategorised).
    SetCategory {
        category: Option<String>,
        reply: oneshot::Sender<()>,
    },
    /// M171: replace the torrent's tag set wholesale (qBt-compat).
    ///
    /// Mirrors qBt's `addTags` / `removeTags` wire behaviour at the API
    /// layer — always a wholesale replacement at the engine layer.
    SetTags {
        tags: Vec<String>,
        reply: oneshot::Sender<()>,
    },
    /// M171 Lane B: snapshot the list of configured web seed URLs
    /// (BEP 19 `url-list` + BEP 17 `httpseeds`).
    ///
    /// Returns an empty vec when metadata hasn't resolved yet.
    GetWebSeeds {
        reply: oneshot::Sender<Vec<String>>,
    },
    /// M171 Lane B: snapshot the per-piece state array as qBt codes.
    ///
    /// Each element is one of {0: not downloaded, 1: downloading,
    /// 2: downloaded + checked}. Returns an empty vec when metadata
    /// hasn't resolved yet (piece count unknown).
    GetPieceStates {
        reply: oneshot::Sender<Vec<u8>>,
    },
    /// M171 Lane B: return a paginated slice of per-piece hash strings.
    ///
    /// v1 / hybrid torrents return SHA-1 hashes (40-char hex). v2-only
    /// torrents return SHA-256 hashes (64-char hex). Returns an empty
    /// vec when metadata hasn't resolved yet, or when `offset` is past
    /// the end of the hash list.
    GetPieceHashes {
        offset: u32,
        limit: u32,
        reply: oneshot::Sender<Vec<String>>,
    },
    SaveResumeData {
        reply: oneshot::Sender<crate::Result<irontide_core::FastResumeData>>,
    },
    SetFilePriority {
        index: usize,
        priority: irontide_core::FilePriority,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    FilePriorities {
        reply: oneshot::Sender<Vec<irontide_core::FilePriority>>,
    },
    ForceReannounce,
    TrackerList {
        reply: oneshot::Sender<Vec<crate::tracker_manager::TrackerInfo>>,
    },
    Scrape {
        reply: oneshot::Sender<Option<(String, irontide_tracker::ScrapeInfo)>>,
    },
    /// Incoming peer routed from the session-level accept loop (TCP or uTP).
    IncomingPeer {
        stream: crate::transport::BoxedStream,
        addr: SocketAddr,
    },
    /// Open a streaming reader for a file within the torrent.
    OpenFile {
        file_index: usize,
        reply: oneshot::Sender<crate::Result<crate::streaming::FileStreamHandle>>,
    },
    /// Update the external IP for BEP 40 peer priority calculation.
    UpdateExternalIp {
        ip: std::net::IpAddr,
    },
    /// Move torrent data files to a new directory.
    MoveStorage {
        new_path: PathBuf,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Incoming SSL peer routed from the session-level SSL listener (M42).
    ///
    /// The TLS handshake has already been completed by the session actor.
    SpawnSslPeer {
        addr: SocketAddr,
        stream: BoxedAsyncStream,
    },
    /// Set the per-torrent download rate limit (bytes/sec, 0 = unlimited).
    SetDownloadLimit {
        bytes_per_sec: u64,
        reply: oneshot::Sender<()>,
    },
    /// Set the per-torrent upload rate limit (bytes/sec, 0 = unlimited).
    SetUploadLimit {
        bytes_per_sec: u64,
        reply: oneshot::Sender<()>,
    },
    /// Get the current per-torrent download rate limit (bytes/sec, 0 = unlimited).
    DownloadLimit {
        reply: oneshot::Sender<u64>,
    },
    /// Get the current per-torrent upload rate limit (bytes/sec, 0 = unlimited).
    UploadLimit {
        reply: oneshot::Sender<u64>,
    },
    /// Enable or disable sequential (in-order) piece downloading.
    SetSequentialDownload {
        enabled: bool,
        reply: oneshot::Sender<()>,
    },
    /// Query whether sequential downloading is enabled.
    IsSequentialDownload {
        reply: oneshot::Sender<bool>,
    },
    /// Enable or disable BEP 16 super seeding mode.
    SetSuperSeeding {
        enabled: bool,
        reply: oneshot::Sender<()>,
    },
    /// Query whether super seeding mode is enabled.
    IsSuperSeeding {
        reply: oneshot::Sender<bool>,
    },
    /// Enable or disable user-requested seed-only mode (M159).
    ///
    /// When enabled, the torrent stops scheduling new block requests and
    /// cancels all in-flight requests, but continues to serve uploads to
    /// interested peers. Mirrors libtorrent's `seed_mode` flag.
    SetSeedMode {
        enabled: bool,
        reply: oneshot::Sender<()>,
    },
    /// Override the per-torrent seed ratio limit (`None` = use session default).
    SetSeedRatioLimit {
        limit: Option<f64>,
        reply: oneshot::Sender<()>,
    },
    /// Add a new tracker URL (fire-and-forget at torrent level).
    AddTracker {
        url: String,
    },
    /// Replace all tracker URLs with a new set.
    ReplaceTrackers {
        urls: Vec<String>,
        reply: oneshot::Sender<()>,
    },
    /// Trigger a full piece verification (force recheck).
    ForceRecheck {
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Rename a file within the torrent on disk.
    RenameFile {
        file_index: usize,
        new_name: String,
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Set the per-torrent maximum number of connections (0 = use global default).
    SetMaxConnections {
        limit: usize,
        reply: oneshot::Sender<()>,
    },
    /// Get the current per-torrent maximum connection limit.
    MaxConnections {
        reply: oneshot::Sender<usize>,
    },
    /// Set the per-torrent maximum number of unchoke slots (upload slots).
    SetMaxUploads {
        limit: usize,
        reply: oneshot::Sender<()>,
    },
    /// Get the current per-torrent maximum unchoke slots (upload slots).
    MaxUploads {
        reply: oneshot::Sender<usize>,
    },
    /// Get per-peer details for all connected peers.
    GetPeerInfo {
        reply: oneshot::Sender<Vec<PeerInfo>>,
    },
    /// Get in-flight piece download status (the download queue).
    GetDownloadQueue {
        reply: oneshot::Sender<Vec<PartialPieceInfo>>,
    },
    /// Check whether a specific piece has been downloaded.
    HavePiece {
        index: u32,
        reply: oneshot::Sender<bool>,
    },
    /// Get per-piece availability counts from connected peers.
    PieceAvailability {
        reply: oneshot::Sender<Vec<u32>>,
    },
    /// Get per-file bytes-downloaded progress.
    FileProgress {
        reply: oneshot::Sender<Vec<u64>>,
    },
    /// Get the torrent's identity hashes (v1 and/or v2).
    InfoHashes {
        reply: oneshot::Sender<irontide_core::InfoHashes>,
    },
    /// Get the full v1 metainfo (None for magnet links before metadata received).
    TorrentFile {
        reply: oneshot::Sender<Option<irontide_core::TorrentMetaV1>>,
    },
    /// Get the full v2 metainfo (None if not a v2/hybrid torrent or before metadata received).
    TorrentFileV2 {
        reply: oneshot::Sender<Option<irontide_core::TorrentMetaV2>>,
    },
    /// Force an immediate DHT announce (fire-and-forget at torrent level).
    ForceDhtAnnounce,
    /// Read all data for a specific piece from disk.
    ReadPiece {
        index: u32,
        reply: oneshot::Sender<crate::Result<bytes::Bytes>>,
    },
    /// Flush the disk write cache for this torrent.
    FlushCache {
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// Clear the error state and resume if the torrent was paused due to error.
    ClearError,
    /// Get per-file open/mode status based on torrent state.
    FileStatus {
        reply: oneshot::Sender<Vec<crate::types::FileStatus>>,
    },
    /// Read the current torrent flags as a bitflag set.
    Flags {
        reply: oneshot::Sender<TorrentFlags>,
    },
    /// Set (enable) the specified torrent flags.
    SetFlags {
        flags: TorrentFlags,
        reply: oneshot::Sender<()>,
    },
    /// Unset (disable) the specified torrent flags.
    UnsetFlags {
        flags: TorrentFlags,
        reply: oneshot::Sender<()>,
    },
    /// Immediately initiate a peer connection to the given address.
    ConnectPeer {
        addr: SocketAddr,
    },
    /// Clear the `need_save_resume` dirty flag after a successful file save (M161).
    ClearSaveResumeFlag,
    /// Restore a piece bitmap from resume data (M161 Phase 4).
    ///
    /// Replaces the chunk tracker's bitfield with the provided raw piece bytes.
    /// The handler validates the bitfield length before applying.
    RestoreResumeBitmap {
        /// Raw piece bitfield bytes from resume data.
        pieces: Vec<u8>,
        /// Reply with `Ok(())` on success or an error if validation fails.
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// M178: Restore the per-URL web-seed stats map from resume data.
    ///
    /// Used by the post-add resume-restore path so that downloaded-byte
    /// counters and last-error / consecutive-failure state survive app
    /// restart (Tension-1 fast-resume persistence).
    RestoreWebSeedStats {
        /// Map of URL → stats from `FastResumeData::web_seed_stats`.
        stats: HashMap<String, irontide_core::WebSeedStats>,
        /// Reply with `Ok(())` on success.
        reply: oneshot::Sender<crate::Result<()>>,
    },
    /// M178 (Lane B3 / TODO-2): cumulative `(pex, lsd)` unique-peer counts
    /// for the GUI Trackers tab + qBt v2 trackers pseudo-tracker rows.
    GetPeerSourceCounts {
        /// Reply with `(pex_peer_count, lsd_peer_count)`.
        reply: oneshot::Sender<(usize, usize)>,
    },
    /// Per-peer cumulative unchoke duration over the torrent's lifetime.
    /// Keyed by `SocketAddr`; merges live `PeerState` accumulators with
    /// the durable per-torrent map so reconnects preserve history.
    /// Used by libtorrent-mirror perf scenarios that gate on
    /// optimistic-unchoke fairness.
    QueryUnchokeDurations {
        /// Reply with one entry per peer ever unchoked by us.
        reply: oneshot::Sender<HashMap<SocketAddr, std::time::Duration>>,
    },
    /// M178 (Lane C): snapshot of per-URL web-seed stats for the qBt v2
    /// `/api/v2/torrents/webseeds` endpoint and the GUI HTTP Sources tab.
    GetWebSeedStats {
        /// Reply with one entry per URL with active stats.
        reply: oneshot::Sender<Vec<irontide_core::WebSeedStats>>,
    },
    /// M147: Pre-resolved metadata from the background `MetadataResolver`.
    ///
    /// Sent by `SessionActor::spawn_metadata_resolver()` when the background
    /// resolver successfully obtains torrent metadata before the `TorrentActor`'s
    /// own `FetchingMetadata` phase completes. This is a race: first to resolve
    /// wins; the other path's result is silently discarded.
    PreResolvedMetadata {
        /// Raw bencoded info dictionary bytes.
        info_bytes: Vec<u8>,
        /// Peers that were successfully connected during metadata resolution
        /// (for pre-seeding the peer pipeline).
        peers: Vec<SocketAddr>,
    },
    /// v0.173.1: single source of truth for torrent metadata.
    ///
    /// Returns `Some(meta.clone())` if the actor has assembled metadata (via
    /// its own `ut_metadata` fetch or a `PreResolvedMetadata` push), else
    /// `None`. Replaces `SessionActor.TorrentEntry.meta` as the authoritative
    /// source — see class-A archaeology in the v0.173.1 plan file at
    /// `docs/plans/2026-04-22-irontide-v0.173.1-qbt-v2-bug-sweep.md`.
    GetMeta {
        /// Reply with `Some(meta)` when available, `None` for a magnet that
        /// hasn't resolved metadata yet.
        reply: oneshot::Sender<Option<irontide_core::TorrentMetaV1>>,
    },
    /// **TEST-ONLY (v0.173.2).** Synchronously inject a fully-assembled info-dict
    /// payload via the same internal handler as the M147 `PreResolvedMetadata`
    /// path, but with backpressure + completion-ack so tests can rely on the
    /// metadata being processed when the future resolves. The M147 fast-path
    /// uses `try_send` and is fire-and-forget by design (resolver shouldn't
    /// block); this variant is the synchronous-test counterpart.
    #[cfg(feature = "test-util")]
    TestInjectMetadata {
        /// Raw bencoded info dictionary bytes.
        info_bytes: Vec<u8>,
        /// Completion ack — fired after `handle_pre_resolved_metadata` returns.
        reply: oneshot::Sender<()>,
    },
    /// v0.187.1: broadcast changed session-level settings to a running torrent.
    ///
    /// Patches `self.config` fields so that settings changes made via
    /// Preferences → Apply take effect on existing torrents, not just
    /// newly-added ones.
    UpdateSettings(SettingsDelta),
}

/// Delta of session-level settings that should be propagated to running
/// torrents. Built by diffing old vs new `Settings` after `apply_settings`.
/// Only non-`None` fields are applied; `None` means "unchanged".
#[derive(Debug, Clone, Default)]
#[allow(
    clippy::option_option,
    reason = "outer Option = unchanged, inner Option = the actual Settings value (None = unlimited)"
)]
pub struct SettingsDelta {
    pub enable_dht: Option<bool>,
    pub enable_pex: Option<bool>,
    pub max_peers: Option<usize>,
    pub seed_ratio_limit: Option<Option<f64>>,
    pub seed_time_limit_secs: Option<Option<u64>>,
    pub inactive_seed_time_limit_secs: Option<Option<u64>>,
    pub max_ratio_action: Option<crate::MaxRatioAction>,
    pub encryption_mode: Option<irontide_wire::mse::EncryptionMode>,
    pub anonymous_mode: Option<bool>,
    /// M224: per-torrent upload slot cap (`-1` = unlimited, `n >= 1` = cap).
    /// Propagated live to in-flight torrents via `handle_update_settings`.
    pub max_uploads_per_torrent: Option<i32>,
    /// M225 Step 1: periodic resume-save interval
    pub save_resume_interval_secs: Option<u64>,
    /// M225 Step 2: pieces verify concurrency cap
    pub hashing_threads: Option<usize>,
    /// M225 Step 3: IP filter toggle
    pub ip_filter_enabled: Option<bool>,
    // ── M226: Notifications / paths / watched folder / network ──
    /// M226: Fire OS desktop notification on torrent complete.
    pub notify_on_complete: Option<bool>,
    /// M226: Fire OS desktop notification on torrent error.
    pub notify_on_error: Option<bool>,
    /// M226: Path to a program to run on torrent completion. Nested `Option`
    /// — outer `None` = unchanged, inner `None` = clear to default (no program).
    pub on_complete_program: Option<Option<std::path::PathBuf>>,
    /// M226: Whether to use a separate in-progress directory.
    pub use_incomplete_dir: Option<bool>,
    /// M226: In-progress directory. Nested `Option` semantics as above.
    pub incomplete_dir: Option<Option<std::path::PathBuf>>,
    /// M226: Default `skip_checking` for new torrents.
    pub default_skip_hash_check: Option<bool>,
    /// M226: Append `.!ut` to in-progress files.
    pub incomplete_extension_enabled: Option<bool>,
    /// M226: Folder to watch for new `.torrent` files. Nested `Option`.
    pub watched_folder: Option<Option<std::path::PathBuf>>,
    /// M226: Delete source `.torrent` after successful add (else rename).
    pub delete_torrent_after_add: Option<bool>,
    /// M226: Move completed torrents to `move_completed_to`.
    pub move_completed_enabled: Option<bool>,
    /// M226: Move-completed destination. Nested `Option`.
    pub move_completed_to: Option<Option<std::path::PathBuf>>,
    /// M226: Auto-refresh the IP filter when the source file changes.
    /// (Field already existed in Settings; M226 wires the delta plumbing.)
    pub ip_filter_auto_refresh: Option<bool>,
    /// M226: Enable `HTTPS` for the qBt v2 `WebUI` listener (stored only).
    pub web_ui_https_enabled: Option<bool>,
    /// M226: Bind peer listeners to a specific network interface. Nested `Option`.
    pub network_interface: Option<Option<String>>,
    /// M226: Default value for `AddTorrentParams.paused` when caller passes `None`.
    pub default_add_paused: Option<bool>,
}

impl SettingsDelta {
    #[must_use]
    pub fn from_diff(old: &crate::settings::Settings, new: &crate::settings::Settings) -> Self {
        let mut d = Self::default();
        if old.enable_dht != new.enable_dht {
            d.enable_dht = Some(new.enable_dht);
        }
        if old.enable_pex != new.enable_pex {
            d.enable_pex = Some(new.enable_pex);
        }
        if old.max_peers_per_torrent != new.max_peers_per_torrent {
            d.max_peers = Some(new.max_peers_per_torrent);
        }
        if old.seed_ratio_limit != new.seed_ratio_limit {
            d.seed_ratio_limit = Some(new.seed_ratio_limit);
        }
        if old.seed_time_limit_secs != new.seed_time_limit_secs {
            d.seed_time_limit_secs = Some(new.seed_time_limit_secs);
        }
        if old.inactive_seed_time_limit_secs != new.inactive_seed_time_limit_secs {
            d.inactive_seed_time_limit_secs = Some(new.inactive_seed_time_limit_secs);
        }
        if old.max_ratio_action != new.max_ratio_action {
            d.max_ratio_action = Some(new.max_ratio_action);
        }
        if old.encryption_mode != new.encryption_mode {
            d.encryption_mode = Some(new.encryption_mode);
        }
        if old.anonymous_mode != new.anonymous_mode {
            d.anonymous_mode = Some(new.anonymous_mode);
        }
        if old.max_uploads_per_torrent != new.max_uploads_per_torrent {
            d.max_uploads_per_torrent = Some(new.max_uploads_per_torrent);
        }
        if old.save_resume_interval_secs != new.save_resume_interval_secs {
            d.save_resume_interval_secs = Some(new.save_resume_interval_secs);
        }
        if old.hashing_threads != new.hashing_threads {
            d.hashing_threads = Some(new.hashing_threads);
        }
        if old.ip_filter_enabled != new.ip_filter_enabled {
            d.ip_filter_enabled = Some(new.ip_filter_enabled);
        }
        // ── M226 ──
        if old.notify_on_complete != new.notify_on_complete {
            d.notify_on_complete = Some(new.notify_on_complete);
        }
        if old.notify_on_error != new.notify_on_error {
            d.notify_on_error = Some(new.notify_on_error);
        }
        if old.on_complete_program != new.on_complete_program {
            d.on_complete_program = Some(new.on_complete_program.clone());
        }
        if old.use_incomplete_dir != new.use_incomplete_dir {
            d.use_incomplete_dir = Some(new.use_incomplete_dir);
        }
        if old.incomplete_dir != new.incomplete_dir {
            d.incomplete_dir = Some(new.incomplete_dir.clone());
        }
        if old.default_skip_hash_check != new.default_skip_hash_check {
            d.default_skip_hash_check = Some(new.default_skip_hash_check);
        }
        if old.incomplete_extension_enabled != new.incomplete_extension_enabled {
            d.incomplete_extension_enabled = Some(new.incomplete_extension_enabled);
        }
        if old.watched_folder != new.watched_folder {
            d.watched_folder = Some(new.watched_folder.clone());
        }
        if old.delete_torrent_after_add != new.delete_torrent_after_add {
            d.delete_torrent_after_add = Some(new.delete_torrent_after_add);
        }
        if old.move_completed_enabled != new.move_completed_enabled {
            d.move_completed_enabled = Some(new.move_completed_enabled);
        }
        if old.move_completed_to != new.move_completed_to {
            d.move_completed_to = Some(new.move_completed_to.clone());
        }
        if old.ip_filter_auto_refresh != new.ip_filter_auto_refresh {
            d.ip_filter_auto_refresh = Some(new.ip_filter_auto_refresh);
        }
        if old.web_ui_https_enabled != new.web_ui_https_enabled {
            d.web_ui_https_enabled = Some(new.web_ui_https_enabled);
        }
        if old.network_interface != new.network_interface {
            d.network_interface = Some(new.network_interface.clone());
        }
        if old.default_add_paused != new.default_add_paused {
            d.default_add_paused = Some(new.default_add_paused);
        }
        d
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.enable_dht.is_none()
            && self.enable_pex.is_none()
            && self.max_peers.is_none()
            && self.seed_ratio_limit.is_none()
            && self.seed_time_limit_secs.is_none()
            && self.inactive_seed_time_limit_secs.is_none()
            && self.max_ratio_action.is_none()
            && self.encryption_mode.is_none()
            && self.anonymous_mode.is_none()
            && self.max_uploads_per_torrent.is_none()
            && self.save_resume_interval_secs.is_none()
            && self.hashing_threads.is_none()
            && self.ip_filter_enabled.is_none()
            // ── M226 ──
            && self.notify_on_complete.is_none()
            && self.notify_on_error.is_none()
            && self.on_complete_program.is_none()
            && self.use_incomplete_dir.is_none()
            && self.incomplete_dir.is_none()
            && self.default_skip_hash_check.is_none()
            && self.incomplete_extension_enabled.is_none()
            && self.watched_folder.is_none()
            && self.delete_torrent_after_add.is_none()
            && self.move_completed_enabled.is_none()
            && self.move_completed_to.is_none()
            && self.ip_filter_auto_refresh.is_none()
            && self.web_ui_https_enabled.is_none()
            && self.network_interface.is_none()
            && self.default_add_paused.is_none()
    }
}


/// Per-peer details exported for client UI introspection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerInfo {
    /// Remote peer address (IP + port).
    pub addr: SocketAddr,
    /// Client identification string (from extension handshake `v` field, or empty).
    pub client: String,
    /// Whether the peer is choking us.
    pub peer_choking: bool,
    /// Whether the peer is interested in our data.
    pub peer_interested: bool,
    /// Whether we are choking the peer.
    pub am_choking: bool,
    /// Whether we are interested in the peer's data.
    pub am_interested: bool,
    /// Current download rate from this peer in bytes/sec.
    pub download_rate: u64,
    /// Current upload rate to this peer in bytes/sec.
    pub upload_rate: u64,
    /// Number of pieces the peer has (bitfield population count).
    pub num_pieces: u32,
    /// How the peer was discovered.
    pub source: crate::peer_state::PeerSource,
    /// Whether the peer supports BEP 6 Fast Extension.
    pub supports_fast: bool,
    /// Whether the peer declared upload-only status (BEP 21).
    pub upload_only: bool,
    /// Whether the peer is snubbed (no data for `snub_timeout_secs`).
    pub snubbed: bool,
    /// Seconds since the peer connection was established.
    pub connected_duration_secs: u64,
    /// Number of outstanding piece requests to this peer.
    pub num_pending_requests: usize,
    /// Number of incoming piece requests from this peer.
    pub num_incoming_requests: usize,
    /// Whether the peer currently holds our optimistic-unchoke slot
    /// (M171 D5; maps to the `O` peer-flag glyph). Not yet wired from
    /// the choker — placeholder for the superset renderer.
    #[serde(default)]
    pub is_optimistic: bool,
    /// Whether the peer connection is encrypted via BEP 8 MSE/PE
    /// (M171 D5; maps to `E` glyph). Not yet wired from the handshake
    /// state — placeholder for the superset renderer.
    #[serde(default)]
    pub is_encrypted: bool,
    /// Whether the peer connection uses BEP 29 uTP (not raw TCP)
    /// (M171 D5; maps to `P` glyph).
    #[serde(default)]
    pub uses_utp: bool,
    /// Whether the peer advertised BEP 55 holepunch support during the
    /// extended handshake (M171 D5; tracked for observability — no
    /// qBt glyph is assigned to holepunch).
    #[serde(default)]
    pub uses_holepunch: bool,
    /// M187: current number of in-flight block requests to this peer.
    #[serde(default)]
    pub in_flight_requests: u32,
    /// M187: current target pipeline depth for this peer.
    #[serde(default)]
    pub target_pipeline_depth: u32,
}

/// In-flight piece download status for the download queue.
#[derive(Debug, Clone, Serialize)]
pub struct PartialPieceInfo {
    /// Index of the piece being downloaded.
    pub piece_index: u32,
    /// Total number of blocks in this piece.
    pub blocks_in_piece: u32,
    /// Number of blocks that have been assigned to peers.
    pub blocks_assigned: u32,
}

/// Info about a file within a torrent.
#[derive(Debug, Clone, Serialize)]
pub struct FileInfo {
    /// Relative path of the file within the torrent.
    pub path: PathBuf,
    /// File size in bytes.
    pub length: u64,
}

/// Metadata about a torrent (available after metadata is fetched).
#[derive(Debug, Clone, Serialize)]
pub struct TorrentInfo {
    /// SHA-1 info hash of the torrent.
    pub info_hash: irontide_core::Id20,
    /// Display name from the torrent metadata.
    pub name: String,
    /// Total size of all files in bytes.
    pub total_length: u64,
    /// Size of each piece in bytes (last piece may be smaller).
    pub piece_length: u64,
    /// Total number of pieces in the torrent.
    pub num_pieces: u32,
    /// List of files contained in the torrent.
    pub files: Vec<FileInfo>,
    /// Whether this is a private torrent (DHT/PEX disabled).
    pub private: bool,
}

/// Aggregate statistics for the whole session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionStats {
    /// Number of non-paused torrents in the session.
    pub active_torrents: usize,
    /// Total bytes downloaded across all torrents since session start.
    pub total_downloaded: u64,
    /// Total bytes uploaded across all torrents since session start.
    pub total_uploaded: u64,
    /// Number of nodes in the DHT routing table.
    pub dht_nodes: usize,
}

/// Whether a file in a torrent is open and its I/O access mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum FileMode {
    /// File is open for reading only (e.g. seeding).
    ReadOnly,
    /// File is open for reading and writing (e.g. downloading).
    ReadWrite,
    /// File is not currently open.
    Closed,
}

/// Status of a single file within a torrent.
#[derive(Debug, Clone, Serialize)]
pub struct FileStatus {
    /// Whether the file is currently open.
    pub open: bool,
    /// The current access mode.
    pub mode: FileMode,
}

bitflags! {
    /// Bitflag convenience wrapper for common torrent state flags.
    ///
    /// These map to existing torrent actor fields; `set_flags` / `unset_flags`
    /// delegate to the underlying operations (pause/resume, set_sequential, etc.).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct TorrentFlags: u32 {
        /// Torrent is paused.
        const PAUSED = 0x1;
        /// Torrent is auto-managed by the session queuing system.
        const AUTO_MANAGED = 0x2;
        /// Sequential (in-order) piece downloading is enabled.
        const SEQUENTIAL_DOWNLOAD = 0x4;
        /// BEP 16 super seeding mode is active.
        const SUPER_SEEDING = 0x8;
        /// Upload-only status (seeding complete, no wanted pieces).
        const UPLOAD_ONLY = 0x10;
    }
}

// ── M187 Debug state DTOs ──

/// Top-level debug state snapshot for all torrents in the session.
#[derive(Debug, Clone, Serialize)]
pub struct DebugState {
    /// Per-torrent debug snapshots.
    pub torrents: Vec<DebugTorrentState>,
}

/// Per-torrent debug state including dispatch counters and peer details.
#[derive(Debug, Clone, Serialize)]
pub struct DebugTorrentState {
    /// Hex-encoded info hash.
    pub info_hash: String,
    /// Current torrent state (e.g. "Downloading", "Seeding").
    pub state: String,
    /// Number of connected peers.
    #[serde(default)]
    pub num_peers: usize,
    /// Dispatch-level counters.
    #[serde(default)]
    pub dispatch: DebugDispatchState,
    /// Per-peer debug state.
    #[serde(default)]
    pub peers: Vec<DebugPeerState>,
}

/// Dispatch-level diagnostic counters (session-wide + per-torrent).
#[derive(Debug, Clone, Default, Serialize)]
pub struct DebugDispatchState {
    /// Total acquire calls.
    #[serde(default)]
    pub acquire_total: i64,
    /// Acquire calls that returned None (no block available).
    #[serde(default)]
    pub acquire_none_total: i64,
    /// Cumulative acquire latency in microseconds.
    #[serde(default)]
    pub acquire_us: i64,
    /// Total notify wakeup events.
    #[serde(default)]
    pub notify_wakeup_total: i64,
    /// Pieces still queued for dispatch (per-torrent).
    #[serde(default)]
    pub pieces_queued: u32,
    /// Pieces currently in-flight (per-torrent).
    #[serde(default)]
    pub pieces_inflight: u32,
}

/// Per-peer debug state for diagnosing throughput issues.
#[derive(Debug, Clone, Serialize)]
pub struct DebugPeerState {
    /// Remote peer socket address.
    pub addr: SocketAddr,
    /// Number of in-flight block requests.
    #[serde(default)]
    pub in_flight: u32,
    /// Current target pipeline depth.
    #[serde(default)]
    pub target_depth: u32,
    /// Whether the peer is choking us.
    #[serde(default)]
    pub choking: bool,
    /// Current download rate in bytes/sec.
    #[serde(default)]
    pub download_rate: u64,
}

/// Type alias for a factory that creates per-torrent storage.
pub type StorageFactory = Box<
    dyn Fn(
            &irontide_core::TorrentMetaV1,
            &std::path::Path,
        ) -> std::sync::Arc<dyn irontide_storage::TorrentStorage>
        + Send
        + Sync,
>;

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

    #[test]
    fn torrent_config_strict_end_game_default() {
        let config = TorrentConfig::default();
        assert!(config.strict_end_game);
    }

    #[test]
    fn torrent_config_bandwidth_defaults() {
        let config = TorrentConfig::default();
        assert_eq!(config.upload_rate_limit, 0);
        assert_eq!(config.download_rate_limit, 0);
    }

    #[test]
    fn torrent_config_encryption_default() {
        let cfg = TorrentConfig::default();
        assert_eq!(
            cfg.encryption_mode,
            irontide_wire::mse::EncryptionMode::Disabled
        );
    }

    #[test]
    fn torrent_config_utp_default() {
        let cfg = TorrentConfig::default();
        assert!(cfg.enable_utp);
    }

    #[test]
    fn torrent_config_web_seed_defaults() {
        let cfg = TorrentConfig::default();
        assert!(cfg.enable_web_seed);
        assert_eq!(cfg.max_web_seeds, 4);
    }

    #[test]
    fn torrent_config_super_seeding_default() {
        let cfg = TorrentConfig::default();
        assert!(!cfg.super_seeding);
        assert!(cfg.upload_only_announce);
    }

    #[test]
    fn torrent_config_picker_defaults() {
        let cfg = TorrentConfig::default();
        assert!(!cfg.sequential_download);
        assert_eq!(cfg.initial_picker_threshold, 4);
        assert_eq!(cfg.whole_pieces_threshold, 20);
        assert_eq!(cfg.snub_timeout_secs, 15);
        assert_eq!(cfg.readahead_pieces, 8);
        assert!(cfg.streaming_timeout_escalation);
    }

    #[test]
    fn torrent_stats_has_peers_by_source() {
        use crate::peer_state::PeerSource;
        use std::collections::HashMap;

        let stats = TorrentStats {
            state: TorrentState::Downloading,
            pieces_total: 10,
            ..Default::default()
        };
        assert!(stats.peers_by_source.is_empty());

        let mut map = HashMap::new();
        map.insert(PeerSource::Tracker, 5);
        map.insert(PeerSource::Dht, 3);
        let stats2 = TorrentStats {
            peers_by_source: map.clone(),
            ..stats
        };
        assert_eq!(stats2.peers_by_source[&PeerSource::Tracker], 5);
        assert_eq!(stats2.peers_by_source[&PeerSource::Dht], 3);
    }

    #[test]
    fn torrent_stats_default_values() {
        let stats = TorrentStats::default();

        // State
        assert_eq!(stats.state, TorrentState::Paused);

        // Original fields are zeroed
        assert_eq!(stats.downloaded, 0);
        assert_eq!(stats.uploaded, 0);
        assert_eq!(stats.pieces_have, 0);
        assert_eq!(stats.pieces_total, 0);
        assert_eq!(stats.peers_connected, 0);
        assert_eq!(stats.peers_available, 0);
        assert!((stats.checking_progress - 0.0).abs() < f32::EPSILON);
        assert!(stats.peers_by_source.is_empty());

        // Identity: zeroed info hash
        assert_eq!(
            stats.info_hashes,
            irontide_core::InfoHashes::v1_only(irontide_core::Id20::from([0u8; 20]))
        );
        assert!(stats.name.is_empty());

        // State flags are all false
        assert!(!stats.has_metadata);
        assert!(!stats.is_seeding);
        assert!(!stats.is_finished);
        assert!(!stats.is_paused);
        assert!(!stats.auto_managed);
        assert!(!stats.sequential_download);
        assert!(!stats.super_seeding);
        assert!(!stats.has_incoming);
        assert!(!stats.need_save_resume);
        assert!(!stats.moving_storage);

        // Progress
        assert!((stats.progress - 0.0).abs() < f32::EPSILON);
        assert_eq!(stats.progress_ppm, 0);
        assert_eq!(stats.total_done, 0);
        assert_eq!(stats.total, 0);
        assert_eq!(stats.total_wanted_done, 0);
        assert_eq!(stats.total_wanted, 0);
        assert_eq!(stats.block_size, 16384);

        // Sentinel values
        assert_eq!(stats.num_complete, -1);
        assert_eq!(stats.num_incomplete, -1);
        assert_eq!(stats.queue_position, -1);
        assert_eq!(stats.error_file, -1);

        // Strings are empty
        assert!(stats.current_tracker.is_empty());
        assert!(stats.save_path.is_empty());
        assert!(stats.error.is_empty());

        // Rates are zero
        assert_eq!(stats.download_rate, 0);
        assert_eq!(stats.upload_rate, 0);
        assert_eq!(stats.download_payload_rate, 0);
        assert_eq!(stats.upload_payload_rate, 0);

        // Distributed copies
        assert_eq!(stats.distributed_full_copies, 0);
        assert_eq!(stats.distributed_fraction, 0);
        assert!((stats.distributed_copies - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn torrent_stats_seeding_flags() {
        let stats = TorrentStats {
            state: TorrentState::Seeding,
            is_seeding: true,
            is_finished: true,
            has_metadata: true,
            progress: 1.0,
            progress_ppm: 1_000_000,
            ..Default::default()
        };
        assert_eq!(stats.state, TorrentState::Seeding);
        assert!(stats.is_seeding);
        assert!(stats.is_finished);
        assert!(stats.has_metadata);
        assert!((stats.progress - 1.0).abs() < f32::EPSILON);
        assert_eq!(stats.progress_ppm, 1_000_000);
        // Other fields remain default
        assert!(!stats.is_paused);
        assert_eq!(stats.downloaded, 0);
    }

    #[test]
    fn torrent_state_sharing_variant() {
        let state = TorrentState::Sharing;
        assert_ne!(state, TorrentState::Downloading);
        assert_ne!(state, TorrentState::Seeding);
        // Verify JSON round-trip
        let json = serde_json::to_string(&state).unwrap();
        assert_eq!(json, "\"Sharing\"");
        let decoded: TorrentState = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, TorrentState::Sharing);
    }

    #[test]
    fn torrent_config_i2p_defaults() {
        let cfg = TorrentConfig::default();
        assert!(!cfg.enable_i2p);
        assert!(!cfg.allow_i2p_mixed);
    }

    #[test]
    fn torrent_config_ssl_listen_port_default() {
        let cfg = TorrentConfig::default();
        assert_eq!(cfg.ssl_listen_port, 0);
    }

    #[test]
    fn torrent_config_ssl_listen_port_from_settings() {
        let s = crate::settings::Settings {
            ssl_listen_port: 4433,
            ..crate::settings::Settings::default()
        };
        let tc = TorrentConfig::from(&s);
        assert_eq!(tc.ssl_listen_port, 4433);
    }

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

    #[test]
    fn torrent_config_m44_defaults() {
        let cfg = TorrentConfig::default();
        assert!(cfg.piece_extent_affinity);
        assert!(!cfg.suggest_mode);
        assert_eq!(cfg.max_suggest_pieces, 10);
        assert_eq!(cfg.predictive_piece_announce_ms, 0);
    }

    #[test]
    fn torrent_config_from_settings_choking() {
        let s = crate::settings::Settings {
            seed_choking_algorithm: SeedChokingAlgorithm::RoundRobin,
            choking_algorithm: ChokingAlgorithm::RateBased,
            ..crate::settings::Settings::default()
        };
        let cfg = TorrentConfig::from(&s);
        assert_eq!(cfg.seed_choking_algorithm, SeedChokingAlgorithm::RoundRobin);
        assert_eq!(cfg.choking_algorithm, ChokingAlgorithm::RateBased);
    }

    #[test]
    fn torrent_config_holepunch_default() {
        let cfg = TorrentConfig::default();
        assert!(cfg.enable_holepunch);

        // Also verify it inherits from Settings
        let s = crate::settings::Settings::default();
        let tc = TorrentConfig::from(&s);
        assert!(tc.enable_holepunch);

        // And when disabled in Settings
        let s2 = crate::settings::Settings {
            enable_holepunch: false,
            ..crate::settings::Settings::default()
        };
        let tc2 = TorrentConfig::from(&s2);
        assert!(!tc2.enable_holepunch);
    }

    #[test]
    fn torrent_config_url_security_default() {
        let cfg = TorrentConfig::default();
        assert!(cfg.url_security.ssrf_mitigation);
        assert!(!cfg.url_security.allow_idna);
        assert!(cfg.url_security.validate_https_trackers);
    }

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

    #[test]
    fn torrent_config_peer_dscp_default() {
        let cfg = TorrentConfig::default();
        assert_eq!(cfg.peer_dscp, 0x08);
    }

    #[test]
    fn torrent_config_peer_dscp_from_settings() {
        let s = crate::settings::Settings {
            peer_dscp: 0x2E,
            ..crate::settings::Settings::default()
        };
        let cfg = TorrentConfig::from(&s);
        assert_eq!(cfg.peer_dscp, 0x2E);
    }

    // ── M121: TorrentSummary and Serialize tests ──

    #[test]
    fn summary_from_stats() {
        let v1_hash =
            irontide_core::Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let stats = TorrentStats {
            info_hashes: irontide_core::InfoHashes::v1_only(v1_hash),
            name: "test torrent".to_string(),
            state: TorrentState::Downloading,
            progress: 0.75,
            download_rate: 1_000_000,
            upload_rate: 500_000,
            total: 100_000_000,
            num_peers: 42,
            added_time: 1_710_900_000,
            ..TorrentStats::default()
        };

        let summary = super::TorrentSummary::from(&stats);
        assert_eq!(
            summary.info_hash,
            "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
        );
        assert_eq!(summary.name, "test torrent");
        assert_eq!(summary.state, TorrentState::Downloading);
        assert!((summary.progress - 0.75).abs() < f64::EPSILON);
        assert_eq!(summary.download_rate, 1_000_000);
        assert_eq!(summary.upload_rate, 500_000);
        assert_eq!(summary.total_size, 100_000_000);
        assert_eq!(summary.num_peers, 42);
        assert_eq!(summary.added_time, 1_710_900_000);
    }

    #[test]
    fn summary_from_stats_v2_only() {
        let v2_hash = irontide_core::Id32::from_hex(
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        )
        .unwrap();
        let stats = TorrentStats {
            info_hashes: irontide_core::InfoHashes::v2_only(v2_hash),
            name: "v2 torrent".to_string(),
            ..TorrentStats::default()
        };

        let summary = super::TorrentSummary::from(&stats);
        // v2-only torrents have no v1 hash, so info_hash is empty
        assert_eq!(summary.info_hash, "");
        assert_eq!(summary.name, "v2 torrent");
    }

    #[test]
    fn stats_serializable() {
        let stats = TorrentStats::default();
        let json = serde_json::to_string(&stats).expect("TorrentStats should serialize to JSON");
        assert!(json.contains("\"state\""));
        assert!(json.contains("\"info_hashes\""));
        assert!(json.contains("\"download_rate\""));
    }

    #[test]
    fn info_hashes_serializable() {
        let v1 = irontide_core::Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let ih = irontide_core::InfoHashes::v1_only(v1);
        let json = serde_json::to_string(&ih).expect("InfoHashes should serialize to JSON");
        // Id20 serializes as raw bytes (not hex) — verify JSON structure
        assert!(json.contains("\"v1\""));
        assert!(json.contains("\"v2\":null"));
    }

    #[test]
    fn summary_serializable() {
        let stats = TorrentStats {
            name: "serialize test".to_string(),
            state: TorrentState::Seeding,
            progress: 1.0,
            ..TorrentStats::default()
        };
        let summary = super::TorrentSummary::from(&stats);
        let json =
            serde_json::to_string(&summary).expect("TorrentSummary should serialize to JSON");
        assert!(json.contains("\"name\":\"serialize test\""));
        assert!(json.contains("\"state\":\"Seeding\""));
        assert!(json.contains("\"progress\":1.0"));
    }

    #[test]
    fn test_torrent_summary_includes_seeds_and_totals() {
        let stats = TorrentStats {
            num_seeds: 7,
            all_time_upload: 1_500_000,
            all_time_download: 3_000_000,
            ..TorrentStats::default()
        };

        let summary = super::TorrentSummary::from(&stats);
        assert_eq!(summary.num_seeds, 7);
        assert_eq!(summary.all_time_upload, 1_500_000);
        assert_eq!(summary.all_time_download, 3_000_000);
    }

    #[test]
    fn settings_delta_empty_when_identical() {
        let s = crate::settings::Settings::default();
        let delta = SettingsDelta::from_diff(&s, &s);
        assert!(delta.is_empty());
    }

    #[test]
    fn settings_delta_detects_dht_change() {
        let old = crate::settings::Settings::default();
        let mut new = old.clone();
        new.enable_dht = !old.enable_dht;
        let delta = SettingsDelta::from_diff(&old, &new);
        assert!(!delta.is_empty());
        assert_eq!(delta.enable_dht, Some(new.enable_dht));
        assert!(delta.enable_pex.is_none());
    }

    #[test]
    fn settings_delta_detects_seed_ratio_change() {
        let old = crate::settings::Settings::default();
        let mut new = old.clone();
        new.seed_ratio_limit = Some(2.0);
        let delta = SettingsDelta::from_diff(&old, &new);
        assert!(!delta.is_empty());
        assert_eq!(delta.seed_ratio_limit, Some(Some(2.0)));
    }

    #[test]
    fn settings_delta_detects_encryption_change() {
        let old = crate::settings::Settings::default();
        let mut new = old.clone();
        new.encryption_mode = irontide_wire::mse::EncryptionMode::Forced;
        let delta = SettingsDelta::from_diff(&old, &new);
        assert!(!delta.is_empty());
        assert_eq!(
            delta.encryption_mode,
            Some(irontide_wire::mse::EncryptionMode::Forced)
        );
    }

    #[test]
    fn settings_delta_detects_max_peers_change() {
        let old = crate::settings::Settings::default();
        let mut new = old.clone();
        new.max_peers_per_torrent = 0;
        let delta = SettingsDelta::from_diff(&old, &new);
        assert!(!delta.is_empty());
        assert_eq!(delta.max_peers, Some(0));
    }

    #[test]
    fn settings_delta_detects_max_uploads_per_torrent_change() {
        let old = crate::settings::Settings::default();
        let mut new = old.clone();
        new.max_uploads_per_torrent = 6;
        let delta = SettingsDelta::from_diff(&old, &new);
        assert!(!delta.is_empty());
        assert_eq!(delta.max_uploads_per_torrent, Some(6));
        assert!(delta.max_peers.is_none());
    }

    #[test]
    fn settings_delta_detects_max_uploads_per_torrent_unlimited_change() {
        let old = crate::settings::Settings {
            max_uploads_per_torrent: 4,
            ..crate::settings::Settings::default()
        };
        let mut new = old.clone();
        new.max_uploads_per_torrent = -1;
        let delta = SettingsDelta::from_diff(&old, &new);
        assert!(!delta.is_empty());
        assert_eq!(delta.max_uploads_per_torrent, Some(-1));
    }

    #[test]
    fn torrent_config_from_settings_propagates_max_uploads_per_torrent() {
        let mut s = crate::settings::Settings {
            max_uploads_per_torrent: 7,
            ..crate::settings::Settings::default()
        };
        let cfg = TorrentConfig::from(&s);
        assert_eq!(cfg.max_uploads_per_torrent, 7);

        s.max_uploads_per_torrent = -1;
        let cfg = TorrentConfig::from(&s);
        assert_eq!(cfg.max_uploads_per_torrent, -1);
    }

    #[test]
    fn torrent_stats_holepunch_relayed_default_zero() {
        let stats = TorrentStats::default();
        assert_eq!(stats.holepunch_relayed, 0);
    }

    #[test]
    fn torrent_stats_holepunch_relayed_serializes() {
        let stats = TorrentStats::default();
        let json = serde_json::to_value(&stats).unwrap();
        assert_eq!(json["holepunch_relayed"], 0);
    }
}